From 363d8a6fec07b7539aaf5976a6a502d8b5bd7b55 Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Thu, 15 Oct 2015 10:17:35 -0400 Subject: [PATCH] Remove all _test.go files in Godep --- .../systemstat/example_simple_test.go | 21 - .../bertimus9/systemstat/systemstat_test.go | 35 - .../bertimus9/systemstat/testdata/loadavg | 1 - .../bertimus9/systemstat/testdata/meminfo | 42 - .../bertimus9/systemstat/testdata/procstat0 | 1 - .../bertimus9/systemstat/testdata/procstat1 | 1 - .../bertimus9/systemstat/testdata/procstat2 | 1 - .../bertimus9/systemstat/testdata/procstat3 | 1 - .../bertimus9/systemstat/testdata/procstat5 | 1 - .../bertimus9/systemstat/testdata/procstat6 | 1 - .../bertimus9/systemstat/testdata/stat | 12 - .../bertimus9/systemstat/testdata/stat2 | 12 - .../bertimus9/systemstat/testdata/stat3 | 12 - .../bertimus9/systemstat/testdata/stat4 | 12 - .../bertimus9/systemstat/testdata/stat5 | 12 - .../bertimus9/systemstat/testdata/stat6 | 12 - .../bertimus9/systemstat/testdata/stat7 | 12 - .../bertimus9/systemstat/testdata/uptime | 1 - .../ww/goautoneg/autoneg_test.go | 33 - .../ClusterHQ/flocker-go/client_test.go | 316 - .../github.com/Sirupsen/logrus/entry_test.go | 53 - .../Sirupsen/logrus/formatter_bench_test.go | 88 - .../github.com/Sirupsen/logrus/hook_test.go | 122 - .../hooks/papertrail/papertrail_test.go | 26 - .../logrus/hooks/sentry/sentry_test.go | 97 - .../logrus/hooks/syslog/syslog_test.go | 26 - .../github.com/Sirupsen/logrus/logrus_test.go | 283 - .../Sirupsen/logrus/text_formatter_test.go | 33 - .../abbot/go-http-auth/basic_test.go | 38 - .../abbot/go-http-auth/digest_test.go | 57 - .../abbot/go-http-auth/md5crypt_test.go | 18 - .../abbot/go-http-auth/misc_test.go | 12 - .../abbot/go-http-auth/users_test.go | 33 - .../github.com/appc/spec/schema/image_test.go | 62 - .../github.com/appc/spec/schema/pod_test.go | 73 - .../spec/schema/types/acidentifier_test.go | 279 - .../appc/spec/schema/types/ackind_test.go | 93 - .../appc/spec/schema/types/acname_test.go | 266 - .../spec/schema/types/annotations_test.go | 233 - .../appc/spec/schema/types/app_test.go | 230 - .../appc/spec/schema/types/date_test.go | 80 - .../spec/schema/types/dependencies_test.go | 40 - .../spec/schema/types/environment_test.go | 76 - .../appc/spec/schema/types/exec_test.go | 42 - .../appc/spec/schema/types/hash_test.go | 96 - .../appc/spec/schema/types/isolator_test.go | 262 - .../appc/spec/schema/types/labels_test.go | 108 - .../appc/spec/schema/types/mountpoint_test.go | 83 - .../appc/spec/schema/types/port_test.go | 48 - .../appc/spec/schema/types/semver_test.go | 129 - .../appc/spec/schema/types/url_test.go | 137 - .../appc/spec/schema/types/uuid_test.go | 73 - .../appc/spec/schema/types/volume_test.go | 99 - .../aws/aws-sdk-go/aws/awsutil/copy_test.go | 201 - .../aws-sdk-go/aws/awsutil/path_value_test.go | 68 - .../aws/aws-sdk-go/aws/config_test.go | 80 - .../aws/aws-sdk-go/aws/convert_types_test.go | 437 - .../aws/corehandlers/handlers_test.go | 107 - .../aws/corehandlers/param_validator_test.go | 134 - .../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 | 88 - .../aws/credentials/static_provider_test.go | 34 - .../stscreds/assume_role_provider_test.go | 59 - .../aws-sdk-go/aws/ec2metadata/api_test.go | 100 - .../aws-sdk-go/aws/request/handlers_test.go | 47 - .../aws/request/request_pagination_test.go | 307 - .../aws-sdk-go/aws/request/request_test.go | 228 - .../aws/aws-sdk-go/aws/types_test.go | 56 - .../internal/endpoints/endpoints_test.go | 28 - .../internal/protocol/ec2query/build_test.go | 880 - .../protocol/ec2query/unmarshal_test.go | 836 - .../internal/protocol/query/build_test.go | 1333 -- .../internal/protocol/query/unmarshal_test.go | 1450 -- .../internal/signer/v4/functional_test.go | 43 - .../aws-sdk-go/internal/signer/v4/v4_test.go | 247 - .../autoscalingiface/interface_test.go | 15 - .../service/autoscaling/examples_test.go | 1179 -- .../service/ec2/customizations_test.go | 36 - .../service/ec2/ec2iface/interface_test.go | 15 - .../aws-sdk-go/service/ec2/examples_test.go | 5164 ------ .../service/elb/elbiface/interface_test.go | 15 - .../aws-sdk-go/service/elb/examples_test.go | 721 - .../beorn7/perks/quantile/bench_test.go | 63 - .../beorn7/perks/quantile/example_test.go | 121 - .../beorn7/perks/quantile/stream_test.go | 188 - .../codegangsta/negroni/logger_test.go | 33 - .../codegangsta/negroni/negroni_test.go | 75 - .../codegangsta/negroni/recovery_test.go | 28 - .../negroni/response_writer_test.go | 150 - .../codegangsta/negroni/static_test.go | 113 - .../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_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 - .../coreos/go-oidc/http/http_test.go | 380 - .../coreos/go-oidc/http/url_test.go | 49 - .../coreos/go-oidc/jose/claims_test.go | 240 - .../coreos/go-oidc/jose/jwk_test.go | 64 - .../coreos/go-oidc/jose/jws_test.go | 74 - .../coreos/go-oidc/jose/jwt_test.go | 94 - .../coreos/go-oidc/jose/sig_hmac_test.go | 85 - .../github.com/coreos/go-oidc/key/key_test.go | 68 - .../coreos/go-oidc/key/manager_test.go | 225 - .../coreos/go-oidc/key/rotate_test.go | 311 - .../coreos/go-oidc/key/sync_test.go | 205 - .../coreos/go-oidc/oauth2/error_test.go | 79 - .../coreos/go-oidc/oauth2/oauth2_test.go | 262 - .../coreos/go-oidc/oidc/client_test.go | 367 - .../coreos/go-oidc/oidc/identity_test.go | 113 - .../coreos/go-oidc/oidc/provider_test.go | 466 - .../coreos/go-oidc/oidc/transport_test.go | 167 - .../coreos/go-oidc/oidc/util_test.go | 95 - .../coreos/go-oidc/oidc/verification_test.go | 297 - .../coreos/go-semver/semver/semver_test.go | 187 - .../coreos/go-systemd/dbus/dbus_test.go | 79 - .../coreos/go-systemd/dbus/methods_test.go | 332 - .../coreos/go-systemd/dbus/set_test.go | 39 - .../go-systemd/dbus/subscription_set_test.go | 66 - .../go-systemd/dbus/subscription_test.go | 91 - .../go-systemd/unit/deserialize_test.go | 301 - .../coreos/go-systemd/unit/option_test.go | 200 - .../coreos/go-systemd/unit/serialize_test.go | 134 - .../coreos/pkg/health/health_test.go | 198 - .../coreos/pkg/httputil/json_test.go | 56 - .../coreos/pkg/timeutil/backoff_test.go | 52 - .../davecgh/go-spew/spew/common_test.go | 298 - .../davecgh/go-spew/spew/dump_test.go | 1021 - .../davecgh/go-spew/spew/dumpcgo_test.go | 97 - .../davecgh/go-spew/spew/dumpnocgo_test.go | 26 - .../davecgh/go-spew/spew/example_test.go | 230 - .../davecgh/go-spew/spew/format_test.go | 1535 -- .../davecgh/go-spew/spew/internal_test.go | 156 - .../davecgh/go-spew/spew/spew_test.go | 308 - .../davecgh/go-spew/spew/testdata/dumpcgo.go | 82 - .../daviddengcn/go-colortext/ct_test.go | 26 - .../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 - .../github.com/dgrijalva/jwt-go/rsa_test.go | 174 - .../pkg/jsonmessage/jsonmessage_test.go | 210 - .../docker/docker/pkg/mount/mount_test.go | 137 - .../docker/pkg/mount/mountinfo_linux_test.go | 477 - .../pkg/mount/sharedsubtree_linux_test.go | 331 - .../docker/pkg/parsers/filters/parse_test.go | 78 - .../docker/pkg/parsers/kernel/kernel_test.go | 61 - .../operatingsystem/operatingsystem_test.go | 124 - .../docker/docker/pkg/parsers/parsers_test.go | 157 - .../term/winconsole/console_windows_test.go | 232 - .../pkg/term/winconsole/term_emulator_test.go | 388 - .../docker/docker/pkg/timeutils/json_test.go | 47 - .../docker/docker/pkg/timeutils/utils_test.go | 44 - .../docker/docker/pkg/units/duration_test.go | 46 - .../docker/docker/pkg/units/size_test.go | 108 - .../libcontainer/cgroups/cgroups_test.go | 27 - .../libcontainer/cgroups/fs/blkio_test.go | 473 - .../libcontainer/cgroups/fs/cpu_test.go | 139 - .../libcontainer/cgroups/fs/cpuset_test.go | 63 - .../libcontainer/cgroups/fs/devices_test.go | 46 - .../libcontainer/cgroups/fs/freezer_test.go | 45 - .../libcontainer/cgroups/fs/memory_test.go | 259 - .../cgroups/fs/stats_util_test.go | 97 - .../libcontainer/cgroups/fs/util_test.go | 64 - .../libcontainer/cgroups/fs/utils_test.go | 95 - .../libcontainer/configs/config_test.go | 249 - .../libcontainer/container_linux_test.go | 201 - .../libcontainer/devices/devices_test.go | 61 - .../docker/libcontainer/error_test.go | 20 - .../docker/libcontainer/factory_linux_test.go | 179 - .../docker/libcontainer/generic_error_test.go | 14 - .../libcontainer/integration/exec_test.go | 615 - .../libcontainer/integration/execin_test.go | 338 - .../libcontainer/integration/init_test.go | 27 - .../libcontainer/integration/template_test.go | 118 - .../libcontainer/integration/utils_test.go | 133 - .../libcontainer/label/label_selinux_test.go | 108 - .../netlink/netlink_linux_test.go | 408 - .../docker/libcontainer/notify_linux_test.go | 96 - .../libcontainer/nsenter/nsenter_test.go | 91 - .../libcontainer/selinux/selinux_test.go | 64 - .../libcontainer/stacktrace/capture_test.go | 27 - .../libcontainer/stacktrace/frame_test.go | 20 - .../docker/libcontainer/user/user_test.go | 352 - .../docker/libcontainer/utils/utils_test.go | 15 - .../github.com/Sirupsen/logrus/entry_test.go | 53 - .../Sirupsen/logrus/formatter_bench_test.go | 88 - .../github.com/Sirupsen/logrus/hook_test.go | 122 - .../hooks/papertrail/papertrail_test.go | 26 - .../logrus/hooks/sentry/sentry_test.go | 97 - .../logrus/hooks/syslog/syslog_test.go | 26 - .../Sirupsen/logrus/json_formatter_test.go | 120 - .../github.com/Sirupsen/logrus/logrus_test.go | 301 - .../Sirupsen/logrus/text_formatter_test.go | 37 - .../github.com/codegangsta/cli/app_test.go | 399 - .../github.com/codegangsta/cli/cli_test.go | 88 - .../codegangsta/cli/command_test.go | 48 - .../codegangsta/cli/context_test.go | 68 - .../github.com/codegangsta/cli/flag_test.go | 194 - .../codegangsta/cli/helpers_test.go | 19 - .../go-systemd/activation/files_test.go | 84 - .../go-systemd/activation/listeners_test.go | 88 - .../coreos/go-systemd/dbus/dbus_test.go | 41 - .../coreos/go-systemd/dbus/methods_test.go | 332 - .../coreos/go-systemd/dbus/set_test.go | 39 - .../go-systemd/dbus/subscription_set_test.go | 66 - .../go-systemd/dbus/subscription_test.go | 91 - .../coreos/go-systemd/login1/dbus_test.go | 30 - .../src/github.com/godbus/dbus/conn_test.go | 199 - .../github.com/godbus/dbus/examples_test.go | 50 - .../src/github.com/godbus/dbus/proto_test.go | 369 - .../src/github.com/godbus/dbus/sig_test.go | 70 - .../godbus/dbus/transport_unix_test.go | 49 - .../github.com/godbus/dbus/variant_test.go | 78 - .../capability/capability_test.go | 83 - .../docker/libcontainer/xattr/xattr_test.go | 77 - .../docker/spdystream/priority_test.go | 108 - .../docker/spdystream/spdy/spdy_test.go | 644 - .../docker/spdystream/spdy_bench_test.go | 113 - .../github.com/docker/spdystream/spdy_test.go | 909 - .../docker/spdystream/ws/ws_test.go | 175 - .../elazarl/goproxy/counterecryptor_test.go | 99 - .../goproxy-jquery-version/jquery_test.go | 118 - .../elazarl/goproxy/ext/auth/basic_test.go | 175 - .../elazarl/goproxy/ext/html/html_test.go | 60 - .../github.com/elazarl/goproxy/proxy_test.go | 767 - .../goproxy/regretable/regretreader_test.go | 174 - .../github.com/elazarl/goproxy/signer_test.go | 87 - .../emicklei/go-restful/bench_curly_test.go | 51 - .../emicklei/go-restful/bench_test.go | 43 - .../emicklei/go-restful/compress_test.go | 127 - .../emicklei/go-restful/container_test.go | 21 - .../emicklei/go-restful/cors_filter_test.go | 125 - .../emicklei/go-restful/curly_test.go | 231 - .../emicklei/go-restful/doc_examples_test.go | 35 - .../go-restful/examples/restful-route_test.go | 39 - .../examples/restful-routefunction_test.go | 29 - .../emicklei/go-restful/filter_test.go | 141 - .../emicklei/go-restful/jsr311_test.go | 212 - .../go-restful/options_filter_test.go | 34 - .../go-restful/path_expression_test.go | 37 - .../emicklei/go-restful/request_test.go | 204 - .../emicklei/go-restful/response_test.go | 176 - .../emicklei/go-restful/route_builder_test.go | 58 - .../emicklei/go-restful/route_test.go | 127 - .../go-restful/swagger/model_builder_test.go | 1111 -- .../go-restful/swagger/model_list_test.go | 48 - .../swagger/model_property_ext_test.go | 46 - .../swagger/model_property_list_test.go | 47 - .../swagger/ordered_route_map_test.go | 29 - .../swagger/postbuild_model_test.go | 42 - .../go-restful/swagger/swagger_test.go | 150 - .../emicklei/go-restful/swagger/utils_test.go | 65 - .../emicklei/go-restful/tracer_test.go | 18 - .../emicklei/go-restful/web_service_test.go | 218 - .../evanphx/json-patch/merge_test.go | 322 - .../evanphx/json-patch/patch_test.go | 234 - .../fsouza/go-dockerclient/auth_test.go | 91 - .../fsouza/go-dockerclient/build_test.go | 154 - .../fsouza/go-dockerclient/change_test.go | 26 - .../fsouza/go-dockerclient/client_test.go | 460 - .../fsouza/go-dockerclient/container_test.go | 1982 -- .../fsouza/go-dockerclient/env_test.go | 351 - .../fsouza/go-dockerclient/event_test.go | 132 - .../fsouza/go-dockerclient/example_test.go | 168 - .../fsouza/go-dockerclient/exec_test.go | 262 - .../github.com/Sirupsen/logrus/entry_test.go | 53 - .../Sirupsen/logrus/formatter_bench_test.go | 98 - .../github.com/Sirupsen/logrus/hook_test.go | 122 - .../Sirupsen/logrus/json_formatter_test.go | 120 - .../github.com/Sirupsen/logrus/logrus_test.go | 301 - .../Sirupsen/logrus/text_formatter_test.go | 61 - .../docker/docker/opts/envfile_test.go | 133 - .../github.com/docker/docker/opts/ip_test.go | 54 - .../docker/docker/opts/opts_test.go | 479 - .../docker/docker/opts/ulimit_test.go | 42 - .../docker/docker/pkg/archive/archive_test.go | 1204 -- .../docker/pkg/archive/archive_unix_test.go | 60 - .../pkg/archive/archive_windows_test.go | 65 - .../docker/pkg/archive/changes_posix_test.go | 127 - .../docker/docker/pkg/archive/changes_test.go | 495 - .../docker/docker/pkg/archive/copy_test.go | 637 - .../docker/docker/pkg/archive/diff_test.go | 190 - .../docker/docker/pkg/archive/utils_test.go | 166 - .../docker/docker/pkg/archive/wrap_test.go | 98 - .../docker/pkg/fileutils/fileutils_test.go | 402 - .../docker/docker/pkg/homedir/homedir_test.go | 24 - .../docker/docker/pkg/ioutils/fmt_test.go | 17 - .../docker/pkg/ioutils/multireader_test.go | 149 - .../docker/docker/pkg/ioutils/readers_test.go | 216 - .../docker/docker/pkg/ioutils/writers_test.go | 65 - .../docker/docker/pkg/mflag/flag_test.go | 516 - .../docker/docker/pkg/parsers/parsers_test.go | 210 - .../docker/docker/pkg/pools/pools_test.go | 162 - .../docker/docker/pkg/stdcopy/stdcopy_test.go | 85 - .../docker/docker/pkg/system/lstat_test.go | 28 - .../docker/pkg/system/meminfo_linux_test.go | 38 - .../docker/docker/pkg/system/stat_test.go | 37 - .../docker/docker/pkg/system/utimes_test.go | 66 - .../docker/docker/pkg/ulimit/ulimit_test.go | 55 - .../docker/docker/pkg/units/duration_test.go | 46 - .../docker/docker/pkg/units/size_test.go | 108 - .../docker/libcontainer/user/user_test.go | 443 - .../gorilla/context/context_test.go | 161 - .../github.com/gorilla/mux/bench_test.go | 21 - .../github.com/gorilla/mux/mux_test.go | 1334 -- .../github.com/gorilla/mux/old_test.go | 714 - .../runc/libcontainer/user/user_test.go | 436 - .../fsouza/go-dockerclient/image_test.go | 973 - .../fsouza/go-dockerclient/misc_test.go | 159 - .../fsouza/go-dockerclient/network_test.go | 96 - .../go-dockerclient/testing/server_test.go | 1843 -- .../fsouza/go-dockerclient/volume_test.go | 142 - .../garyburd/redigo/redis/conn_test.go | 542 - .../garyburd/redigo/redis/pool_test.go | 674 - .../garyburd/redigo/redis/pubsub_test.go | 143 - .../garyburd/redigo/redis/reply_test.go | 166 - .../garyburd/redigo/redis/scan_test.go | 412 - .../garyburd/redigo/redis/script_test.go | 93 - .../garyburd/redigo/redis/test_test.go | 38 - .../redigo/redis/zpop_example_test.go | 113 - .../src/github.com/ghodss/yaml/yaml_test.go | 271 - .../src/github.com/godbus/dbus/conn_test.go | 199 - .../github.com/godbus/dbus/examples_test.go | 50 - .../src/github.com/godbus/dbus/proto_test.go | 369 - .../src/github.com/godbus/dbus/sig_test.go | 70 - .../godbus/dbus/transport_unix_test.go | 49 - .../github.com/godbus/dbus/variant_test.go | 78 - .../gogo/protobuf/proto/all_test.go | 2156 --- .../gogo/protobuf/proto/clone_test.go | 267 - .../gogo/protobuf/proto/equal_test.go | 209 - .../gogo/protobuf/proto/extensions_test.go | 292 - .../gogo/protobuf/proto/message_set_test.go | 66 - .../gogo/protobuf/proto/proto3_test.go | 125 - .../gogo/protobuf/proto/size2_test.go | 63 - .../gogo/protobuf/proto/size_test.go | 147 - .../gogo/protobuf/proto/testdata/Makefile | 37 - .../protobuf/proto/testdata/golden_test.go | 86 - .../gogo/protobuf/proto/testdata/test.pb.go | 2948 --- .../protobuf/proto/testdata/test.pb.go.golden | 1737 -- .../gogo/protobuf/proto/testdata/test.proto | 494 - .../gogo/protobuf/proto/text_parser_test.go | 523 - .../gogo/protobuf/proto/text_test.go | 474 - .../src/github.com/golang/glog/glog_test.go | 415 - .../golang/groupcache/lru/lru_test.go | 73 - .../golang/protobuf/proto/all_test.go | 2059 --- .../golang/protobuf/proto/clone_test.go | 227 - .../golang/protobuf/proto/equal_test.go | 191 - .../golang/protobuf/proto/extensions_test.go | 137 - .../golang/protobuf/proto/message_set_test.go | 66 - .../golang/protobuf/proto/proto3_test.go | 93 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 135 - .../golang/protobuf/proto/testdata/Makefile | 50 - .../protobuf/proto/testdata/golden_test.go | 86 - .../golang/protobuf/proto/testdata/test.pb.go | 2389 --- .../golang/protobuf/proto/testdata/test.proto | 434 - .../golang/protobuf/proto/text_parser_test.go | 509 - .../golang/protobuf/proto/text_test.go | 436 - .../google/cadvisor/api/versions_test.go | 249 - .../cadvisor/cache/memory/memory_test.go | 97 - .../collector/collector_manager_test.go | 75 - .../collector/generic_collector_test.go | 167 - .../collector/prometheus_collector_test.go | 64 - .../google/cadvisor/container/factory_test.go | 158 - .../container/raw/container_hints_test.go | 57 - .../google/cadvisor/events/handler_test.go | 196 - .../github.com/google/cadvisor/fs/fs_test.go | 78 - .../google/cadvisor/info/v1/container_test.go | 79 - .../google/cadvisor/manager/container_test.go | 205 - .../google/cadvisor/manager/manager_test.go | 212 - .../cadvisor/metrics/prometheus_test.go | 164 - .../metrics/testdata/prometheus_metrics | 155 - .../storage/influxdb/influxdb_test.go | 187 - .../google/cadvisor/summary/buffer_test.go | 118 - .../cadvisor/summary/percentiles_test.go | 202 - .../cadvisor/utils/machine/testdata/cpuinfo | 251 - .../cadvisor/utils/machine/topology_test.go | 117 - .../utils/oomparser/oomparser_test.go | 166 - .../cadvisor/utils/sysinfo/sysinfo_test.go | 132 - .../google/cadvisor/utils/timed_store_test.go | 221 - .../github.com/google/gofuzz/example_test.go | 225 - .../src/github.com/google/gofuzz/fuzz_test.go | 384 - .../gorilla/context/context_test.go | 161 - .../src/github.com/gorilla/mux/bench_test.go | 21 - .../src/github.com/gorilla/mux/mux_test.go | 1003 - .../src/github.com/gorilla/mux/old_test.go | 714 - .../github.com/imdario/mergo/mergo_test.go | 288 - .../imdario/mergo/testdata/license.yml | 3 - .../imdario/mergo/testdata/thing.yml | 5 - .../jonboulle/clockwork/clockwork_test.go | 120 - .../jonboulle/clockwork/example_test.go | 49 - .../juju/ratelimit/ratelimit_test.go | 328 - .../github.com/kardianos/osext/osext_test.go | 180 - .../pbutil/all_test.go | 320 - .../pbutil/fixtures_test.go | 103 - .../mesos-go/auth/sasl/authenticatee_test.go | 106 - .../mesos/mesos-go/detector/factory_test.go | 59 - .../mesos-go/detector/standalone_test.go | 169 - .../mesos-go/detector/zoo/detect_test.go | 528 - .../mesos-go/detector/zoo/plugin_test.go | 19 - .../mesos-go/executor/executor_intgr_test.go | 567 - .../mesos/mesos-go/executor/executor_test.go | 418 - .../mesos/mesos-go/mesosproto/logpb_test.go | 3245 ---- .../mesos/mesos-go/mesosproto/mesospb_test.go | 15435 ---------------- .../mesos/mesos-go/mesosproto/statepb_test.go | 1175 -- .../mesos-go/mesosutil/mesosprotoutil_test.go | 252 - .../messenger/http_transporter_test.go | 350 - .../mesos-go/messenger/messenger_test.go | 460 - .../mesos-go/scheduler/schedcache_test.go | 215 - .../scheduler/scheduler_intgr_test.go | 458 - .../mesos-go/scheduler/scheduler_unit_test.go | 550 - .../mesos/mesos-go/upid/upid_test.go | 51 - .../src/github.com/miekg/dns/client_test.go | 195 - .../src/github.com/miekg/dns/dns_test.go | 511 - .../src/github.com/miekg/dns/dnssec_test.go | 672 - .../src/github.com/miekg/dns/dyn_test.go | 3 - .../src/github.com/miekg/dns/edns_test.go | 48 - .../src/github.com/miekg/dns/example_test.go | 147 - .../github.com/miekg/dns/idn/example_test.go | 18 - .../github.com/miekg/dns/idn/punycode_test.go | 94 - .../src/github.com/miekg/dns/labels_test.go | 214 - .../src/github.com/miekg/dns/nsecx_test.go | 33 - .../src/github.com/miekg/dns/parse_test.go | 1276 -- .../github.com/miekg/dns/privaterr_test.go | 169 - .../src/github.com/miekg/dns/server_test.go | 401 - .../src/github.com/miekg/dns/sig0_test.go | 96 - .../src/github.com/miekg/dns/types_test.go | 42 - .../src/github.com/miekg/dns/update_test.go | 105 - .../mapstructure/decode_hooks_test.go | 191 - .../mapstructure_benchmark_test.go | 243 - .../mapstructure/mapstructure_bugs_test.go | 47 - .../mapstructure_examples_test.go | 169 - .../mapstructure/mapstructure_test.go | 828 - .../mxk/go-flowrate/flowrate/io_test.go | 146 - .../ginkgo/ginkgo/nodot/nodot_suite_test.go | 91 - .../onsi/ginkgo/ginkgo/nodot/nodot_test.go | 81 - .../ginkgo/testsuite/testsuite_suite_test.go | 13 - .../ginkgo/ginkgo/testsuite/testsuite_test.go | 167 - .../onsi/ginkgo/integration/convert_test.go | 121 - .../onsi/ginkgo/integration/coverage_test.go | 54 - .../onsi/ginkgo/integration/fail_test.go | 48 - .../onsi/ginkgo/integration/flags_test.go | 176 - .../integration/integration_suite_test.go | 89 - .../onsi/ginkgo/integration/interrupt_test.go | 51 - .../ginkgo/integration/precompiled_test.go | 53 - .../onsi/ginkgo/integration/progress_test.go | 75 - .../onsi/ginkgo/integration/run_test.go | 373 - .../onsi/ginkgo/integration/skip_test.go | 43 - .../ginkgo/integration/subcommand_test.go | 364 - .../ginkgo/integration/suite_command_test.go | 63 - .../ginkgo/integration/suite_setup_test.go | 178 - .../onsi/ginkgo/integration/tags_test.go | 27 - .../integration/test_description_test.go | 25 - .../integration/verbose_and_succinct_test.go | 80 - .../onsi/ginkgo/integration/watch_test.go | 239 - .../codelocation/code_location_suite_test.go | 13 - .../codelocation/code_location_test.go | 79 - .../container_node_suite_test.go | 13 - .../containernode/container_node_test.go | 212 - .../internal/failer/failer_suite_test.go | 13 - .../ginkgo/internal/failer/failer_test.go | 141 - .../ginkgo/internal/leafnodes/it_node_test.go | 22 - .../leafnodes/leaf_node_suite_test.go | 13 - .../internal/leafnodes/measure_node_test.go | 109 - .../internal/leafnodes/setup_nodes_test.go | 40 - .../internal/leafnodes/shared_runner_test.go | 361 - .../internal/leafnodes/suite_nodes_test.go | 230 - .../synchronized_after_suite_node_test.go | 196 - .../synchronized_before_suite_node_test.go | 445 - .../ginkgo/internal/remote/aggregator_test.go | 311 - .../remote/fake_output_interceptor_test.go | 17 - .../internal/remote/fake_poster_test.go | 33 - .../remote/forwarding_reporter_test.go | 180 - .../internal/remote/remote_suite_test.go | 13 - .../ginkgo/internal/remote/server_test.go | 269 - .../internal/spec/index_computer_test.go | 149 - .../ginkgo/internal/spec/spec_suite_test.go | 13 - .../onsi/ginkgo/internal/spec/spec_test.go | 626 - .../onsi/ginkgo/internal/spec/specs_test.go | 335 - .../specrunner/spec_runner_suite_test.go | 13 - .../internal/specrunner/spec_runner_test.go | 623 - .../ginkgo/internal/suite/suite_suite_test.go | 35 - .../onsi/ginkgo/internal/suite/suite_test.go | 399 - .../internal/writer/writer_suite_test.go | 13 - .../ginkgo/internal/writer/writer_test.go | 75 - .../ginkgo/reporters/default_reporter_test.go | 415 - .../ginkgo/reporters/junit_reporter_test.go | 241 - .../ginkgo/reporters/reporters_suite_test.go | 13 - .../reporters/teamcity_reporter_test.go | 213 - .../onsi/ginkgo/types/types_suite_test.go | 13 - .../onsi/ginkgo/types/types_test.go | 81 - .../onsi/gomega/format/format_suite_test.go | 13 - .../onsi/gomega/format/format_test.go | 449 - .../onsi/gomega/gbytes/buffer_test.go | 158 - .../onsi/gomega/gbytes/gbuffer_suite_test.go | 13 - .../onsi/gomega/gbytes/say_matcher_test.go | 163 - .../onsi/gomega/gexec/exit_matcher_test.go | 113 - .../onsi/gomega/gexec/gexec_suite_test.go | 26 - .../onsi/gomega/gexec/prefixed_writer_test.go | 43 - .../onsi/gomega/gexec/session_test.go | 177 - .../gomega/ghttp/test_server_suite_test.go | 13 - .../onsi/gomega/ghttp/test_server_test.go | 591 - .../assertion/assertion_suite_test.go | 13 - .../internal/assertion/assertion_test.go | 252 - .../async_assertion_suite_test.go | 13 - .../asyncassertion/async_assertion_test.go | 345 - .../testingtsupport/testing_t_support_test.go | 12 - .../assignable_to_type_of_matcher_test.go | 30 - .../gomega/matchers/be_closed_matcher_test.go | 70 - .../gomega/matchers/be_empty_matcher_test.go | 52 - .../matchers/be_equivalent_to_matcher_test.go | 50 - .../gomega/matchers/be_false_matcher_test.go | 20 - .../gomega/matchers/be_nil_matcher_test.go | 28 - .../matchers/be_numerically_matcher_test.go | 148 - .../gomega/matchers/be_sent_matcher_test.go | 106 - .../matchers/be_temporally_matcher_test.go | 98 - .../gomega/matchers/be_true_matcher_test.go | 20 - .../gomega/matchers/be_zero_matcher_test.go | 30 - .../onsi/gomega/matchers/consist_of_test.go | 75 - .../matchers/contain_element_matcher_test.go | 72 - .../contain_substring_matcher_test.go | 36 - .../gomega/matchers/equal_matcher_test.go | 44 - .../gomega/matchers/have_key_matcher_test.go | 73 - .../have_key_with_value_matcher_test.go | 82 - .../gomega/matchers/have_len_matcher_test.go | 53 - .../matchers/have_occurred_matcher_test.go | 28 - .../matchers/have_prefix_matcher_test.go | 36 - .../matchers/have_suffix_matcher_test.go | 36 - .../matchers/match_error_matcher_test.go | 93 - .../matchers/match_json_matcher_test.go | 59 - .../matchers/match_regexp_matcher_test.go | 44 - .../matchers/matcher_tests_suite_test.go | 29 - .../gomega/matchers/panic_matcher_test.go | 36 - .../gomega/matchers/receive_matcher_test.go | 280 - .../gomega/matchers/succeed_matcher_test.go | 39 - .../src/github.com/pborman/uuid/json_test.go | 32 - .../src/github.com/pborman/uuid/seq_test.go | 66 - .../src/github.com/pborman/uuid/uuid_test.go | 390 - .../prometheus/benchmark_test.go | 159 - .../client_golang/prometheus/counter_test.go | 58 - .../prometheus/example_clustermanager_test.go | 130 - .../prometheus/example_memstats_test.go | 87 - .../prometheus/example_selfcollector_test.go | 69 - .../client_golang/prometheus/examples_test.go | 649 - .../client_golang/prometheus/expvar_test.go | 97 - .../client_golang/prometheus/gauge_test.go | 182 - .../prometheus/go_collector_test.go | 123 - .../prometheus/histogram_test.go | 326 - .../client_golang/prometheus/http_test.go | 121 - .../client_golang/prometheus/metric_test.go | 35 - .../prometheus/process_collector_test.go | 54 - .../client_golang/prometheus/registry_test.go | 535 - .../client_golang/prometheus/summary_test.go | 347 - .../client_golang/prometheus/vec_test.go | 91 - .../prometheus/common/expfmt/bench_test.go | 171 - .../prometheus/common/expfmt/decode_test.go | 373 - .../common/expfmt/json_decode_test.go | 124 - .../prometheus/common/expfmt/testdata/json2 | 46 - .../common/expfmt/testdata/protobuf | 516 - .../common/expfmt/testdata/protobuf.gz | 129 - .../prometheus/common/expfmt/testdata/test.gz | 163 - .../prometheus/common/expfmt/testdata/text | 322 - .../common/expfmt/text_create_test.go | 443 - .../common/expfmt/text_parse_test.go | 586 - .../prometheus/common/model/labels_test.go | 91 - .../prometheus/common/model/metric_test.go | 83 - .../prometheus/common/model/signature_test.go | 304 - .../prometheus/common/model/time_test.go | 86 - .../prometheus/common/model/value_test.go | 362 - .../github.com/prometheus/procfs/fs_test.go | 13 - .../prometheus/procfs/proc_limits_test.go | 36 - .../prometheus/procfs/proc_stat_test.go | 112 - .../github.com/prometheus/procfs/proc_test.go | 123 - .../github.com/prometheus/procfs/stat_test.go | 19 - .../blockstorage/v1/snapshots_test.go | 70 - .../openstack/blockstorage/v1/volumes_test.go | 63 - .../blockstorage/v1/volumetypes_test.go | 49 - .../acceptance/openstack/client_test.go | 40 - .../compute/v2/bootfromvolume_test.go | 55 - .../openstack/compute/v2/compute_test.go | 104 - .../openstack/compute/v2/extension_test.go | 47 - .../openstack/compute/v2/flavors_test.go | 57 - .../openstack/compute/v2/floatingip_test.go | 107 - .../openstack/compute/v2/images_test.go | 37 - .../openstack/compute/v2/keypairs_test.go | 74 - .../openstack/compute/v2/network_test.go | 78 - .../openstack/compute/v2/secdefrules_test.go | 72 - .../openstack/compute/v2/secgroup_test.go | 177 - .../openstack/compute/v2/servergroup_test.go | 143 - .../openstack/compute/v2/servers_test.go | 484 - .../compute/v2/tenantnetworks_test.go | 109 - .../openstack/compute/v2/volumeattach_test.go | 125 - .../openstack/identity/v2/extension_test.go | 46 - .../openstack/identity/v2/identity_test.go | 47 - .../openstack/identity/v2/role_test.go | 58 - .../openstack/identity/v2/tenant_test.go | 32 - .../openstack/identity/v2/token_test.go | 38 - .../openstack/identity/v2/user_test.go | 127 - .../openstack/identity/v3/endpoint_test.go | 111 - .../openstack/identity/v3/identity_test.go | 39 - .../openstack/identity/v3/service_test.go | 36 - .../openstack/identity/v3/token_test.go | 42 - .../networking/v2/apiversion_test.go | 51 - .../openstack/networking/v2/extension_test.go | 45 - .../v2/extensions/fwaas/firewall_test.go | 116 - .../v2/extensions/fwaas/policy_test.go | 107 - .../v2/extensions/fwaas/rule_test.go | 84 - .../networking/v2/extensions/layer3_test.go | 300 - .../v2/extensions/lbaas/member_test.go | 95 - .../v2/extensions/lbaas/monitor_test.go | 77 - .../v2/extensions/lbaas/pool_test.go | 98 - .../v2/extensions/lbaas/vip_test.go | 101 - .../networking/v2/extensions/provider_test.go | 68 - .../networking/v2/extensions/security_test.go | 171 - .../openstack/networking/v2/network_test.go | 68 - .../openstack/networking/v2/port_test.go | 117 - .../openstack/networking/v2/subnet_test.go | 86 - .../objectstorage/v1/accounts_test.go | 50 - .../objectstorage/v1/containers_test.go | 137 - .../objectstorage/v1/objects_test.go | 119 - .../orchestration/v1/buildinfo_test.go | 20 - .../orchestration/v1/stackevents_test.go | 68 - .../orchestration/v1/stackresources_test.go | 62 - .../openstack/orchestration/v1/stacks_test.go | 81 - .../orchestration/v1/stacktemplates_test.go | 77 - .../blockstorage/v1/snapshot_test.go | 82 - .../rackspace/blockstorage/v1/volume_test.go | 71 - .../blockstorage/v1/volume_type_test.go | 46 - .../acceptance/rackspace/cdn/v1/base_test.go | 32 - .../rackspace/cdn/v1/flavor_test.go | 47 - .../rackspace/cdn/v1/service_test.go | 93 - .../rackspace/cdn/v1/serviceasset_test.go | 32 - .../acceptance/rackspace/client_test.go | 28 - .../compute/v2/bootfromvolume_test.go | 49 - .../rackspace/compute/v2/compute_test.go | 60 - .../rackspace/compute/v2/flavors_test.go | 61 - .../rackspace/compute/v2/images_test.go | 63 - .../rackspace/compute/v2/keypairs_test.go | 87 - .../rackspace/compute/v2/networks_test.go | 53 - .../rackspace/compute/v2/servers_test.go | 217 - .../compute/v2/virtualinterfaces_test.go | 53 - .../rackspace/compute/v2/volumeattach_test.go | 130 - .../rackspace/identity/v2/extension_test.go | 54 - .../rackspace/identity/v2/identity_test.go | 50 - .../rackspace/identity/v2/role_test.go | 59 - .../rackspace/identity/v2/tenant_test.go | 37 - .../rackspace/identity/v2/tokens_test.go | 61 - .../rackspace/identity/v2/user_test.go | 93 - .../acceptance/rackspace/lb/v1/acl_test.go | 94 - .../acceptance/rackspace/lb/v1/lb_test.go | 214 - .../rackspace/lb/v1/monitor_test.go | 60 - .../acceptance/rackspace/lb/v1/node_test.go | 175 - .../rackspace/lb/v1/session_test.go | 47 - .../rackspace/lb/v1/throttle_test.go | 53 - .../acceptance/rackspace/lb/v1/vip_test.go | 83 - .../rackspace/networking/v2/network_test.go | 65 - .../rackspace/networking/v2/port_test.go | 116 - .../rackspace/networking/v2/security_test.go | 165 - .../rackspace/networking/v2/subnet_test.go | 84 - .../objectstorage/v1/accounts_test.go | 38 - .../rackspace/objectstorage/v1/bulk_test.go | 23 - .../objectstorage/v1/cdncontainers_test.go | 66 - .../objectstorage/v1/cdnobjects_test.go | 50 - .../objectstorage/v1/containers_test.go | 90 - .../objectstorage/v1/objects_test.go | 124 - .../orchestration/v1/buildinfo_test.go | 20 - .../orchestration/v1/stackevents_test.go | 70 - .../orchestration/v1/stackresources_test.go | 64 - .../rackspace/orchestration/v1/stacks_test.go | 82 - .../orchestration/v1/stacktemplates_test.go | 79 - .../rackconnect/v3/cloudnetworks_test.go | 36 - .../rackspace/rackconnect/v3/lbpools_test.go | 71 - .../rackconnect/v3/publicips_test.go | 45 - .../gophercloud/endpoint_search_test.go | 19 - .../v1/apiversions/requests_test.go | 145 - .../blockstorage/v1/apiversions/urls_test.go | 26 - .../v1/snapshots/requests_test.go | 104 - .../blockstorage/v1/snapshots/urls_test.go | 50 - .../blockstorage/v1/volumes/requests_test.go | 123 - .../blockstorage/v1/volumes/urls_test.go | 44 - .../v1/volumetypes/requests_test.go | 118 - .../blockstorage/v1/volumetypes/urls_test.go | 38 - .../openstack/cdn/v1/base/requests_test.go | 43 - .../openstack/cdn/v1/flavors/requests_test.go | 89 - .../cdn/v1/serviceassets/requests_test.go | 18 - .../cdn/v1/services/requests_test.go | 358 - .../gophercloud/openstack/client_test.go | 161 - .../common/extensions/requests_test.go | 38 - .../openstack/common/extensions/urls_test.go | 26 - .../bootfromvolume/requests_test.go | 53 - .../v2/extensions/bootfromvolume/urls_test.go | 16 - .../extensions/defsecrules/requests_test.go | 100 - .../compute/v2/extensions/delegate_test.go | 96 - .../v2/extensions/diskconfig/requests_test.go | 89 - .../v2/extensions/diskconfig/results_test.go | 68 - .../v2/extensions/floatingip/requests_test.go | 80 - .../v2/extensions/floatingip/urls_test.go | 60 - .../v2/extensions/keypairs/requests_test.go | 71 - .../v2/extensions/keypairs/urls_test.go | 40 - .../v2/extensions/networks/requests_test.go | 37 - .../v2/extensions/networks/urls_test.go | 25 - .../schedulerhints/requests_test.go | 130 - .../v2/extensions/secgroups/requests_test.go | 248 - .../extensions/servergroups/requests_test.go | 59 - .../v2/extensions/servergroups/urls_test.go | 42 - .../v2/extensions/startstop/requests_test.go | 30 - .../tenantnetworks/requests_test.go | 37 - .../v2/extensions/tenantnetworks/urls_test.go | 25 - .../extensions/volumeattach/requests_test.go | 94 - .../v2/extensions/volumeattach/urls_test.go | 46 - .../compute/v2/flavors/requests_test.go | 129 - .../openstack/compute/v2/flavors/urls_test.go | 26 - .../compute/v2/images/requests_test.go | 191 - .../openstack/compute/v2/images/urls_test.go | 26 - .../compute/v2/servers/requests_test.go | 373 - .../openstack/compute/v2/servers/urls_test.go | 68 - .../openstack/endpoint_location_test.go | 228 - .../extensions/admin/roles/requests_test.go | 64 - .../identity/v2/extensions/delegate_test.go | 38 - .../identity/v2/tenants/requests_test.go | 29 - .../identity/v2/tokens/requests_test.go | 141 - .../identity/v2/users/requests_test.go | 165 - .../identity/v3/endpoints/requests_test.go | 226 - .../identity/v3/endpoints/urls_test.go | 23 - .../identity/v3/roles/requests_test.go | 104 - .../openstack/identity/v3/roles/urls_test.go | 15 - .../identity/v3/services/requests_test.go | 209 - .../identity/v3/services/urls_test.go | 23 - .../identity/v3/tokens/requests_test.go | 514 - .../openstack/identity/v3/tokens/urls_test.go | 21 - .../v2/apiversions/requests_test.go | 182 - .../networking/v2/apiversions/urls_test.go | 26 - .../networking/v2/extensions/delegate_test.go | 105 - .../v2/extensions/external/results_test.go | 254 - .../fwaas/firewalls/requests_test.go | 246 - .../fwaas/policies/requests_test.go | 279 - .../extensions/fwaas/rules/requests_test.go | 328 - .../layer3/floatingips/requests_test.go | 355 - .../layer3/routers/requests_test.go | 338 - .../extensions/lbaas/members/requests_test.go | 243 - .../lbaas/monitors/requests_test.go | 312 - .../extensions/lbaas/pools/requests_test.go | 318 - .../v2/extensions/lbaas/vips/requests_test.go | 336 - .../v2/extensions/provider/results_test.go | 253 - .../security/groups/requests_test.go | 213 - .../security/rules/requests_test.go | 243 - .../networking/v2/networks/requests_test.go | 276 - .../networking/v2/networks/urls_test.go | 38 - .../networking/v2/ports/requests_test.go | 321 - .../networking/v2/ports/urls_test.go | 44 - .../networking/v2/subnets/requests_test.go | 362 - .../networking/v2/subnets/results_test.go | 54 - .../networking/v2/subnets/urls_test.go | 44 - .../v1/accounts/requests_test.go | 32 - .../objectstorage/v1/accounts/urls_test.go | 26 - .../v1/containers/requests_test.go | 117 - .../objectstorage/v1/containers/urls_test.go | 43 - .../objectstorage/v1/objects/requests_test.go | 165 - .../objectstorage/v1/objects/urls_test.go | 56 - .../v1/apiversions/requests_test.go | 89 - .../v1/buildinfo/requests_test.go | 20 - .../v1/stackevents/requests_test.go | 71 - .../v1/stackresources/requests_test.go | 107 - .../orchestration/v1/stacks/requests_test.go | 217 - .../v1/stacktemplates/requests_test.go | 57 - .../openstack/utils/choose_version_test.go | 118 - .../gophercloud/pagination/linked_test.go | 120 - .../gophercloud/pagination/marker_test.go | 126 - .../gophercloud/pagination/pagination_test.go | 13 - .../gophercloud/pagination/single_test.go | 84 - .../rackspace/gophercloud/params_test.go | 165 - .../gophercloud/provider_client_test.go | 35 - .../v1/snapshots/delegate_test.go | 97 - .../blockstorage/v1/volumes/delegate_test.go | 107 - .../v1/volumetypes/delegate_test.go | 64 - .../rackspace/cdn/v1/base/delegate_test.go | 44 - .../rackspace/cdn/v1/flavors/delegate_test.go | 90 - .../cdn/v1/serviceassets/delegate_test.go | 19 - .../cdn/v1/services/delegate_test.go | 359 - .../gophercloud/rackspace/client_test.go | 38 - .../v2/bootfromvolume/delegate_test.go | 54 - .../compute/v2/flavors/delegate_test.go | 62 - .../compute/v2/images/delegate_test.go | 62 - .../compute/v2/keypairs/delegate_test.go | 72 - .../compute/v2/networks/requests_test.go | 156 - .../compute/v2/networks/urls_test.go | 38 - .../compute/v2/servers/delegate_test.go | 182 - .../compute/v2/servers/requests_test.go | 59 - .../v2/virtualinterfaces/requests_test.go | 165 - .../compute/v2/virtualinterfaces/urls_test.go | 32 - .../compute/v2/volumeattach/delegate_test.go | 95 - .../identity/v2/extensions/delegate_test.go | 39 - .../identity/v2/roles/delegate_test.go | 66 - .../identity/v2/tenants/delegate_test.go | 28 - .../identity/v2/tokens/delegate_test.go | 36 - .../identity/v2/users/delegate_test.go | 111 - .../rackspace/lb/v1/acl/requests_test.go | 91 - .../rackspace/lb/v1/lbs/requests_test.go | 438 - .../rackspace/lb/v1/monitors/requests_test.go | 75 - .../rackspace/lb/v1/nodes/requests_test.go | 243 - .../rackspace/lb/v1/sessions/requests_test.go | 44 - .../rackspace/lb/v1/ssl/requests_test.go | 167 - .../rackspace/lb/v1/throttle/requests_test.go | 44 - .../rackspace/lb/v1/vips/requests_test.go | 87 - .../networking/v2/networks/delegate_test.go | 285 - .../networking/v2/ports/delegate_test.go | 322 - .../v2/security/groups/delegate_test.go | 206 - .../v2/security/rules/delegate_test.go | 236 - .../networking/v2/subnets/delegate_test.go | 363 - .../v1/accounts/delegate_test.go | 32 - .../objectstorage/v1/bulk/requests_test.go | 36 - .../objectstorage/v1/bulk/urls_test.go | 26 - .../v1/cdncontainers/delegate_test.go | 50 - .../v1/cdncontainers/requests_test.go | 29 - .../v1/cdncontainers/urls_test.go | 20 - .../v1/cdnobjects/delegate_test.go | 19 - .../v1/containers/delegate_test.go | 91 - .../objectstorage/v1/objects/delegate_test.go | 127 - .../v1/buildinfo/delegate_test.go | 21 - .../v1/stackevents/delegate_test.go | 72 - .../v1/stackresources/delegate_test.go | 108 - .../orchestration/v1/stacks/delegate_test.go | 461 - .../v1/stacktemplates/delegate_test.go | 58 - .../v3/cloudnetworks/requests_test.go | 87 - .../rackconnect/v3/lbpools/requests_test.go | 876 - .../rackconnect/v3/publicips/requests_test.go | 378 - .../gophercloud/service_client_test.go | 14 - .../rackspace/gophercloud/util_test.go | 14 - .../russross/blackfriday/block_test.go | 1296 -- .../russross/blackfriday/inline_test.go | 859 - .../russross/blackfriday/upskirtref_test.go | 128 - .../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 - .../scalingdata/gcfg/example_test.go | 132 - .../scalingdata/gcfg/issues_test.go | 63 - .../github.com/scalingdata/gcfg/read_test.go | 333 - .../scalingdata/gcfg/scanner/example_test.go | 46 - .../scalingdata/gcfg/scanner/scanner_test.go | 417 - .../scalingdata/gcfg/testdata/gcfg_test.gcfg | 3 - .../gcfg/testdata/gcfg_unicode_test.gcfg | 3 - .../scalingdata/gcfg/token/position_test.go | 181 - .../scalingdata/gcfg/token/serialize_test.go | 111 - .../scalingdata/gcfg/types/enum_test.go | 29 - .../scalingdata/gcfg/types/int_test.go | 67 - .../scalingdata/gcfg/types/scan_test.go | 36 - .../sanitized_anchor_name/main_test.go | 35 - .../skynetservices/skydns/msg/service_test.go | 137 - .../spf13/cobra/bash_completions_test.go | 87 - .../src/github.com/spf13/cobra/cobra_test.go | 1058 -- .../github.com/spf13/cobra/command_test.go | 114 - .../github.com/spf13/cobra/examples_test.go | 34 - .../github.com/spf13/cobra/man_docs_test.go | 68 - .../github.com/spf13/cobra/md_docs_test.go | 67 - .../src/github.com/spf13/pflag/bool_test.go | 180 - .../src/github.com/spf13/pflag/count_test.go | 55 - .../github.com/spf13/pflag/example_test.go | 77 - .../src/github.com/spf13/pflag/export_test.go | 29 - .../src/github.com/spf13/pflag/flag_test.go | 874 - .../github.com/spf13/pflag/golangflag_test.go | 39 - .../github.com/spf13/pflag/int_slice_test.go | 162 - .../src/github.com/spf13/pflag/ip_test.go | 63 - .../src/github.com/spf13/pflag/ipnet_test.go | 70 - .../spf13/pflag/string_slice_test.go | 141 - .../stretchr/objx/accessors_test.go | 145 - .../stretchr/objx/conversions_test.go | 94 - .../github.com/stretchr/objx/fixture_test.go | 98 - .../github.com/stretchr/objx/map_for_test.go | 10 - .../src/github.com/stretchr/objx/map_test.go | 147 - .../stretchr/objx/mutations_test.go | 77 - .../github.com/stretchr/objx/security_test.go | 12 - .../stretchr/objx/simple_example_test.go | 41 - .../github.com/stretchr/objx/tests_test.go | 24 - .../objx/type_specific_codegen_test.go | 2867 --- .../github.com/stretchr/objx/value_test.go | 1 - .../testify/assert/assertions_test.go | 813 - .../testify/assert/forward_assertions_test.go | 511 - .../testify/assert/http_assertions_test.go | 86 - .../stretchr/testify/mock/mock_test.go | 908 - .../require/forward_requirements_test.go | 260 - .../testify/require/requirements_test.go | 266 - .../capability/capability_test.go | 83 - .../github.com/ugorji/go/codec/cbor_test.go | 205 - .../github.com/ugorji/go/codec/codec_test.go | 1175 -- .../ugorji/go/codec/codecgen_test.go | 23 - .../github.com/ugorji/go/codec/helper_test.go | 155 - .../src/github.com/ugorji/go/codec/py_test.go | 30 - .../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 - .../xyproto/simpleredis/simpleredis_test.go | 66 - .../x/crypto/ssh/agent/client_test.go | 278 - .../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 | 156 - .../golang.org/x/crypto/ssh/cipher_test.go | 64 - .../x/crypto/ssh/client_auth_test.go | 393 - .../golang.org/x/crypto/ssh/client_test.go | 39 - .../golang.org/x/crypto/ssh/example_test.go | 211 - .../golang.org/x/crypto/ssh/handshake_test.go | 311 - .../src/golang.org/x/crypto/ssh/kex_test.go | 48 - .../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 | 244 - .../src/golang.org/x/crypto/ssh/mux_test.go | 525 - .../golang.org/x/crypto/ssh/session_test.go | 680 - .../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 | 50 - .../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 | 321 - .../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 - .../x/exp/inotify/inotify_linux_test.go | 107 - .../golang.org/x/net/context/context_test.go | 575 - .../x/net/context/ctxhttp/ctxhttp_test.go | 72 - .../x/net/context/withtimeout_test.go | 26 - .../golang.org/x/net/html/atom/atom_test.go | 109 - .../golang.org/x/net/html/atom/table_test.go | 351 - .../x/net/html/charset/charset_test.go | 236 - .../html/charset/testdata/HTTP-charset.html | 48 - .../charset/testdata/HTTP-vs-UTF-8-BOM.html | 48 - .../testdata/HTTP-vs-meta-charset.html | 49 - .../testdata/HTTP-vs-meta-content.html | 49 - .../testdata/No-encoding-declaration.html | 47 - .../x/net/html/charset/testdata/README | 9 - .../html/charset/testdata/UTF-16BE-BOM.html | Bin 2670 -> 0 bytes .../html/charset/testdata/UTF-16LE-BOM.html | Bin 2682 -> 0 bytes .../testdata/UTF-8-BOM-vs-meta-charset.html | 49 - .../testdata/UTF-8-BOM-vs-meta-content.html | 48 - .../testdata/meta-charset-attribute.html | 48 - .../testdata/meta-content-attribute.html | 48 - .../src/golang.org/x/net/html/entity_test.go | 29 - .../src/golang.org/x/net/html/escape_test.go | 97 - .../src/golang.org/x/net/html/example_test.go | 40 - .../src/golang.org/x/net/html/node_test.go | 146 - .../src/golang.org/x/net/html/parse_test.go | 388 - .../src/golang.org/x/net/html/render_test.go | 156 - .../golang.org/x/net/html/testdata/go1.html | 2237 --- .../x/net/html/testdata/webkit/README | 28 - .../x/net/html/testdata/webkit/adoption01.dat | 194 - .../x/net/html/testdata/webkit/adoption02.dat | 31 - .../x/net/html/testdata/webkit/comments01.dat | 135 - .../x/net/html/testdata/webkit/doctype01.dat | 370 - .../x/net/html/testdata/webkit/entities01.dat | 603 - .../x/net/html/testdata/webkit/entities02.dat | 249 - .../html/testdata/webkit/html5test-com.dat | 246 - .../x/net/html/testdata/webkit/inbody01.dat | 43 - .../x/net/html/testdata/webkit/isindex.dat | 40 - ...pending-spec-changes-plain-text-unsafe.dat | Bin 115 -> 0 bytes .../testdata/webkit/pending-spec-changes.dat | 52 - .../testdata/webkit/plain-text-unsafe.dat | Bin 4166 -> 0 bytes .../net/html/testdata/webkit/scriptdata01.dat | 308 - .../testdata/webkit/scripted/adoption01.dat | 15 - .../testdata/webkit/scripted/webkit01.dat | 28 - .../x/net/html/testdata/webkit/tables01.dat | 212 - .../x/net/html/testdata/webkit/tests1.dat | 1952 -- .../x/net/html/testdata/webkit/tests10.dat | 799 - .../x/net/html/testdata/webkit/tests11.dat | 482 - .../x/net/html/testdata/webkit/tests12.dat | 62 - .../x/net/html/testdata/webkit/tests14.dat | 74 - .../x/net/html/testdata/webkit/tests15.dat | 208 - .../x/net/html/testdata/webkit/tests16.dat | 2299 --- .../x/net/html/testdata/webkit/tests17.dat | 153 - .../x/net/html/testdata/webkit/tests18.dat | 269 - .../x/net/html/testdata/webkit/tests19.dat | 1237 -- .../x/net/html/testdata/webkit/tests2.dat | 763 - .../x/net/html/testdata/webkit/tests20.dat | 455 - .../x/net/html/testdata/webkit/tests21.dat | 221 - .../x/net/html/testdata/webkit/tests22.dat | 157 - .../x/net/html/testdata/webkit/tests23.dat | 155 - .../x/net/html/testdata/webkit/tests24.dat | 79 - .../x/net/html/testdata/webkit/tests25.dat | 219 - .../x/net/html/testdata/webkit/tests26.dat | 313 - .../x/net/html/testdata/webkit/tests3.dat | 305 - .../x/net/html/testdata/webkit/tests4.dat | 59 - .../x/net/html/testdata/webkit/tests5.dat | 191 - .../x/net/html/testdata/webkit/tests6.dat | 663 - .../x/net/html/testdata/webkit/tests7.dat | 390 - .../x/net/html/testdata/webkit/tests8.dat | 148 - .../x/net/html/testdata/webkit/tests9.dat | 457 - .../testdata/webkit/tests_innerHTML_1.dat | 741 - .../x/net/html/testdata/webkit/tricky01.dat | 261 - .../x/net/html/testdata/webkit/webkit01.dat | 610 - .../x/net/html/testdata/webkit/webkit02.dat | 159 - .../src/golang.org/x/net/html/token_test.go | 748 - .../x/net/websocket/exampledial_test.go | 31 - .../x/net/websocket/examplehandler_test.go | 26 - .../golang.org/x/net/websocket/hybi_test.go | 608 - .../x/net/websocket/websocket_test.go | 587 - .../clientcredentials_test.go | 96 - .../src/golang.org/x/oauth2/example_test.go | 45 - .../x/oauth2/google/example_test.go | 150 - .../golang.org/x/oauth2/google/google_test.go | 67 - .../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 - .../golang.org/x/oauth2/jwt/example_test.go | 31 - .../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 - .../x/tools/go/ast/astutil/enclosing_test.go | 195 - .../x/tools/go/ast/astutil/imports_test.go | 946 - .../golang.org/x/tools/imports/fix_test.go | 862 - .../api/googleapi/googleapi_test.go | 598 - .../api/googleapi/types_test.go | 44 - .../natefinch/lumberjack.v2/example_test.go | 18 - .../natefinch/lumberjack.v2/linux_test.go | 104 - .../lumberjack.v2/lumberjack_test.go | 690 - .../natefinch/lumberjack.v2/rotate_test.go | 27 - .../natefinch/lumberjack.v2/testing_test.go | 91 - .../src/gopkg.in/yaml.v2/decode_test.go | 902 - .../src/gopkg.in/yaml.v2/encode_test.go | 434 - .../src/gopkg.in/yaml.v2/suite_test.go | 12 - .../go/exp/math/dec/inf/benchmark_test.go | 210 - .../go/exp/math/dec/inf/dec_go1_2_test.go | 33 - .../go/exp/math/dec/inf/dec_internal_test.go | 40 - .../go/exp/math/dec/inf/dec_test.go | 379 - .../go/exp/math/dec/inf/example_test.go | 62 - .../exp/math/dec/inf/rounder_example_test.go | 72 - .../go/exp/math/dec/inf/rounder_test.go | 109 - hack/verify-godeps.sh | 2 +- 1048 files changed, 1 insertion(+), 221777 deletions(-) delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/example_simple_test.go delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/systemstat_test.go delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/loadavg delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/meminfo delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat0 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat1 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat2 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat3 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat5 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat6 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat2 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat3 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat4 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat5 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat6 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat7 delete mode 100644 Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/uptime delete mode 100644 Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go delete mode 100644 Godeps/_workspace/src/github.com/ClusterHQ/flocker-go/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go delete mode 100644 Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go delete mode 100644 Godeps/_workspace/src/github.com/abbot/go-http-auth/basic_test.go delete mode 100644 Godeps/_workspace/src/github.com/abbot/go-http-auth/digest_test.go delete mode 100644 Godeps/_workspace/src/github.com/abbot/go-http-auth/md5crypt_test.go delete mode 100644 Godeps/_workspace/src/github.com/abbot/go-http-auth/misc_test.go delete mode 100644 Godeps/_workspace/src/github.com/abbot/go-http-auth/users_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/image_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/pod_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/acidentifier_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/ackind_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/acname_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/annotations_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/app_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/date_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/dependencies_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/environment_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/exec_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/hash_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/isolator_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/labels_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/mountpoint_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/port_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/semver_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/url_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/uuid_test.go delete mode 100644 Godeps/_workspace/src/github.com/appc/spec/schema/types/volume_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 delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.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 delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_test.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/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/autoscaling/autoscalingiface/interface_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/examples_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/elb/elbiface/interface_test.go delete mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/negroni/logger_test.go delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/negroni/negroni_test.go delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/negroni/recovery_test.go delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/negroni/response_writer_test.go delete mode 100644 Godeps/_workspace/src/github.com/codegangsta/negroni/static_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/coreos/go-oidc/http/http_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/http/url_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/jose/claims_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwk_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jws_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwt_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/jose/sig_hmac_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/key/key_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/key/manager_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/key/rotate_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/key/sync_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/error_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/oauth2_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/identity_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/transport_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/util_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/verification_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-semver/semver/semver_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/unit/deserialize_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/unit/option_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/go-systemd/unit/serialize_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/pkg/health/health_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/pkg/httputil/json_test.go delete mode 100644 Godeps/_workspace/src/github.com/coreos/pkg/timeutil/backoff_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/spew_test.go delete mode 100644 Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go delete mode 100644 Godeps/_workspace/src/github.com/daviddengcn/go-colortext/ct_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_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/jsonmessage/jsonmessage_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/json_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/units/duration_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/docker/pkg/units/size_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/cgroups_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/blkio_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpu_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpuset_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/devices_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/freezer_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/memory_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/stats_util_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/util_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/configs/config_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/container_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/devices/devices_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/error_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/factory_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/generic_error_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/integration/exec_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/integration/execin_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/integration/init_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/integration/template_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/integration/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/label/label_selinux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/netlink/netlink_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/notify_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/nsenter/nsenter_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/selinux/selinux_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/capture_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/frame_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/user/user_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/utils/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/entry_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/formatter_bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hook_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/json_formatter_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/logrus_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/text_formatter_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/app_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/cli_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/command_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/context_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/flag_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/helpers_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/files_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/listeners_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/dbus_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/methods_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/set_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/login1/dbus_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/conn_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/proto_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/sig_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/transport_unix_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/variant_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/syndtr/gocapability/capability/capability_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/libcontainer/xattr/xattr_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/spdystream/priority_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/spdystream/spdy/spdy_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/spdystream/spdy_bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/spdystream/spdy_test.go delete mode 100644 Godeps/_workspace/src/github.com/docker/spdystream/ws/ws_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/counterecryptor_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/examples/goproxy-jquery-version/jquery_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/ext/auth/basic_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/ext/html/html_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/proxy_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/regretable/regretreader_test.go delete mode 100644 Godeps/_workspace/src/github.com/elazarl/goproxy/signer_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go delete mode 100644 Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go delete mode 100644 Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go delete mode 100644 Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ulimit_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/mflag/flag_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/parsers/parsers_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit/ulimit_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/duration_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/size_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/libcontainer/user/user_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go delete mode 100644 Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go delete mode 100644 Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go delete mode 100644 Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/conn_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/proto_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/sig_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/transport_unix_test.go delete mode 100644 Godeps/_workspace/src/github.com/godbus/dbus/variant_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/all_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/clone_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/equal_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/extensions_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/message_set_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/size2_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/size_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/Makefile delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/golden_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go.golden delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.proto delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_parser_test.go delete mode 100644 Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/glog/glog_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/api/versions_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/cache/memory/memory_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/collector/collector_manager_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/collector/generic_collector_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/collector/prometheus_collector_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/container/factory_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/container/raw/container_hints_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/events/handler_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/fs/fs_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/manager/container_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/manager/manager_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/metrics/prometheus_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/metrics/testdata/prometheus_metrics delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/storage/influxdb/influxdb_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/summary/buffer_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/summary/percentiles_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/testdata/cpuinfo delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/topology_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/utils/oomparser/oomparser_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/utils/sysinfo/sysinfo_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/cadvisor/utils/timed_store_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/gofuzz/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go delete mode 100644 Godeps/_workspace/src/github.com/gorilla/context/context_test.go delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go delete mode 100644 Godeps/_workspace/src/github.com/gorilla/mux/old_test.go delete mode 100644 Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go delete mode 100644 Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml delete mode 100644 Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml delete mode 100644 Godeps/_workspace/src/github.com/jonboulle/clockwork/clockwork_test.go delete mode 100644 Godeps/_workspace/src/github.com/jonboulle/clockwork/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go delete mode 100644 Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go delete mode 100644 Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go delete mode 100644 Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/auth/sasl/authenticatee_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/detector/factory_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/detector/standalone_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/detect_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/plugin_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_intgr_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/logpb_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/mesospb_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/statepb_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/mesosutil/mesosprotoutil_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/http_transporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/messenger_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/schedcache_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_intgr_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_unit_test.go delete mode 100644 Godeps/_workspace/src/github.com/mesos/mesos-go/upid/upid_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/dns_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/edns_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/idn/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/idn/punycode_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/labels_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/nsecx_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/parse_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/privaterr_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/server_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/sig0_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/types_test.go delete mode 100644 Godeps/_workspace/src/github.com/miekg/dns/update_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/mxk/go-flowrate/flowrate/io_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/skip_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_command_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gexec/exit_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gexec/gexec_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gexec/prefixed_writer_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/gexec/session_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_closed_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_empty_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_false_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_nil_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_sent_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_true_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_zero_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/consist_of_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_element_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/equal_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_len_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_error_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_json_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/panic_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/receive_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/onsi/gomega/matchers/succeed_matcher_test.go delete mode 100644 Godeps/_workspace/src/github.com/pborman/uuid/json_test.go delete mode 100644 Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go delete mode 100644 Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go delete mode 100644 Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/snapshots_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumes_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumetypes_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/bootfromvolume_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/compute_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/extension_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/flavors_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/floatingip_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/images_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/keypairs_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/network_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secdefrules_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secgroup_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servergroup_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servers_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/tenantnetworks_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/volumeattach_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/extension_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/identity_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/role_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/tenant_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/token_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/user_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/endpoint_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/identity_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/service_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/token_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/apiversion_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extension_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/firewall_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/policy_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/rule_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/layer3_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/member_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/monitor_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/pool_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/vip_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/provider_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/security_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/network_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/port_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/subnet_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/accounts_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/containers_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/objects_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/buildinfo_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackevents_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackresources_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacks_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacktemplates_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/snapshot_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_type_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/base_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/flavor_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/service_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/serviceasset_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/bootfromvolume_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/compute_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/flavors_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/images_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/keypairs_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/networks_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/servers_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/virtualinterfaces_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/volumeattach_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/extension_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/identity_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/role_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tenant_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tokens_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/user_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/acl_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/lb_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/monitor_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/node_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/session_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/throttle_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/vip_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/network_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/port_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/security_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/subnet_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/accounts_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/bulk_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdncontainers_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdnobjects_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/containers_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/objects_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/buildinfo_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackevents_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackresources_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacks_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacktemplates_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/cloudnetworks_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/lbpools_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/publicips_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/endpoint_search_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/base/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/flavors/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/defsecrules/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/results_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/endpoint_location_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/users/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external/results_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/provider/results_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/apiversions/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/utils/choose_version_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/linked_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/marker_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/pagination_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/single_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/params_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/provider_client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/snapshots/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumetypes/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/base/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/flavors/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/serviceassets/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/services/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/bootfromvolume/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/flavors/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/images/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/extensions/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/roles/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tenants/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tokens/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/users/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/acl/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/lbs/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/monitors/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/nodes/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/sessions/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/ssl/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/throttle/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/vips/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/networks/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/ports/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/groups/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/rules/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/subnets/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/urls_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdnobjects/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/buildinfo/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackevents/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates/delegate_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/cloudnetworks/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/lbpools/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/publicips/requests_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/service_client_test.go delete mode 100644 Godeps/_workspace/src/github.com/rackspace/gophercloud/util_test.go delete mode 100644 Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go delete mode 100644 Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go delete mode 100644 Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_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/scalingdata/gcfg/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go delete mode 100644 Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go delete mode 100644 Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go delete mode 100644 Godeps/_workspace/src/github.com/skynetservices/skydns/msg/service_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/command_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/count_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/example_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/export_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go delete mode 100644 Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/map_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/security_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/objx/value_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go delete mode 100644 Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go delete mode 100644 Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_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 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/github.com/xyproto/simpleredis/simpleredis_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/exp/inotify/inotify_linux_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 delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/atom/atom_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/atom/table_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/charset_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-charset.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/README delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-16BE-BOM.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-16LE-BOM.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-content-attribute.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/entity_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/escape_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/example_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/node_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/parse_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/render_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/go1.html delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/README delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption02.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/comments01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/doctype01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities02.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/html5test-com.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/inbody01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/isindex.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes-plain-text-unsafe.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/plain-text-unsafe.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scriptdata01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/adoption01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/webkit01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tables01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests1.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests10.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests11.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests12.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests14.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests15.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests16.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests17.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests18.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests19.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests2.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests20.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests21.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests22.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests23.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests24.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests25.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests26.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests3.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests4.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests5.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests6.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests7.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests8.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests9.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests_innerHTML_1.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tricky01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit01.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit02.dat delete mode 100644 Godeps/_workspace/src/golang.org/x/net/html/token_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/websocket/exampledial_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/websocket/examplehandler_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/websocket/hybi_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/websocket/websocket_test.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 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/golang.org/x/tools/go/ast/astutil/enclosing_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/imports_test.go delete mode 100644 Godeps/_workspace/src/golang.org/x/tools/imports/fix_test.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/example_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/linux_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/lumberjack_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/rotate_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/testing_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go delete mode 100644 Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/benchmark_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_go1_2_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_internal_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/example_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_example_test.go delete mode 100644 Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_test.go diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/example_simple_test.go b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/example_simple_test.go deleted file mode 100644 index 24788ddfba1..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/example_simple_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2013 Phillip Bond -// Licensed under the MIT License -// see file LICENSE - -package systemstat_test - -import ( - "bitbucket.org/bertimus9/systemstat" - "fmt" -) - -var sample systemstat.MemSample - -// This example shows how easy it is to get memory information -func Example_simple() { - sample = systemstat.GetMemSample() - fmt.Println("Total available RAM in kb:", sample.MemTotal, "k total") - fmt.Println("Used RAM in kb:", sample.MemUsed, "k used") - fmt.Println("Free RAM in kb:", sample.MemFree, "k free") - fmt.Printf("The output is similar to, but somewhat different than:\n\ttop -n1 | grep Mem:\n") -} diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/systemstat_test.go b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/systemstat_test.go deleted file mode 100644 index 069c9188b33..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/systemstat_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2013 Phillip Bond -// Licensed under the MIT License -// see file LICENSE - -package systemstat - -import ( - "fmt" - "testing" -) - -var ( - msgFail = "%v method fails. Expects %v, returns %v" -) - -func TestGetUptime(t *testing.T) { - s := getUptime("testdata/uptime") - if s.Uptime != 18667.53 { - t.Errorf(msgFail, "getUptime", "18667.53", s.Uptime) - } -} - -func TestGetLoadAvgSample(t *testing.T) { - s := getLoadAvgSample("testdata/loadavg") - fmt.Printf("%#v\n", s) - if s.One != 0.1 { - t.Errorf(msgFail, "getUptime", "0.1", s.One) - } - if s.Five != 0.15 { - t.Errorf(msgFail, "getUptime", "0.15", s.Five) - } - if s.Fifteen != 0.14 { - t.Errorf(msgFail, "getUptime", "0.14", s.Fifteen) - } -} diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/loadavg b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/loadavg deleted file mode 100644 index 9660368d67e..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/loadavg +++ /dev/null @@ -1 +0,0 @@ -0.10 0.15 0.14 1/538 27757 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/meminfo b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/meminfo deleted file mode 100644 index 361aa6656a8..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/meminfo +++ /dev/null @@ -1,42 +0,0 @@ -MemTotal: 3768292 kB -MemFree: 831872 kB -Buffers: 153268 kB -Cached: 1622412 kB -SwapCached: 0 kB -Active: 1287508 kB -Inactive: 1297924 kB -Active(anon): 811384 kB -Inactive(anon): 227652 kB -Active(file): 476124 kB -Inactive(file): 1070272 kB -Unevictable: 196 kB -Mlocked: 196 kB -SwapTotal: 7907324 kB -SwapFree: 7907324 kB -Dirty: 228 kB -Writeback: 0 kB -AnonPages: 809948 kB -Mapped: 226452 kB -Shmem: 229284 kB -Slab: 210268 kB -SReclaimable: 148028 kB -SUnreclaim: 62240 kB -KernelStack: 4344 kB -PageTables: 37932 kB -NFS_Unstable: 0 kB -Bounce: 0 kB -WritebackTmp: 0 kB -CommitLimit: 9791468 kB -Committed_AS: 4513904 kB -VmallocTotal: 34359738367 kB -VmallocUsed: 368496 kB -VmallocChunk: 34359365956 kB -HardwareCorrupted: 0 kB -AnonHugePages: 0 kB -HugePages_Total: 0 -HugePages_Free: 0 -HugePages_Rsvd: 0 -HugePages_Surp: 0 -Hugepagesize: 2048 kB -DirectMap4k: 126592 kB -DirectMap2M: 3786752 kB diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat0 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat0 deleted file mode 100644 index ce37972c69c..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat0 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) S 28256 28256 27864 34816 28256 4202496 736 0 0 0 17470 14 0 0 20 0 7 0 1882735 274173952 571 18446744073709551615 4194368 5592552 140737466979680 139798064197344 4333379 0 0 0 2143420159 18446744073709551615 0 0 17 1 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat1 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat1 deleted file mode 100644 index c77ddceba5d..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat1 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) R 28256 28256 27864 34816 28256 4202496 736 0 0 0 18773 16 0 0 20 0 7 0 1882735 274173952 571 18446744073709551615 4194368 5592552 140737466979680 139798065368712 4457862 0 0 0 2143420159 18446744073709551615 0 0 17 3 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat2 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat2 deleted file mode 100644 index 660b5e203ab..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat2 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) R 28256 28256 27864 34816 28256 4202496 738 0 0 0 20618 18 0 0 20 0 7 0 1882735 274239488 571 18446744073709551615 4194368 5592552 140737466979680 140737466979424 4203351 0 0 0 2143420159 18446744073709551615 0 0 17 0 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat3 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat3 deleted file mode 100644 index 707291e5fb9..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat3 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) R 28256 28256 27864 34816 28256 4202496 738 0 0 0 21641 19 0 0 20 0 7 0 1882735 274239488 571 18446744073709551615 4194368 5592552 140737466979680 139798065356424 4333379 0 0 0 2143420159 18446744073709551615 0 0 17 0 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat5 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat5 deleted file mode 100644 index 409e572983a..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat5 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) R 28256 28256 27864 34816 28256 4202496 738 0 0 0 23722 21 0 0 20 0 7 0 1882735 274239488 571 18446744073709551615 4194368 5592552 140737466979680 139798065368712 4203351 0 0 0 2143420159 18446744073709551615 0 0 17 1 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat6 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat6 deleted file mode 100644 index a4bffeb6705..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/procstat6 +++ /dev/null @@ -1 +0,0 @@ -28267 (go-top) S 28256 28256 27864 34816 28256 4202496 741 0 0 0 25512 22 0 0 20 0 7 0 1882735 274305024 571 18446744073709551615 4194368 5592552 140737466979680 140737466979424 4333379 0 0 0 2143420159 18446744073709551615 0 0 17 2 0 0 0 0 0 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat deleted file mode 100644 index 3e39653ddd2..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat +++ /dev/null @@ -1,12 +0,0 @@ -cpu 17313 714 8241 717906 1456 0 364 0 0 0 -cpu0 6642 289 3526 173411 1162 0 355 0 0 0 -cpu1 2193 88 1066 183608 86 0 2 0 0 0 -cpu2 6463 217 2578 177186 141 0 4 0 0 0 -cpu3 2014 118 1070 183699 65 0 2 0 0 0 -intr 2312829 54 5540 0 0 0 0 0 0 1 24723 0 0 262321 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124099 1226 121928 26 141511 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3689186 -btime 1374442803 -processes 27752 -procs_running 1 -procs_blocked 0 -softirq 923034 6 201522 63 2716 129127 6 168304 89194 629 331467 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat2 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat2 deleted file mode 100644 index e455027c2cf..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat2 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 17328 714 8254 725156 1457 0 366 0 0 0 -cpu0 6648 289 3531 175213 1164 0 356 0 0 0 -cpu1 2198 88 1066 185425 86 0 2 0 0 0 -cpu2 6466 217 2584 178996 141 0 4 0 0 0 -cpu3 2015 118 1071 185521 65 0 2 0 0 0 -intr 2316896 54 5562 0 0 0 0 0 0 1 24939 0 0 262321 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124124 1226 123058 26 142249 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3694091 -btime 1374442803 -processes 27777 -procs_running 1 -procs_blocked 0 -softirq 925673 6 202044 63 2716 129146 6 169061 89550 633 332448 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat3 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat3 deleted file mode 100644 index 7e40bf388b6..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat3 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 18661 714 8322 736828 1463 0 367 0 0 0 -cpu0 6715 289 3555 178374 1170 0 358 0 0 0 -cpu1 3134 88 1080 187754 86 0 2 0 0 0 -cpu2 6769 217 2603 181942 141 0 4 0 0 0 -cpu3 2042 118 1082 188756 65 0 2 0 0 0 -intr 2346985 54 5673 0 0 0 0 0 0 1 25358 0 0 269347 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124230 1226 125412 26 143648 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3722386 -btime 1374442803 -processes 27939 -procs_running 2 -procs_blocked 0 -softirq 939514 6 208124 63 2720 129245 6 170565 91355 637 336793 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat4 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat4 deleted file mode 100644 index 2f61f46e2dd..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat4 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 24106 714 8436 758512 1472 0 372 0 0 0 -cpu0 7831 289 3602 183989 1177 0 361 0 0 0 -cpu1 5075 88 1096 192627 86 0 3 0 0 0 -cpu2 7667 217 2640 187814 142 0 5 0 0 0 -cpu3 3531 118 1096 194081 66 0 2 0 0 0 -intr 2425351 54 5880 0 0 0 0 0 0 1 26243 0 0 282247 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124425 1226 130129 26 146647 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3788723 -btime 1374442803 -processes 28152 -procs_running 1 -procs_blocked 0 -softirq 975972 6 226788 63 2738 129419 6 173753 98111 659 344429 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat5 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat5 deleted file mode 100644 index b51720f07e4..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat5 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 25797 714 8461 761860 1472 0 375 0 0 0 -cpu0 8406 289 3611 184664 1177 0 364 0 0 0 -cpu1 5391 88 1102 193577 86 0 3 0 0 0 -cpu2 8115 217 2646 188622 142 0 5 0 0 0 -cpu3 3884 118 1100 194996 66 0 2 0 0 0 -intr 2446830 54 5896 0 0 0 0 0 0 1 26399 0 0 286933 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124455 1226 131103 26 147182 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3804378 -btime 1374442803 -processes 28177 -procs_running 3 -procs_blocked 0 -softirq 985047 6 231802 63 2740 129448 6 174303 100182 665 345832 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat6 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat6 deleted file mode 100644 index 54ea5d0fd28..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat6 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 31643 714 8507 766175 1477 0 377 0 0 0 -cpu0 9865 289 3628 185726 1182 0 366 0 0 0 -cpu1 6867 88 1110 194656 86 0 3 0 0 0 -cpu2 9658 217 2661 189610 142 0 5 0 0 0 -cpu3 5252 118 1108 196181 66 0 2 0 0 0 -intr 2492898 54 5942 0 0 0 0 0 0 1 26734 0 0 291667 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124574 1226 133046 26 148246 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3836141 -btime 1374442803 -processes 28244 -procs_running 5 -procs_blocked 0 -softirq 1009821 6 247713 63 2748 129565 6 175417 104452 670 349181 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat7 b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat7 deleted file mode 100644 index 6ff438a421a..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/stat7 +++ /dev/null @@ -1,12 +0,0 @@ -cpu 32813 714 8513 766223 1477 0 377 0 0 0 -cpu0 10159 289 3628 185737 1182 0 367 0 0 0 -cpu1 7162 88 1110 194668 86 0 3 0 0 0 -cpu2 9945 217 2664 189623 142 0 5 0 0 0 -cpu3 5546 118 1109 196193 66 0 2 0 0 0 -intr 2498999 54 5954 0 0 0 0 0 0 1 26770 0 0 291667 0 0 0 733 0 0 34 0 0 0 141 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 124585 1226 133246 26 148377 145 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -ctxt 3839591 -btime 1374442803 -processes 28269 -procs_running 5 -procs_blocked 0 -softirq 1014220 6 250668 63 2748 129576 6 175558 105038 670 349887 diff --git a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/uptime b/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/uptime deleted file mode 100644 index 05adb73bc2c..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/bertimus9/systemstat/testdata/uptime +++ /dev/null @@ -1 +0,0 @@ -18667.53 7140.26 diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go deleted file mode 100644 index 41d328f1d5f..00000000000 --- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package goautoneg - -import ( - "testing" -) - -var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - -func TestParseAccept(t *testing.T) { - alternatives := []string{"text/html", "image/png"} - content_type := Negotiate(chrome, alternatives) - if content_type != "image/png" { - t.Errorf("got %s expected image/png", content_type) - } - - alternatives = []string{"text/html", "text/plain", "text/n3"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/html" { - t.Errorf("got %s expected text/html", content_type) - } - - alternatives = []string{"text/n3", "text/plain"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/plain" { - t.Errorf("got %s expected text/plain", content_type) - } - - alternatives = []string{"text/n3", "application/rdf+xml"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/n3" { - t.Errorf("got %s expected text/n3", content_type) - } -} diff --git a/Godeps/_workspace/src/github.com/ClusterHQ/flocker-go/client_test.go b/Godeps/_workspace/src/github.com/ClusterHQ/flocker-go/client_test.go deleted file mode 100644 index ef0feaf7e97..00000000000 --- a/Godeps/_workspace/src/github.com/ClusterHQ/flocker-go/client_test.go +++ /dev/null @@ -1,316 +0,0 @@ -package flocker - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "strconv" - "strings" - "testing" - "time" - - "k8s.io/kubernetes/pkg/volume" - - "github.com/stretchr/testify/assert" -) - -func TestMaximumSizeIs1024Multiple(t *testing.T) { - assert := assert.New(t) - - n, err := strconv.Atoi(string(defaultVolumeSize)) - assert.NoError(err) - assert.Equal(0, n%1024) -} - -func TestPost(t *testing.T) { - const ( - expectedPayload = "foobar" - expectedStatusCode = 418 - ) - - assert := assert.New(t) - - type payload struct { - Test string `json:"test"` - } - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var result payload - err := json.NewDecoder(r.Body).Decode(&result) - assert.NoError(err) - assert.Equal(expectedPayload, result.Test) - w.WriteHeader(expectedStatusCode) - })) - defer ts.Close() - - c := Client{Client: &http.Client{}} - - resp, err := c.post(ts.URL, payload{expectedPayload}) - assert.NoError(err) - assert.Equal(expectedStatusCode, resp.StatusCode) -} - -func TestGet(t *testing.T) { - const ( - expectedStatusCode = 418 - ) - - assert := assert.New(t) - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(expectedStatusCode) - })) - defer ts.Close() - - c := Client{Client: &http.Client{}} - - resp, err := c.get(ts.URL) - assert.NoError(err) - assert.Equal(expectedStatusCode, resp.StatusCode) -} - -func TestFindIDInConfigurationsPayload(t *testing.T) { - const ( - searchedName = "search-for-this-name" - expected = "The-42-id" - ) - assert := assert.New(t) - - c := Client{} - - payload := fmt.Sprintf( - `[{"dataset_id": "1-2-3", "metadata": {"name": "test"}}, {"dataset_id": "The-42-id", "metadata": {"name": "%s"}}]`, - searchedName, - ) - - id, err := c.findIDInConfigurationsPayload( - ioutil.NopCloser(bytes.NewBufferString(payload)), searchedName, - ) - assert.NoError(err) - assert.Equal(expected, id) - - id, err = c.findIDInConfigurationsPayload( - ioutil.NopCloser(bytes.NewBufferString(payload)), "it will not be found", - ) - assert.Equal(errConfigurationNotFound, err) - - id, err = c.findIDInConfigurationsPayload( - ioutil.NopCloser(bytes.NewBufferString("invalid { json")), "", - ) - assert.Error(err) -} - -func TestFindPrimaryUUID(t *testing.T) { - const expectedPrimary = "primary-uuid" - assert := assert.New(t) - - var ( - mockedHost = "127.0.0.1" - mockedPrimary = expectedPrimary - ) - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal("GET", r.Method) - assert.Equal("/v1/state/nodes", r.URL.Path) - w.Write([]byte(fmt.Sprintf(`[{"host": "%s", "uuid": "%s"}]`, mockedHost, mockedPrimary))) - })) - - host, port, err := getHostAndPortFromTestServer(ts) - assert.NoError(err) - - c := newFlockerTestClient(host, port) - assert.NoError(err) - - mockedPrimary = expectedPrimary - primary, err := c.GetPrimaryUUID() - assert.NoError(err) - assert.Equal(expectedPrimary, primary) - - c.clientIP = "not.found" - _, err = c.GetPrimaryUUID() - assert.Equal(errStateNotFound, err) -} - -func TestGetURL(t *testing.T) { - const ( - expectedHost = "host" - expectedPort = 42 - ) - - assert := assert.New(t) - - c := newFlockerTestClient(expectedHost, expectedPort) - var expectedURL = fmt.Sprintf("%s://%s:%d/v1/test", c.schema, expectedHost, expectedPort) - - url := c.getURL("test") - assert.Equal(expectedURL, url) -} - -func getHostAndPortFromTestServer(ts *httptest.Server) (string, int, error) { - tsURL, err := url.Parse(ts.URL) - if err != nil { - return "", 0, err - } - - hostSplits := strings.Split(tsURL.Host, ":") - - port, err := strconv.Atoi(hostSplits[1]) - if err != nil { - return "", 0, nil - } - return hostSplits[0], port, nil -} - -func getVolumeConfig(host string, port int) volume.VolumeConfig { - return volume.VolumeConfig{ - OtherAttributes: map[string]string{ - "CONTROL_SERVICE_HOST": host, - "CONTROL_SERVICE_PORT": strconv.Itoa(port), - }, - } -} - -func TestHappyPathCreateDatasetFromNonExistent(t *testing.T) { - const ( - expectedDatasetName = "dir" - expectedPrimary = "A-B-C-D" - expectedDatasetID = "datasetID" - ) - expectedPath := fmt.Sprintf("/flocker/%s", expectedDatasetID) - - assert := assert.New(t) - var ( - numCalls int - err error - ) - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - numCalls++ - switch numCalls { - case 1: - assert.Equal("GET", r.Method) - assert.Equal("/v1/state/nodes", r.URL.Path) - w.Write([]byte(fmt.Sprintf(`[{"host": "127.0.0.1", "uuid": "%s"}]`, expectedPrimary))) - case 2: - assert.Equal("POST", r.Method) - assert.Equal("/v1/configuration/datasets", r.URL.Path) - - var c configurationPayload - err := json.NewDecoder(r.Body).Decode(&c) - assert.NoError(err) - assert.Equal(expectedPrimary, c.Primary) - assert.Equal(defaultVolumeSize, c.MaximumSize) - assert.Equal(expectedDatasetName, c.Metadata.Name) - - w.Write([]byte(fmt.Sprintf(`{"dataset_id": "%s"}`, expectedDatasetID))) - case 3: - assert.Equal("GET", r.Method) - assert.Equal("/v1/state/datasets", r.URL.Path) - w.Write([]byte(`[]`)) - case 4: - assert.Equal("GET", r.Method) - assert.Equal("/v1/state/datasets", r.URL.Path) - w.Write([]byte(fmt.Sprintf(`[{"dataset_id": "%s", "path": "/flocker/%s"}]`, expectedDatasetID, expectedDatasetID))) - } - })) - - host, port, err := getHostAndPortFromTestServer(ts) - assert.NoError(err) - - c := newFlockerTestClient(host, port) - assert.NoError(err) - - tickerWaitingForVolume = 1 * time.Millisecond // TODO: this is overriding globally - - s, err := c.CreateDataset(expectedDatasetName) - assert.NoError(err) - assert.Equal(expectedPath, s.Path) -} - -func TestCreateDatasetThatAlreadyExists(t *testing.T) { - const ( - datasetName = "dir" - expectedPrimary = "A-B-C-D" - ) - - assert := assert.New(t) - var numCalls int - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - numCalls++ - switch numCalls { - case 1: - assert.Equal("GET", r.Method) - assert.Equal("/v1/state/nodes", r.URL.Path) - w.Write([]byte(fmt.Sprintf(`[{"host": "127.0.0.1", "uuid": "%s"}]`, expectedPrimary))) - case 2: - assert.Equal("POST", r.Method) - assert.Equal("/v1/configuration/datasets", r.URL.Path) - w.WriteHeader(http.StatusConflict) - } - })) - - host, port, err := getHostAndPortFromTestServer(ts) - assert.NoError(err) - - c := newFlockerTestClient(host, port) - assert.NoError(err) - - _, err = c.CreateDataset(datasetName) - assert.Equal(errVolumeAlreadyExists, err) -} - -func TestUpdatePrimaryForDataset(t *testing.T) { - const ( - dir = "dir" - expectedPrimary = "the-new-primary" - expectedDatasetID = "datasetID" - ) - expectedURL := fmt.Sprintf("/v1/configuration/datasets/%s", expectedDatasetID) - - assert := assert.New(t) - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal("POST", r.Method) - assert.Equal(expectedURL, r.URL.Path) - - var c configurationPayload - err := json.NewDecoder(r.Body).Decode(&c) - assert.NoError(err) - - assert.Equal(expectedPrimary, c.Primary) - - w.Write([]byte(fmt.Sprintf(`{"dataset_id": "%s", "path": "just-to-double-check"}`, expectedDatasetID))) - })) - - host, port, err := getHostAndPortFromTestServer(ts) - assert.NoError(err) - - c := newFlockerTestClient(host, port) - assert.NoError(err) - - s, err := c.UpdatePrimaryForDataset(expectedPrimary, expectedDatasetID) - assert.NoError(err) - assert.Equal(expectedDatasetID, s.DatasetID) - assert.NotEqual("", s.Path) -} - -func TestInterfaceIsImplemented(t *testing.T) { - assert.Implements(t, (*Clientable)(nil), Client{}) -} - -func newFlockerTestClient(host string, port int) *Client { - return &Client{ - Client: &http.Client{}, - host: host, - port: port, - version: "v1", - schema: "http", - maximumSize: defaultVolumeSize, - clientIP: "127.0.0.1", - } -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go deleted file mode 100644 index 98717df4901..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index 77989da6297..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package logrus - -import ( - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go deleted file mode 100644 index 13f34cb6f81..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go deleted file mode 100644 index 96318d00304..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_papertrail - -import ( - "fmt" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/stvp/go-udp-testing" -) - -func TestWritingToUDP(t *testing.T) { - port := 16661 - udp.SetAddr(fmt.Sprintf(":%d", port)) - - hook, err := NewPapertrailHook("localhost", port, "test") - if err != nil { - t.Errorf("Unable to connect to local UDP server.") - } - - log := logrus.New() - log.Hooks.Add(hook) - - udp.ShouldReceive(t, "foo", func() { - log.Info("foo") - }) -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go deleted file mode 100644 index 45f18d17047..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package logrus_sentry - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/getsentry/raven-go" -) - -const ( - message = "error message" - server_name = "testserver.internal" - logger_name = "test.logger" -) - -func getTestLogger() *logrus.Logger { - l := logrus.New() - l.Out = ioutil.Discard - return l -} - -func WithTestDSN(t *testing.T, tf func(string, <-chan *raven.Packet)) { - pch := make(chan *raven.Packet, 1) - s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - defer req.Body.Close() - d := json.NewDecoder(req.Body) - p := &raven.Packet{} - err := d.Decode(p) - if err != nil { - t.Fatal(err.Error()) - } - - pch <- p - })) - defer s.Close() - - fragments := strings.SplitN(s.URL, "://", 2) - dsn := fmt.Sprintf( - "%s://public:secret@%s/sentry/project-id", - fragments[0], - fragments[1], - ) - tf(dsn, pch) -} - -func TestSpecialFields(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - logger.WithFields(logrus.Fields{ - "server_name": server_name, - "logger": logger_name, - }).Error(message) - - packet := <-pch - if packet.Logger != logger_name { - t.Errorf("logger should have been %s, was %s", logger_name, packet.Logger) - } - - if packet.ServerName != server_name { - t.Errorf("server_name should have been %s, was %s", server_name, packet.ServerName) - } - }) -} - -func TestSentryHandler(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - - logger.Error(message) - packet := <-pch - if packet.Message != message { - t.Errorf("message should have been %s, was %s", message, packet.Message) - } - }) -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go deleted file mode 100644 index 42762dc10d7..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_syslog - -import ( - "github.com/Sirupsen/logrus" - "log/syslog" - "testing" -) - -func TestLocalhostAddAndPrint(t *testing.T) { - log := logrus.New() - hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - - if err != nil { - t.Errorf("Unable to connect to local syslog.") - } - - log.Hooks.Add(hook) - - for _, level := range hook.Levels() { - if len(log.Hooks[level]) != 1 { - t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level])) - } - } - - log.Info("Congratulations!") -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go deleted file mode 100644 index 53025425816..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,283 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1) - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Len(t, fields, 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Len(t, fields, 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index f604f1b0026..00000000000 --- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - - "testing" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} diff --git a/Godeps/_workspace/src/github.com/abbot/go-http-auth/basic_test.go b/Godeps/_workspace/src/github.com/abbot/go-http-auth/basic_test.go deleted file mode 100644 index 522e00ff15f..00000000000 --- a/Godeps/_workspace/src/github.com/abbot/go-http-auth/basic_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package auth - -import ( - "encoding/base64" - "net/http" - "testing" -) - -func TestAuthBasic(t *testing.T) { - secrets := HtpasswdFileProvider("test.htpasswd") - a := &BasicAuth{Realm: "example.com", Secrets: secrets} - r := &http.Request{} - r.Method = "GET" - if a.CheckAuth(r) != "" { - t.Fatal("CheckAuth passed on empty headers") - } - r.Header = http.Header(make(map[string][]string)) - r.Header.Set("Authorization", "Digest blabla ololo") - if a.CheckAuth(r) != "" { - t.Fatal("CheckAuth passed on bad headers") - } - r.Header.Set("Authorization", "Basic !@#") - if a.CheckAuth(r) != "" { - t.Fatal("CheckAuth passed on bad base64 data") - } - - data := [][]string{ - {"test", "hello"}, - {"test2", "hello2"}, - } - for _, tc := range data { - auth := base64.StdEncoding.EncodeToString([]byte(tc[0] + ":" + tc[1])) - r.Header.Set("Authorization", "Basic "+auth) - if a.CheckAuth(r) != tc[0] { - t.Fatalf("CheckAuth failed for user '%s'", tc[0]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/abbot/go-http-auth/digest_test.go b/Godeps/_workspace/src/github.com/abbot/go-http-auth/digest_test.go deleted file mode 100644 index b4da0814ae7..00000000000 --- a/Godeps/_workspace/src/github.com/abbot/go-http-auth/digest_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package auth - -import ( - "net/http" - "net/url" - "testing" - "time" -) - -func TestAuthDigest(t *testing.T) { - secrets := HtdigestFileProvider("test.htdigest") - da := &DigestAuth{Opaque: "U7H+ier3Ae8Skd/g", - Realm: "example.com", - Secrets: secrets, - clients: map[string]*digest_client{}} - r := &http.Request{} - r.Method = "GET" - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for empty request header") - } - r.Header = http.Header(make(map[string][]string)) - r.Header.Set("Authorization", "Digest blabla") - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for bad request header") - } - r.Header.Set("Authorization", `Digest username="test", realm="example.com", nonce="Vb9BP/h81n3GpTTB", uri="/t2", cnonce="NjE4MTM2", nc=00000001, qop="auth", response="ffc357c4eba74773c8687e0bc724c9a3", opaque="U7H+ier3Ae8Skd/g", algorithm="MD5"`) - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for unknown client") - } - - r.URL, _ = url.Parse("/t2") - da.clients["Vb9BP/h81n3GpTTB"] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - if u, _ := da.CheckAuth(r); u != "test" { - t.Fatal("empty auth for legitimate client") - } - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for outdated nc") - } - - r.URL, _ = url.Parse("/") - da.clients["Vb9BP/h81n3GpTTB"] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for bad request path") - } - - r.URL, _ = url.Parse("/t3") - da.clients["Vb9BP/h81n3GpTTB"] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - if u, _ := da.CheckAuth(r); u != "" { - t.Fatal("non-empty auth for bad request path") - } - - da.clients["+RbVXSbIoa1SaJk1"] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - r.Header.Set("Authorization", `Digest username="test", realm="example.com", nonce="+RbVXSbIoa1SaJk1", uri="/", cnonce="NjE4NDkw", nc=00000001, qop="auth", response="c08918024d7faaabd5424654c4e3ad1c", opaque="U7H+ier3Ae8Skd/g", algorithm="MD5"`) - if u, _ := da.CheckAuth(r); u != "test" { - t.Fatal("empty auth for valid request in subpath") - } -} diff --git a/Godeps/_workspace/src/github.com/abbot/go-http-auth/md5crypt_test.go b/Godeps/_workspace/src/github.com/abbot/go-http-auth/md5crypt_test.go deleted file mode 100644 index 65738ecefa4..00000000000 --- a/Godeps/_workspace/src/github.com/abbot/go-http-auth/md5crypt_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package auth - -import "testing" - -func Test_MD5Crypt(t *testing.T) { - test_cases := [][]string{ - {"apache", "$apr1$J.w5a/..$IW9y6DR0oO/ADuhlMF5/X1"}, - {"pass", "$1$YeNsbWdH$wvOF8JdqsoiLix754LTW90"}, - } - for _, tc := range test_cases { - e := NewMD5Entry(tc[1]) - result := MD5Crypt([]byte(tc[0]), e.Salt, e.Magic) - if string(result) != tc[1] { - t.Fatalf("MD5Crypt returned '%s' instead of '%s'", string(result), tc[1]) - } - t.Logf("MD5Crypt: '%s' (%s%s$) -> %s", tc[0], e.Magic, e.Salt, result) - } -} diff --git a/Godeps/_workspace/src/github.com/abbot/go-http-auth/misc_test.go b/Godeps/_workspace/src/github.com/abbot/go-http-auth/misc_test.go deleted file mode 100644 index 089524c7c0d..00000000000 --- a/Godeps/_workspace/src/github.com/abbot/go-http-auth/misc_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package auth - -import "testing" - -func TestH(t *testing.T) { - const hello = "Hello, world!" - const hello_md5 = "6cd3556deb0da54bca060b4c39479839" - h := H(hello) - if h != hello_md5 { - t.Fatal("Incorrect digest for test string:", h, "instead of", hello_md5) - } -} diff --git a/Godeps/_workspace/src/github.com/abbot/go-http-auth/users_test.go b/Godeps/_workspace/src/github.com/abbot/go-http-auth/users_test.go deleted file mode 100644 index 4fbe8875103..00000000000 --- a/Godeps/_workspace/src/github.com/abbot/go-http-auth/users_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package auth - -import ( - "testing" -) - -func TestHtdigestFile(t *testing.T) { - secrets := HtdigestFileProvider("test.htdigest") - digest := secrets("test", "example.com") - if digest != "aa78524fceb0e50fd8ca96dd818b8cf9" { - t.Fatal("Incorrect digest for test user:", digest) - } - digest = secrets("test", "example1.com") - if digest != "" { - t.Fatal("Got digest for user in non-existant realm:", digest) - } - digest = secrets("test1", "example.com") - if digest != "" { - t.Fatal("Got digest for non-existant user:", digest) - } -} - -func TestHtpasswdFile(t *testing.T) { - secrets := HtpasswdFileProvider("test.htpasswd") - passwd := secrets("test", "blah") - if passwd != "{SHA}qvTGHdzF6KLavt4PO0gs2a6pQ00=" { - t.Fatal("Incorrect passwd for test user:", passwd) - } - passwd = secrets("test3", "blah") - if passwd != "" { - t.Fatal("Got passwd for non-existant user:", passwd) - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/image_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/image_test.go deleted file mode 100644 index dd9aeb37689..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/image_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package schema - -import "testing" - -func TestEmptyApp(t *testing.T) { - imj := ` - { - "acKind": "ImageManifest", - "acVersion": "0.6.1", - "name": "example.com/test" - } - ` - - var im ImageManifest - - err := im.UnmarshalJSON([]byte(imj)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - // Marshal and Unmarshal to verify that no "app": {} is generated on - // Marshal and converted to empty struct on Unmarshal - buf, err := im.MarshalJSON() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - err = im.UnmarshalJSON(buf) - if err != nil { - t.Errorf("unexpected error: %v", err) - } -} - -func TestImageManifestMerge(t *testing.T) { - imj := `{"name": "example.com/test"}` - im := &ImageManifest{} - - if im.UnmarshalJSON([]byte(imj)) == nil { - t.Fatal("Manifest JSON without acKind and acVersion unmarshalled successfully") - } - - im = BlankImageManifest() - - err := im.UnmarshalJSON([]byte(imj)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/pod_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/pod_test.go deleted file mode 100644 index 978e99dc3f2..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/pod_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package schema - -import ( - "testing" - - "github.com/appc/spec/schema/types" -) - -func TestPodManifestMerge(t *testing.T) { - pmj := `{}` - pm := &PodManifest{} - - if pm.UnmarshalJSON([]byte(pmj)) == nil { - t.Fatal("Manifest JSON without acKind and acVersion unmarshalled successfully") - } - - pm = BlankPodManifest() - - err := pm.UnmarshalJSON([]byte(pmj)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } -} - -func TestAppList(t *testing.T) { - ri := RuntimeImage{ - ID: *types.NewHashSHA512([]byte{}), - } - al := AppList{ - RuntimeApp{ - Name: "foo", - Image: ri, - }, - RuntimeApp{ - Name: "bar", - Image: ri, - }, - } - if _, err := al.MarshalJSON(); err != nil { - t.Errorf("want err=nil, got %v", err) - } - dal := AppList{ - RuntimeApp{ - Name: "foo", - Image: ri, - }, - RuntimeApp{ - Name: "bar", - Image: ri, - }, - RuntimeApp{ - Name: "foo", - Image: ri, - }, - } - if _, err := dal.MarshalJSON(); err == nil { - t.Errorf("want err, got nil") - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/acidentifier_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/acidentifier_test.go deleted file mode 100644 index b662705031f..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/acidentifier_test.go +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "reflect" - "testing" -) - -var ( - goodIdentifiers = []string{ - "asdf", - "foo-bar-baz", - "zab_rab_oof", - "database", - "my~database", - "example.com/database", - "example.com/~bob/database", - "example.com/ourapp-1.0.0", - "sub-domain.example.com/org/product/release-1.0.0", - "sub-domain.example.com/org/product/~alice/release-1.0.0", - } - badIdentifiers = []string{ - "", - "BAR", - "foo#", - "EXAMPLE.com", - "foo.com/BAR", - "/app", - "app/", - "-app", - "app-", - ".app", - "app.", - "_app", - "app_", - "~app", - "app~", - } -) - -func TestNewACIdentifier(t *testing.T) { - for i, in := range goodIdentifiers { - l, err := NewACIdentifier(in) - if err != nil { - t.Errorf("#%d: got err=%v, want nil", i, err) - } - if l == nil { - t.Errorf("#%d: got l=nil, want non-nil", i) - } - } -} - -func TestNewACIdentifierBad(t *testing.T) { - for i, in := range badIdentifiers { - l, err := NewACIdentifier(in) - if l != nil { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} - -func TestMustACIdentifier(t *testing.T) { - for i, in := range goodIdentifiers { - l := MustACIdentifier(in) - if l == nil { - t.Errorf("#%d: got l=nil, want non-nil", i) - } - } -} - -func expectPanicMustACIdentifier(i int, in string, t *testing.T) { - defer func() { - recover() - }() - _ = MustACIdentifier(in) - t.Errorf("#%d: panic expected", i) -} - -func TestMustACIdentifierBad(t *testing.T) { - for i, in := range badIdentifiers { - expectPanicMustACIdentifier(i, in, t) - } -} - -func TestSanitizeACIdentifier(t *testing.T) { - tests := map[string]string{ - "foo#": "foo", - "FOO": "foo", - "EXAMPLE.com": "example.com", - "foo.com/BAR": "foo.com/bar", - "/app": "app", - "app/": "app", - "-app": "app", - "app-": "app", - ".app": "app", - "app.": "app", - "_app": "app", - "app_": "app", - "~app": "app", - "app~": "app", - "app///": "app", - "-/.app..": "app", - "-/app.name-test/-/": "app.name-test", - "sub-domain.example.com/org/product/~alice/release-1.0.0": "sub-domain.example.com/org/product/~alice/release-1.0.0", - } - for in, ex := range tests { - o, err := SanitizeACIdentifier(in) - if err != nil { - t.Errorf("got err=%v, want nil", err) - } - if o != ex { - t.Errorf("got l=%s, want %s", o, ex) - } - } -} - -func TestACIdentifierSetGood(t *testing.T) { - tests := map[string]ACIdentifier{ - "blargh": ACIdentifier("blargh"), - "example-ourapp-1-0-0": ACIdentifier("example-ourapp-1-0-0"), - } - for in, w := range tests { - // Ensure an empty name is set appropriately - var a ACIdentifier - err := a.Set(in) - if err != nil { - t.Errorf("%v: got err=%v, want nil", in, err) - continue - } - if !reflect.DeepEqual(a, w) { - t.Errorf("%v: a=%v, want %v", in, a, w) - } - - // Ensure an existing name is overwritten - var b ACIdentifier = ACIdentifier("orig") - err = b.Set(in) - if err != nil { - t.Errorf("%v: got err=%v, want nil", in, err) - continue - } - if !reflect.DeepEqual(b, w) { - t.Errorf("%v: b=%v, want %v", in, b, w) - } - } -} - -func TestACIdentifierSetBad(t *testing.T) { - for i, in := range badIdentifiers { - // Ensure an empty name stays empty - var a ACIdentifier - err := a.Set(in) - if err == nil { - t.Errorf("#%d: err=%v, want nil", i, err) - continue - } - if w := ACIdentifier(""); !reflect.DeepEqual(a, w) { - t.Errorf("%d: a=%v, want %v", i, a, w) - } - - // Ensure an existing name is not overwritten - var b ACIdentifier = ACIdentifier("orig") - err = b.Set(in) - if err == nil { - t.Errorf("#%d: err=%v, want nil", i, err) - continue - } - if w := ACIdentifier("orig"); !reflect.DeepEqual(b, w) { - t.Errorf("%d: b=%v, want %v", i, b, w) - } - } -} - -func TestSanitizeACIdentifierBad(t *testing.T) { - tests := []string{ - "__", - "..", - "//", - "", - ".//-"} - for i, in := range tests { - l, err := SanitizeACIdentifier(in) - if l != "" { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} - -func TestACIdentifierUnmarshalBad(t *testing.T) { - tests := []string{ - "", - "garbage", - `""`, - `"EXAMPLE"`, - `"example.com/app#1"`, - `"~example.com/app1"`, - } - for i, in := range tests { - var a, b ACIdentifier - err := a.UnmarshalJSON([]byte(in)) - if err == nil { - t.Errorf("#%d: err=nil, want non-nil", i) - } else if !reflect.DeepEqual(a, b) { - t.Errorf("#%d: a=%v, want empty", i, a) - } - } -} - -func TestACIdentifierUnmarshalGood(t *testing.T) { - tests := map[string]ACIdentifier{ - `"example"`: ACIdentifier("example"), - `"foo-bar"`: ACIdentifier("foo-bar"), - } - for in, w := range tests { - var a ACIdentifier - err := json.Unmarshal([]byte(in), &a) - if err != nil { - t.Errorf("%v: err=%v, want nil", in, err) - } else if !reflect.DeepEqual(a, w) { - t.Errorf("%v: a=%v, want %v", in, a, w) - } - } -} - -func TestACIdentifierMarshalBad(t *testing.T) { - tests := map[string]error{ - "Foo": ErrInvalidCharInACIdentifier, - "foo#": ErrInvalidCharInACIdentifier, - "-foo": ErrInvalidEdgeInACIdentifier, - "example-": ErrInvalidEdgeInACIdentifier, - "": ErrEmptyACIdentifier, - } - for in, werr := range tests { - a := ACIdentifier(in) - b, gerr := json.Marshal(a) - if b != nil { - t.Errorf("ACIdentifier(%q): want b=nil, got %v", in, b) - } - if jerr, ok := gerr.(*json.MarshalerError); !ok { - t.Errorf("expected JSONMarshalerError") - } else { - if e := jerr.Err; e != werr { - t.Errorf("err=%#v, want %#v", e, werr) - } - } - } -} - -func TestACIdentifierMarshalGood(t *testing.T) { - for i, in := range goodIdentifiers { - a := ACIdentifier(in) - b, err := json.Marshal(a) - if !reflect.DeepEqual(b, []byte(`"`+in+`"`)) { - t.Errorf("#%d: marshalled=%v, want %v", i, b, []byte(in)) - } - if err != nil { - t.Errorf("#%d: err=%v, want nil", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/ackind_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/ackind_test.go deleted file mode 100644 index 6522adb23f1..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/ackind_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestACKindMarshalBad(t *testing.T) { - tests := map[string]error{ - "Foo": ACKindError("bad ACKind: Foo"), - "ApplicationManifest": ACKindError("bad ACKind: ApplicationManifest"), - "": ErrNoACKind, - } - for in, werr := range tests { - a := ACKind(in) - b, gerr := json.Marshal(a) - if b != nil { - t.Errorf("ACKind(%q): want b=nil, got %v", in, b) - } - if jerr, ok := gerr.(*json.MarshalerError); !ok { - t.Errorf("expected JSONMarshalerError") - } else { - if e := jerr.Err; e != werr { - t.Errorf("err=%#v, want %#v", e, werr) - } - } - } -} - -func TestACKindMarshalGood(t *testing.T) { - for i, in := range []string{ - "ImageManifest", - "PodManifest", - } { - a := ACKind(in) - b, err := json.Marshal(a) - if !reflect.DeepEqual(b, []byte(`"`+in+`"`)) { - t.Errorf("#%d: marshalled=%v, want %v", i, b, []byte(in)) - } - if err != nil { - t.Errorf("#%d: err=%v, want nil", i, err) - } - } -} - -func TestACKindUnmarshalBad(t *testing.T) { - tests := []string{ - "ImageManifest", // Not a valid JSON-encoded string - `"garbage"`, - `"AppManifest"`, - `""`, - } - for i, in := range tests { - var a, b ACKind - err := a.UnmarshalJSON([]byte(in)) - if err == nil { - t.Errorf("#%d: err=nil, want non-nil", i) - } else if !reflect.DeepEqual(a, b) { - t.Errorf("#%d: a=%v, want empty", i, a) - } - } -} - -func TestACKindUnmarshalGood(t *testing.T) { - tests := map[string]ACKind{ - `"PodManifest"`: ACKind("PodManifest"), - `"ImageManifest"`: ACKind("ImageManifest"), - } - for in, w := range tests { - var a ACKind - err := json.Unmarshal([]byte(in), &a) - if err != nil { - t.Errorf("%v: err=%v, want nil", in, err) - } else if !reflect.DeepEqual(a, w) { - t.Errorf("%v: a=%v, want %v", in, a, w) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/acname_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/acname_test.go deleted file mode 100644 index 11b8d2cab16..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/acname_test.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "reflect" - "testing" -) - -var ( - goodNames = []string{ - "asdf", - "foo-bar-baz", - "database", - } - badNames = []string{ - "", - "foo#", - "example.com", - "EXAMPLE.com", - "example/database", - "example/database-1.0.0", - "foo.com/BAR", - "example.com/app_1", - "/app", - "app/", - "-app", - "app-", - ".app", - "app.", - } -) - -func TestNewACName(t *testing.T) { - for i, in := range goodNames { - l, err := NewACName(in) - if err != nil { - t.Errorf("#%d: got err=%v, want nil", i, err) - } - if l == nil { - t.Errorf("#%d: got l=nil, want non-nil", i) - } - } -} - -func TestNewACNameBad(t *testing.T) { - for i, in := range badNames { - l, err := NewACName(in) - if l != nil { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} - -func TestMustACName(t *testing.T) { - for i, in := range goodNames { - l := MustACName(in) - if l == nil { - t.Errorf("#%d: got l=nil, want non-nil", i) - } - } -} - -func expectPanicMustACName(i int, in string, t *testing.T) { - defer func() { - recover() - }() - _ = MustACName(in) - t.Errorf("#%d: panic expected", i) -} - -func TestMustACNameBad(t *testing.T) { - for i, in := range badNames { - expectPanicMustACName(i, in, t) - } -} - -func TestSanitizeACName(t *testing.T) { - tests := map[string]string{ - "foo#": "foo", - "EXAMPLE.com": "example-com", - "foo.com/BAR": "foo-com-bar", - "example.com/app_1": "example-com-app-1", - "/app": "app", - "app/": "app", - "-app": "app", - "app-": "app", - ".app": "app", - "app.": "app", - "app///": "app", - "-/.app..": "app", - "-/app.name-test/-/": "app-name-test", - "sub-domain.example.com/org/product/release-1.0.0": "sub-domain-example-com-org-product-release-1-0-0", - } - for in, ex := range tests { - o, err := SanitizeACName(in) - if err != nil { - t.Errorf("got err=%v, want nil", err) - } - if o != ex { - t.Errorf("got l=%s, want %s", o, ex) - } - } -} - -func TestACNameSetGood(t *testing.T) { - tests := map[string]ACName{ - "blargh": ACName("blargh"), - "example-ourapp-1-0-0": ACName("example-ourapp-1-0-0"), - } - for in, w := range tests { - // Ensure an empty name is set appropriately - var a ACName - err := a.Set(in) - if err != nil { - t.Errorf("%v: got err=%v, want nil", in, err) - continue - } - if !reflect.DeepEqual(a, w) { - t.Errorf("%v: a=%v, want %v", in, a, w) - } - - // Ensure an existing name is overwritten - var b ACName = ACName("orig") - err = b.Set(in) - if err != nil { - t.Errorf("%v: got err=%v, want nil", in, err) - continue - } - if !reflect.DeepEqual(b, w) { - t.Errorf("%v: b=%v, want %v", in, b, w) - } - } -} - -func TestACNameSetBad(t *testing.T) { - for i, in := range badNames { - // Ensure an empty name stays empty - var a ACName - err := a.Set(in) - if err == nil { - t.Errorf("#%d: err=%v, want nil", i, err) - continue - } - if w := ACName(""); !reflect.DeepEqual(a, w) { - t.Errorf("%d: a=%v, want %v", i, a, w) - } - - // Ensure an existing name is not overwritten - var b ACName = ACName("orig") - err = b.Set(in) - if err == nil { - t.Errorf("#%d: err=%v, want nil", i, err) - continue - } - if w := ACName("orig"); !reflect.DeepEqual(b, w) { - t.Errorf("%d: b=%v, want %v", i, b, w) - } - } -} - -func TestSanitizeACNameBad(t *testing.T) { - tests := []string{ - "__", - "..", - "//", - "", - ".//-"} - for i, in := range tests { - l, err := SanitizeACName(in) - if l != "" { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} - -func TestACNameUnmarshalBad(t *testing.T) { - tests := []string{ - "", - "garbage", - `""`, - `"EXAMPLE"`, - `"example.com/app_1"`, - } - for i, in := range tests { - var a, b ACName - err := a.UnmarshalJSON([]byte(in)) - if err == nil { - t.Errorf("#%d: err=nil, want non-nil", i) - } else if !reflect.DeepEqual(a, b) { - t.Errorf("#%d: a=%v, want empty", i, a) - } - } -} - -func TestACNameUnmarshalGood(t *testing.T) { - tests := map[string]ACName{ - `"example"`: ACName("example"), - `"foo-bar"`: ACName("foo-bar"), - } - for in, w := range tests { - var a ACName - err := json.Unmarshal([]byte(in), &a) - if err != nil { - t.Errorf("%v: err=%v, want nil", in, err) - } else if !reflect.DeepEqual(a, w) { - t.Errorf("%v: a=%v, want %v", in, a, w) - } - } -} - -func TestACNameMarshalBad(t *testing.T) { - tests := map[string]error{ - "Foo": ErrInvalidCharInACName, - "foo#": ErrInvalidCharInACName, - "-foo": ErrInvalidEdgeInACName, - "example-": ErrInvalidEdgeInACName, - "": ErrEmptyACName, - } - for in, werr := range tests { - a := ACName(in) - b, gerr := json.Marshal(a) - if b != nil { - t.Errorf("ACName(%q): want b=nil, got %v", in, b) - } - if jerr, ok := gerr.(*json.MarshalerError); !ok { - t.Errorf("expected JSONMarshalerError") - } else { - if e := jerr.Err; e != werr { - t.Errorf("err=%#v, want %#v", e, werr) - } - } - } -} - -func TestACNameMarshalGood(t *testing.T) { - for i, in := range goodNames { - a := ACName(in) - b, err := json.Marshal(a) - if !reflect.DeepEqual(b, []byte(`"`+in+`"`)) { - t.Errorf("#%d: marshalled=%v, want %v", i, b, []byte(in)) - } - if err != nil { - t.Errorf("#%d: err=%v, want nil", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/annotations_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/annotations_test.go deleted file mode 100644 index 358fd18e464..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/annotations_test.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "reflect" - "testing" -) - -func makeAnno(n, v string) Annotation { - name, err := NewACIdentifier(n) - if err != nil { - panic(err) - } - return Annotation{ - Name: *name, - Value: v, - } -} - -func TestAnnotationsAssertValid(t *testing.T) { - tests := []struct { - in []Annotation - werr bool - }{ - // duplicate names should fail - { - []Annotation{ - makeAnno("foo", "bar"), - makeAnno("foo", "baz"), - }, - true, - }, - // bad created should fail - { - []Annotation{ - makeAnno("created", "garbage"), - }, - true, - }, - // bad homepage should fail - { - []Annotation{ - makeAnno("homepage", "not-A$@#URL"), - }, - true, - }, - // bad documentation should fail - { - []Annotation{ - makeAnno("documentation", "ftp://isnotallowed.com"), - }, - true, - }, - // good cases - { - []Annotation{ - makeAnno("created", "2004-05-14T23:11:14+00:00"), - makeAnno("documentation", "http://example.com/docs"), - }, - false, - }, - { - []Annotation{ - makeAnno("foo", "bar"), - makeAnno("homepage", "https://homepage.com"), - }, - false, - }, - // empty is OK - { - []Annotation{}, - false, - }, - } - for i, tt := range tests { - a := Annotations(tt.in) - err := a.assertValid() - if gerr := (err != nil); gerr != tt.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err) - } - } -} - -func TestAnnotationsMarshal(t *testing.T) { - for i, tt := range []struct { - in []Annotation - wb []byte - werr bool - }{ - { - []Annotation{ - makeAnno("foo", "bar"), - makeAnno("foo", "baz"), - makeAnno("website", "http://example.com/anno"), - }, - nil, - true, - }, - { - []Annotation{ - makeAnno("a", "b"), - }, - []byte(`[{"name":"a","value":"b"}]`), - false, - }, - { - []Annotation{ - makeAnno("foo", "bar"), - makeAnno("website", "http://example.com/anno"), - }, - []byte(`[{"name":"foo","value":"bar"},{"name":"website","value":"http://example.com/anno"}]`), - false, - }, - } { - a := Annotations(tt.in) - b, err := a.MarshalJSON() - if !reflect.DeepEqual(b, tt.wb) { - t.Errorf("#%d: b=%s, want %s", i, b, tt.wb) - } - gerr := err != nil - if gerr != tt.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err) - } - } -} - -func TestAnnotationsUnmarshal(t *testing.T) { - tests := []struct { - in string - wann *Annotations - werr bool - }{ - { - `garbage`, - &Annotations{}, - true, - }, - { - `[{"name":"a","value":"b"},{"name":"a","value":"b"}]`, - &Annotations{}, - true, - }, - { - `[{"name":"a","value":"b"}]`, - &Annotations{ - makeAnno("a", "b"), - }, - false, - }, - } - for i, tt := range tests { - a := &Annotations{} - err := a.UnmarshalJSON([]byte(tt.in)) - gerr := err != nil - if gerr != tt.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err) - } - if !reflect.DeepEqual(a, tt.wann) { - t.Errorf("#%d: ann=%#v, want %#v", i, a, tt.wann) - } - } - -} - -func TestAnnotationsGet(t *testing.T) { - for i, tt := range []struct { - in string - wval string - wok bool - }{ - {"foo", "bar", true}, - {"website", "http://example.com/anno", true}, - {"baz", "", false}, - {"wuuf", "", false}, - } { - a := Annotations{ - makeAnno("foo", "bar"), - makeAnno("website", "http://example.com/anno"), - } - gval, gok := a.Get(tt.in) - if gval != tt.wval { - t.Errorf("#%d: val=%v, want %v", i, gval, tt.wval) - } - if gok != tt.wok { - t.Errorf("#%d: ok=%t, want %t", i, gok, tt.wok) - } - } -} - -func TestAnnotationsSet(t *testing.T) { - a := Annotations{} - - a.Set("foo", "bar") - w := Annotations{ - Annotation{ACIdentifier("foo"), "bar"}, - } - if !reflect.DeepEqual(w, a) { - t.Fatalf("want %v, got %v", w, a) - } - - a.Set("dog", "woof") - w = Annotations{ - Annotation{ACIdentifier("foo"), "bar"}, - Annotation{ACIdentifier("dog"), "woof"}, - } - if !reflect.DeepEqual(w, a) { - t.Fatalf("want %v, got %v", w, a) - } - - a.Set("foo", "baz") - a.Set("example.com/foo_bar", "quux") - w = Annotations{ - Annotation{ACIdentifier("foo"), "baz"}, - Annotation{ACIdentifier("dog"), "woof"}, - Annotation{ACIdentifier("example.com/foo_bar"), "quux"}, - } - if !reflect.DeepEqual(w, a) { - t.Fatalf("want %v, got %v", w, a) - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/app_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/app_test.go deleted file mode 100644 index 9a68532f025..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/app_test.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "reflect" - "testing" -) - -func TestAppValid(t *testing.T) { - tests := []App{ - App{ - Exec: []string{"/bin/httpd"}, - User: "0", - Group: "0", - WorkingDirectory: "/tmp", - }, - App{ - Exec: []string{"/app"}, - User: "0", - Group: "0", - EventHandlers: []EventHandler{ - {Name: "pre-start"}, - {Name: "post-stop"}, - }, - Environment: []EnvironmentVariable{ - {Name: "DEBUG", Value: "true"}, - }, - WorkingDirectory: "/tmp", - }, - App{ - Exec: []string{"/app", "arg1", "arg2"}, - User: "0", - Group: "0", - WorkingDirectory: "/tmp", - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err != nil { - t.Errorf("#%d: err == %v, want nil", i, err) - } - } -} - -func TestAppExecInvalid(t *testing.T) { - tests := []App{ - App{ - Exec: nil, - }, - App{ - Exec: []string{}, - User: "0", - Group: "0", - }, - App{ - Exec: []string{"app"}, - User: "0", - Group: "0", - }, - App{ - Exec: []string{"bin/app", "arg1"}, - User: "0", - Group: "0", - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} - -func TestAppEventHandlersInvalid(t *testing.T) { - tests := []App{ - App{ - Exec: []string{"/bin/httpd"}, - User: "0", - Group: "0", - EventHandlers: []EventHandler{ - EventHandler{ - Name: "pre-start", - }, - EventHandler{ - Name: "pre-start", - }, - }, - }, - App{ - Exec: []string{"/bin/httpd"}, - User: "0", - Group: "0", - EventHandlers: []EventHandler{ - EventHandler{ - Name: "post-stop", - }, - EventHandler{ - Name: "pre-start", - }, - EventHandler{ - Name: "post-stop", - }, - }, - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} - -func TestUserGroupInvalid(t *testing.T) { - tests := []App{ - App{ - Exec: []string{"/app"}, - }, - App{ - Exec: []string{"/app"}, - User: "0", - }, - App{ - Exec: []string{"app"}, - Group: "0", - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} - -func TestAppWorkingDirectoryInvalid(t *testing.T) { - tests := []App{ - App{ - Exec: []string{"/app"}, - User: "foo", - Group: "bar", - WorkingDirectory: "stuff", - }, - App{ - Exec: []string{"/app"}, - User: "foo", - Group: "bar", - WorkingDirectory: "../home/fred", - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} - -func TestAppEnvironmentInvalid(t *testing.T) { - tests := []App{ - App{ - Exec: []string{"/app"}, - User: "foo", - Group: "bar", - Environment: Environment{ - EnvironmentVariable{"0DEBUG", "true"}, - }, - }, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} - -func TestAppUnmarshal(t *testing.T) { - tests := []struct { - in string - wann *App - werr bool - }{ - { - `garbage`, - &App{}, - true, - }, - { - `{"Exec":"not a list"}`, - &App{}, - true, - }, - { - `{"Exec":["notfullyqualified"]}`, - &App{}, - true, - }, - { - `{"Exec":["/a"],"User":"0","Group":"0"}`, - &App{ - Exec: Exec{ - "/a", - }, - User: "0", - Group: "0", - Environment: make(Environment, 0), - }, - false, - }, - } - for i, tt := range tests { - a := &App{} - err := a.UnmarshalJSON([]byte(tt.in)) - gerr := err != nil - if gerr != tt.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err) - } - if !reflect.DeepEqual(a, tt.wann) { - t.Errorf("#%d: ann=%#v, want %#v", i, a, tt.wann) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/date_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/date_test.go deleted file mode 100644 index 9eb11830f51..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/date_test.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "testing" - "time" -) - -var ( - pst = time.FixedZone("Pacific", -8*60*60) -) - -func TestUnmarshalDate(t *testing.T) { - tests := []struct { - in string - - wt time.Time - }{ - { - `"2004-05-14T23:11:14+00:00"`, - - time.Date(2004, 05, 14, 23, 11, 14, 0, time.UTC), - }, - { - `"2001-02-03T04:05:06Z"`, - - time.Date(2001, 02, 03, 04, 05, 06, 0, time.UTC), - }, - { - `"2014-11-14T17:36:54-08:00"`, - - time.Date(2014, 11, 14, 17, 36, 54, 0, pst), - }, - { - `"2004-05-14T23:11:14+00:00"`, - - time.Date(2004, 05, 14, 23, 11, 14, 0, time.UTC), - }, - } - for i, tt := range tests { - var d Date - if err := json.Unmarshal([]byte(tt.in), &d); err != nil { - t.Errorf("#%d: got err=%v, want nil", i, err) - } - if gt := time.Time(d); !gt.Equal(tt.wt) { - t.Errorf("#%d: got time=%v, want %v", i, gt, tt.wt) - } - } -} - -func TestUnmarshalDateBad(t *testing.T) { - tests := []string{ - `not a json string`, - `2014-11-14T17:36:54-08:00`, - `"garbage"`, - `"1416015188"`, - `"Fri Nov 14 17:53:02 PST 2014"`, - `"2014-11-1417:36:54"`, - } - for i, tt := range tests { - var d Date - if err := json.Unmarshal([]byte(tt), &d); err == nil { - t.Errorf("#%d: unexpected nil err", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/dependencies_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/dependencies_test.go deleted file mode 100644 index ac3f1f96d96..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/dependencies_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import "testing" - -func TestEmptyHash(t *testing.T) { - dj := `{"imageName": "example.com/reduce-worker-base"}` - - var d Dependency - - err := d.UnmarshalJSON([]byte(dj)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Marshal to verify that marshalling works without validation errors - buf, err := d.MarshalJSON() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // Unmarshal to verify that the generated json will not create wrong empty hash - err = d.UnmarshalJSON(buf) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/environment_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/environment_test.go deleted file mode 100644 index 8c51bea9aef..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/environment_test.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "testing" -) - -func TestEnvironmentAssertValid(t *testing.T) { - tests := []struct { - env Environment - werr bool - }{ - // duplicate names should fail - { - Environment{ - EnvironmentVariable{"DEBUG", "true"}, - EnvironmentVariable{"DEBUG", "true"}, - }, - true, - }, - // empty name should fail - { - Environment{ - EnvironmentVariable{"", "value"}, - }, - true, - }, - // name beginning with digit should fail - { - Environment{ - EnvironmentVariable{"0DEBUG", "true"}, - }, - true, - }, - // name with non [A-Za-z0-9_] should fail - { - Environment{ - EnvironmentVariable{"VERBOSE-DEBUG", "true"}, - }, - true, - }, - // accepted environment variable forms - { - Environment{ - EnvironmentVariable{"DEBUG", "true"}, - }, - false, - }, - { - Environment{ - EnvironmentVariable{"_0_DEBUG_0_", "true"}, - }, - false, - }, - } - for i, test := range tests { - env := Environment(test.env) - err := env.assertValid() - if gerr := (err != nil); gerr != test.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, test.werr, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/exec_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/exec_test.go deleted file mode 100644 index 326dc5dd29d..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/exec_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import "testing" - -func TestExecValid(t *testing.T) { - tests := []Exec{ - Exec{"/bin/httpd"}, - Exec{"/app"}, - Exec{"/app", "arg1", "arg2"}, - } - for i, tt := range tests { - if err := tt.assertValid(); err != nil { - t.Errorf("#%d: err == %v, want nil", i, err) - } - } -} - -func TestExecInvalid(t *testing.T) { - tests := []Exec{ - Exec{}, - Exec{"app"}, - } - for i, tt := range tests { - if err := tt.assertValid(); err == nil { - t.Errorf("#%d: err == nil, want non-nil", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/hash_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/hash_test.go deleted file mode 100644 index dc597efd3a7..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/hash_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "testing" -) - -func TestMarshalHash(t *testing.T) { - tests := []struct { - typ string - val string - - wout string - }{ - { - "sha512", - "abcdefghi", - - `"sha512-abcdefghi"`, - }, - { - "sha512", - "06c733b1838136838e6d2d3e8fa5aea4c7905e92", - - `"sha512-06c733b1838136838e6d2d3e8fa5aea4c7905e92"`, - }, - } - for i, tt := range tests { - h := Hash{ - typ: tt.typ, - Val: tt.val, - } - b, err := json.Marshal(h) - if err != nil { - t.Errorf("#%d: unexpected err=%v", i, err) - } - if g := string(b); g != tt.wout { - t.Errorf("#%d: got string=%v, want %v", i, g, tt.wout) - } - } -} - -func TestMarshalHashBad(t *testing.T) { - tests := []struct { - typ string - val string - }{ - { - // empty value - "sha512", - "", - }, - { - // bad type - "sha1", - "abcdef", - }, - { - // empty type - "", - "abcdef", - }, - { - // empty empty - "", - "", - }, - } - for i, tt := range tests { - h := Hash{ - typ: tt.typ, - Val: tt.val, - } - g, err := json.Marshal(h) - if err == nil { - t.Errorf("#%d: unexpected nil err", i) - } - if g != nil { - t.Errorf("#%d: unexpected non-nil bytes: %v", i, g) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/isolator_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/isolator_test.go deleted file mode 100644 index 785c4f02813..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/isolator_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestIsolatorUnmarshal(t *testing.T) { - tests := []struct { - msg string - werr bool - }{ - { - `{ - "name": "os/linux/capabilities-retain-set", - "value": {"set": ["CAP_KILL"]} - }`, - false, - }, - { - `{ - "name": "os/linux/capabilities-retain-set", - "value": {"set": ["CAP_PONIES"]} - }`, - false, - }, - { - `{ - "name": "os/linux/capabilities-retain-set", - "value": {"set": []} - }`, - true, - }, - { - `{ - "name": "os/linux/capabilities-retain-set", - "value": {"set": "CAP_PONIES"} - }`, - true, - }, - { - `{ - "name": "resource/block-bandwidth", - "value": {"default": true, "limit": "1G"} - }`, - false, - }, - { - `{ - "name": "resource/block-bandwidth", - "value": {"default": false, "limit": "1G"} - }`, - true, - }, - { - `{ - "name": "resource/block-bandwidth", - "value": {"request": "30G", "limit": "1G"} - }`, - true, - }, - { - `{ - "name": "resource/block-iops", - "value": {"default": true, "limit": "1G"} - }`, - false, - }, - { - `{ - "name": "resource/block-iops", - "value": {"default": false, "limit": "1G"} - }`, - true, - }, - { - `{ - "name": "resource/block-iops", - "value": {"request": "30G", "limit": "1G"} - }`, - true, - }, - { - `{ - "name": "resource/cpu", - "value": {"request": "30m", "limit": "1m"} - }`, - false, - }, - { - `{ - "name": "resource/memory", - "value": {"request": "1G", "limit": "2Gi"} - }`, - false, - }, - { - `{ - "name": "resource/memory", - "value": {"default": true, "request": "1G", "limit": "2G"} - }`, - true, - }, - { - `{ - "name": "resource/network-bandwidth", - "value": {"default": true, "limit": "1G"} - }`, - false, - }, - { - `{ - "name": "resource/network-bandwidth", - "value": {"default": false, "limit": "1G"} - }`, - true, - }, - { - `{ - "name": "resource/network-bandwidth", - "value": {"request": "30G", "limit": "1G"} - }`, - true, - }, - } - - for i, tt := range tests { - var ii Isolator - err := ii.UnmarshalJSON([]byte(tt.msg)) - if gerr := (err != nil); gerr != tt.werr { - t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err) - } - } -} - -func TestIsolatorsGetByName(t *testing.T) { - ex := ` - [ - { - "name": "resource/cpu", - "value": {"request": "30m", "limit": "1m"} - }, - { - "name": "resource/memory", - "value": {"request": "1G", "limit": "2Gi"} - }, - { - "name": "os/linux/capabilities-retain-set", - "value": {"set": ["CAP_KILL"]} - }, - { - "name": "os/linux/capabilities-remove-set", - "value": {"set": ["CAP_KILL"]} - } - ] - ` - - tests := []struct { - name ACIdentifier - wlimit int64 - wrequest int64 - wset []LinuxCapability - }{ - {"resource/cpu", 1, 30, nil}, - {"resource/memory", 2147483648, 1000000000, nil}, - {"os/linux/capabilities-retain-set", 0, 0, []LinuxCapability{"CAP_KILL"}}, - {"os/linux/capabilities-remove-set", 0, 0, []LinuxCapability{"CAP_KILL"}}, - } - - var is Isolators - err := json.Unmarshal([]byte(ex), &is) - if err != nil { - panic(err) - } - - if len(is) < 2 { - t.Fatalf("too few items %v", len(is)) - } - - for i, tt := range tests { - c := is.GetByName(tt.name) - if c == nil { - t.Fatalf("can't find item %v in %v items", tt.name, len(is)) - } - switch v := c.Value().(type) { - case Resource: - var r Resource = v - glimit := r.Limit() - grequest := r.Request() - - var vlimit, vrequest int64 - if tt.name == "resource/cpu" { - vlimit, vrequest = glimit.MilliValue(), grequest.MilliValue() - } else { - vlimit, vrequest = glimit.Value(), grequest.Value() - } - - if vlimit != tt.wlimit { - t.Errorf("#%d: glimit=%v, want %v", i, vlimit, tt.wlimit) - } - if vrequest != tt.wrequest { - t.Errorf("#%d: grequest=%v, want %v", i, vrequest, tt.wrequest) - } - - case LinuxCapabilitiesSet: - var s LinuxCapabilitiesSet = v - if !reflect.DeepEqual(s.Set(), tt.wset) { - t.Errorf("#%d: gset=%v, want %v", i, s.Set(), tt.wset) - } - - default: - panic("unexecpected type") - } - } -} - -func TestIsolatorUnrecognized(t *testing.T) { - msg := ` - [{ - "name": "resource/network-bandwidth", - "value": {"default": true, "limit": "1G"} - }, - { - "name": "resource/network-ponies", - "value": 0 - }]` - - ex := Isolators{ - {Name: "resource/network-ponies"}, - } - - is := Isolators{} - if err := json.Unmarshal([]byte(msg), &is); err != nil { - t.Fatalf("failed to unmarshal isolators: %v", err) - } - - u := is.Unrecognized() - if len(u) != len(ex) { - t.Errorf("unrecognized isolator list is wrong len: want %v, got %v", len(ex), len(u)) - } - - for i, e := range ex { - if e.Name != u[i].Name { - t.Errorf("unrecognized isolator list mismatch: want %v, got %v", e.Name, u[i].Name) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/labels_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/labels_test.go deleted file mode 100644 index 9759d88bc07..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/labels_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "strings" - "testing" -) - -func TestLabels(t *testing.T) { - tests := []struct { - in string - errPrefix string - }{ - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "amd64"}]`, - "", - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "aarch64"}]`, - "", - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "arm64"}]`, - `bad arch "arm64" for linux`, - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "aarch64_be"}]`, - "", - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "arm64_be"}]`, - `bad arch "arm64_be" for linux`, - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "arm"}]`, - `bad arch "arm" for linux`, - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "armv6l"}]`, - "", - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "armv7l"}]`, - "", - }, - { - `[{"name": "os", "value": "linux"}, {"name": "arch", "value": "armv7b"}]`, - "", - }, - { - `[{"name": "os", "value": "freebsd"}, {"name": "arch", "value": "amd64"}]`, - "", - }, - { - `[{"name": "os", "value": "OS/360"}, {"name": "arch", "value": "S/360"}]`, - `bad os "OS/360"`, - }, - { - `[{"name": "os", "value": "freebsd"}, {"name": "arch", "value": "armv7b"}]`, - `bad arch "armv7b" for freebsd`, - }, - { - `[{"name": "name"}]`, - `invalid label name: "name"`, - }, - { - `[{"name": "os", "value": "linux"}, {"name": "os", "value": "freebsd"}]`, - `duplicate labels of name "os"`, - }, - { - `[{"name": "arch", "value": "amd64"}, {"name": "os", "value": "freebsd"}, {"name": "arch", "value": "x86_64"}]`, - `duplicate labels of name "arch"`, - }, - { - `[]`, - "", - }, - } - for i, tt := range tests { - var l Labels - if err := json.Unmarshal([]byte(tt.in), &l); err != nil { - if tt.errPrefix == "" { - t.Errorf("#%d: got err=%v, expected no error", i, err) - } else if !strings.HasPrefix(err.Error(), tt.errPrefix) { - t.Errorf("#%d: got err=%v, expected prefix %#v", i, err, tt.errPrefix) - } - } else { - t.Log(l) - if tt.errPrefix != "" { - t.Errorf("#%d: got no err, expected prefix %#v", i, tt.errPrefix) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/mountpoint_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/mountpoint_test.go deleted file mode 100644 index f7b216edd0f..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/mountpoint_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "reflect" - "testing" -) - -func TestMountPointFromString(t *testing.T) { - tests := []struct { - s string - mount MountPoint - }{ - { - "foobar,path=/tmp", - MountPoint{ - Name: "foobar", - Path: "/tmp", - ReadOnly: false, - }, - }, - { - "foobar,path=/tmp,readOnly=false", - MountPoint{ - Name: "foobar", - Path: "/tmp", - ReadOnly: false, - }, - }, - { - "foobar,path=/tmp,readOnly=true", - MountPoint{ - Name: "foobar", - Path: "/tmp", - ReadOnly: true, - }, - }, - } - for i, tt := range tests { - mount, err := MountPointFromString(tt.s) - if err != nil { - t.Errorf("#%d: got err=%v, want nil", i, err) - } - if !reflect.DeepEqual(*mount, tt.mount) { - t.Errorf("#%d: mount=%v, want %v", i, *mount, tt.mount) - } - } -} - -func TestMountPointFromStringBad(t *testing.T) { - tests := []string{ - "#foobar,path=/tmp", - "foobar,path=/tmp,readOnly=true,asdf=asdf", - "foobar,path=/tmp,readOnly=maybe", - "foobar,path=/tmp,readOnly=", - "foobar,path=", - "foobar", - "", - ",path=/", - } - for i, in := range tests { - l, err := MountPointFromString(in) - if l != nil { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/port_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/port_test.go deleted file mode 100644 index 3462c0e3819..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/port_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "testing" -) - -func TestGoodPort(t *testing.T) { - p := Port{ - Port: 32456, - Count: 100, - } - if err := p.assertValid(); err != nil { - t.Errorf("good port assertion failed: %v", err) - } -} - -func TestBadPort(t *testing.T) { - p := Port{ - Port: 88888, - } - if p.assertValid() == nil { - t.Errorf("bad port asserted valid") - } -} - -func TestBadRange(t *testing.T) { - p := Port{ - Port: 32456, - Count: 45678, - } - if p.assertValid() == nil { - t.Errorf("bad port range asserted valid") - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/semver_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/semver_test.go deleted file mode 100644 index 6afb1811098..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/semver_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/coreos/go-semver/semver" -) - -func TestMarshalSemver(t *testing.T) { - tests := []struct { - sv SemVer - - wd []byte - }{ - { - SemVer(semver.Version{Major: 1}), - - []byte(`"1.0.0"`), - }, - { - SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1}), - - []byte(`"3.2.1"`), - }, - { - SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1, PreRelease: "foo"}), - - []byte(`"3.2.1-foo"`), - }, - { - SemVer(semver.Version{Major: 1, Minor: 2, Patch: 3, PreRelease: "alpha", Metadata: "git"}), - - []byte(`"1.2.3-alpha+git"`), - }, - } - for i, tt := range tests { - d, err := json.Marshal(tt.sv) - if !reflect.DeepEqual(d, tt.wd) { - t.Errorf("#%d: d=%v, want %v", i, string(d), string(tt.wd)) - } - if err != nil { - t.Errorf("#%d: err=%v, want nil", i, err) - } - } -} - -func TestUnmarshalSemver(t *testing.T) { - tests := []struct { - d []byte - - wsv SemVer - werr bool - }{ - { - []byte(`"1.0.0"`), - - SemVer(semver.Version{Major: 1}), - false, - }, - { - []byte(`"3.2.1"`), - SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1}), - - false, - }, - { - []byte(`"3.2.1-foo"`), - - SemVer(semver.Version{Major: 3, Minor: 2, Patch: 1, PreRelease: "foo"}), - false, - }, - { - []byte(`"1.2.3-alpha+git"`), - - SemVer(semver.Version{Major: 1, Minor: 2, Patch: 3, PreRelease: "alpha", Metadata: "git"}), - false, - }, - { - []byte(`"1"`), - - SemVer{}, - true, - }, - { - []byte(`"1.2.3.4"`), - - SemVer{}, - true, - }, - { - []byte(`1.2.3`), - - SemVer{}, - true, - }, - { - []byte(`"v1.2.3"`), - - SemVer{}, - true, - }, - } - for i, tt := range tests { - var sv SemVer - err := json.Unmarshal(tt.d, &sv) - if !reflect.DeepEqual(sv, tt.wsv) { - t.Errorf("#%d: semver=%#v, want %#v", i, sv, tt.wsv) - } - if gerr := (err != nil); gerr != tt.werr { - t.Errorf("#%d: err==%v, want errstate %t", i, err, tt.werr) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/url_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/url_test.go deleted file mode 100644 index fa1e65d5699..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/url_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "encoding/json" - "net/url" - "reflect" - "testing" -) - -func mustParseURL(t *testing.T, s string) url.URL { - u, err := url.Parse(s) - if err != nil { - t.Fatalf("error parsing URL: %v", err) - } - return *u -} - -func TestMarshalURL(t *testing.T) { - tests := []struct { - u url.URL - - w string - }{ - { - mustParseURL(t, "http://foo.com"), - - `"http://foo.com"`, - }, - { - mustParseURL(t, "http://foo.com/huh/what?is=this"), - - `"http://foo.com/huh/what?is=this"`, - }, - { - mustParseURL(t, "https://example.com/bar"), - - `"https://example.com/bar"`, - }, - } - for i, tt := range tests { - u := URL(tt.u) - b, err := json.Marshal(u) - if g := string(b); g != tt.w { - t.Errorf("#%d: got %q, want %q", i, g, tt.w) - } - if err != nil { - t.Errorf("#%d: err=%v, want nil", i, err) - } - - } -} - -func TestMarshalURLBad(t *testing.T) { - tests := []url.URL{ - mustParseURL(t, "ftp://foo.com"), - mustParseURL(t, "unix:///hello"), - } - for i, tt := range tests { - u := URL(tt) - b, err := json.Marshal(u) - if b != nil { - t.Errorf("#%d: got %v, want nil", i, b) - } - if err == nil { - t.Errorf("#%d: got unexpected err=nil", i) - } - } -} - -func TestUnmarshalURL(t *testing.T) { - tests := []struct { - in string - - w URL - }{ - { - `"http://foo.com"`, - - URL(mustParseURL(t, "http://foo.com")), - }, - { - `"http://yis.com/hello?goodbye=yes"`, - - URL(mustParseURL(t, "http://yis.com/hello?goodbye=yes")), - }, - { - `"https://ohai.net"`, - - URL(mustParseURL(t, "https://ohai.net")), - }, - } - for i, tt := range tests { - var g URL - err := json.Unmarshal([]byte(tt.in), &g) - if err != nil { - t.Errorf("#%d: want err=nil, got %v", i, err) - } - if !reflect.DeepEqual(g, tt.w) { - t.Errorf("#%d: got url=%v, want %v", i, g, tt.w) - } - } -} - -func TestUnmarshalURLBad(t *testing.T) { - var empty = URL{} - tests := []string{ - "badjson", - "http://google.com", - `"ftp://example.com"`, - `"unix://file.net"`, - `"not a url"`, - } - for i, tt := range tests { - var g URL - err := json.Unmarshal([]byte(tt), &g) - if err == nil { - t.Errorf("#%d: want err, got nil", i) - } - if !reflect.DeepEqual(g, empty) { - t.Errorf("#%d: got %v, want %v", i, g, empty) - } - } -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/uuid_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/uuid_test.go deleted file mode 100644 index 03c93202d8e..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/uuid_test.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import "testing" - -func TestNewUUID(t *testing.T) { - tests := []struct { - in string - ws string - }{ - { - "6733C088-A507-4694-AABF-EDBE4FC5266F", - - "6733c088-a507-4694-aabf-edbe4fc5266f", - }, - { - "6733C088A5074694AABFEDBE4FC5266F", - - "6733c088-a507-4694-aabf-edbe4fc5266f", - }, - { - "0aaf0a79-1a39-4d59-abbf-1bebca8209d2", - - "0aaf0a79-1a39-4d59-abbf-1bebca8209d2", - }, - { - "0aaf0a791a394d59abbf1bebca8209d2", - - "0aaf0a79-1a39-4d59-abbf-1bebca8209d2", - }, - } - for i, tt := range tests { - gu, err := NewUUID(tt.in) - if err != nil { - t.Errorf("#%d: err=%v, want %v", i, err, nil) - } - if gs := gu.String(); gs != tt.ws { - t.Errorf("#%d: String()=%v, want %v", i, gs, tt.ws) - } - } -} - -func TestNewUUIDBad(t *testing.T) { - tests := []string{ - "asdf", - "0AAF0A79-1A39-4D59-ABBF-1BEBCA8209D2ABC", - "", - } - for i, tt := range tests { - g, err := NewUUID(tt) - if err == nil { - t.Errorf("#%d: err=nil, want non-nil", i) - } - if g != nil { - t.Errorf("#%d: err=%v, want %v", i, g, nil) - - } - } - -} diff --git a/Godeps/_workspace/src/github.com/appc/spec/schema/types/volume_test.go b/Godeps/_workspace/src/github.com/appc/spec/schema/types/volume_test.go deleted file mode 100644 index 8094793c824..00000000000 --- a/Godeps/_workspace/src/github.com/appc/spec/schema/types/volume_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2015 The appc Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package types - -import ( - "reflect" - "testing" -) - -func TestVolumeFromString(t *testing.T) { - trueVar := true - falseVar := false - tests := []struct { - s string - v Volume - }{ - { - "foobar,kind=host,source=/tmp", - Volume{ - Name: "foobar", - Kind: "host", - Source: "/tmp", - ReadOnly: nil, - }, - }, - { - "foobar,kind=host,source=/tmp,readOnly=false", - Volume{ - Name: "foobar", - Kind: "host", - Source: "/tmp", - ReadOnly: &falseVar, - }, - }, - { - "foobar,kind=host,source=/tmp,readOnly=true", - Volume{ - Name: "foobar", - Kind: "host", - Source: "/tmp", - ReadOnly: &trueVar, - }, - }, - { - "foobar,kind=empty", - Volume{ - Name: "foobar", - Kind: "empty", - ReadOnly: nil, - }, - }, - { - "foobar,kind=empty,readOnly=true", - Volume{ - Name: "foobar", - Kind: "empty", - ReadOnly: &trueVar, - }, - }, - } - for i, tt := range tests { - v, err := VolumeFromString(tt.s) - if err != nil { - t.Errorf("#%d: got err=%v, want nil", i, err) - } - if !reflect.DeepEqual(*v, tt.v) { - t.Errorf("#%d: v=%v, want %v", i, *v, tt.v) - } - } -} - -func TestVolumeFromStringBad(t *testing.T) { - tests := []string{ - "#foobar,kind=host,source=/tmp", - "foobar,kind=host,source=/tmp,readOnly=true,asdf=asdf", - "foobar,kind=empty,source=/tmp", - } - for i, in := range tests { - l, err := VolumeFromString(in) - if l != nil { - t.Errorf("#%d: got l=%v, want nil", i, l) - } - if err == nil { - t.Errorf("#%d: got err=nil, want non-nil", i) - } - } -} 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 4f26241a2b8..00000000000 --- 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 0da6b06fddc..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go deleted file mode 100644 index c4320ca1ede..00000000000 --- 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 df7a3e5d2de..00000000000 --- 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/corehandlers/handlers_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go deleted file mode 100644 index 214adcab088..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/handlers_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package corehandlers_test - -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/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/service" -) - -func TestValidateEndpointHandler(t *testing.T) { - os.Clearenv() - svc := service.New(aws.NewConfig().WithRegion("us-west-2")) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.NoError(t, err) -} - -func TestValidateEndpointHandlerErrorRegion(t *testing.T) { - os.Clearenv() - svc := service.New(nil) - svc.Handlers.Clear() - svc.Handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - - req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := req.Build() - - assert.Error(t, err) - assert.Equal(t, aws.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 := service.New(&aws.Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: aws.Int(1)}) - - svc.Handlers.Clear() - svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) { - r.Error = awserr.New("UnknownError", "", nil) - r.HTTPResponse = &http.Response{StatusCode: 400} - }) - svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - r.Error = awserr.New("ExpiredTokenException", "", nil) - }) - svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - - assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired") - assert.False(t, credProvider.retrieveCalled) - - req := svc.NewRequest(&request.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 := service.New(&aws.Config{ - HTTPClient: &http.Client{ - Transport: &testSendHandlerTransport{}, - }, - }) - svc.Handlers.Clear() - svc.Handlers.Send.PushBackNamed(corehandlers.SendHandler) - r := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - - r.Send() - - assert.Error(t, r.Error) - assert.NotNil(t, r.HTTPResponse) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go deleted file mode 100644 index db483ba408b..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package corehandlers_test - -import ( - "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/corehandlers" - "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/stretchr/testify/require" -) - -var testSvc = func() *service.Service { - s := &service.Service{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - require.NoError(t, req.Error) -} - -func TestMissingRequiredParameters(t *testing.T) { - input := &StructShape{} - req := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - require.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 := testSvc.NewRequest(&request.Operation{}, input, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - require.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()) -} - -type testInput struct { - StringField string `min:"5"` - PtrStrField *string `min:"2"` - ListField []string `min:"3"` - MapField map[string]string `min:"4"` -} - -var testsFieldMin = []struct { - err awserr.Error - in testInput -}{ - { - err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 5: StringField", nil), - in: testInput{StringField: "abcd"}, - }, - { - err: awserr.New("InvalidParameter", "2 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField", nil), - in: testInput{StringField: "abcd", ListField: []string{"a", "b"}}, - }, - { - err: awserr.New("InvalidParameter", "3 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField\n- field too short, minimum length 4: MapField", nil), - in: testInput{StringField: "abcd", ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}}, - }, - { - err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 2: PtrStrField", nil), - in: testInput{StringField: "abcde", PtrStrField: aws.String("v")}, - }, - { - err: nil, - in: testInput{StringField: "abcde", PtrStrField: aws.String("value"), - ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}}, - }, -} - -func TestValidateFieldMinParameter(t *testing.T) { - for i, c := range testsFieldMin { - req := testSvc.NewRequest(&request.Operation{}, &c.in, nil) - corehandlers.ValidateParametersHandler.Fn(req) - - require.Equal(t, c.err, req.Error, "%d case failed", i) - } -} 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 4fba22f29f4..00000000000 --- 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 99c2b47742e..00000000000 --- 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 cd0cbc97e06..00000000000 --- 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 53f6ce256eb..00000000000 --- 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 1d9983f2ce1..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider_test.go +++ /dev/null @@ -1,88 +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() - for i := 0; i < b.N; i++ { - _, 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 ea012369624..00000000000 --- 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_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 f5b97c0053b..00000000000 --- 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/ec2metadata/api_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/ec2metadata/api_test.go deleted file mode 100644 index 61ab62a5305..00000000000 --- 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/request" -) - -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 := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", "testpath"), - } - - req := c.Service.NewRequest(op, nil, nil) - assert.Equal(t, "http://169.254.169.254/latest", req.Service.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 *request.Request) { - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - r.Error = awserr.New("RequestError", "send request failed", nil) - r.Retryable = aws.Bool(true) // network errors are retryable - }) - - available := c.Available() - - assert.False(t, available) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers_test.go deleted file mode 100644 index 2ff05a8154e..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/handlers_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package request_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -func TestHandlerList(t *testing.T) { - s := "" - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { - s += "a" - r.Data = s - }) - l.Run(r) - assert.Equal(t, "a", s) - assert.Equal(t, "a", r.Data) -} - -func TestMultipleHandlers(t *testing.T) { - r := &request.Request{} - l := request.HandlerList{} - l.PushBack(func(r *request.Request) { r.Data = nil }) - l.PushFront(func(r *request.Request) { r.Data = aws.Bool(true) }) - l.Run(r) - if r.Data != nil { - t.Error("Expected handler to execute") - } -} - -func TestNamedHandlers(t *testing.T) { - l := request.HandlerList{} - named := request.NamedHandler{"Name", func(r *request.Request) {}} - named2 := request.NamedHandler{"NotName", func(r *request.Request) {}} - l.PushBackNamed(named) - l.PushBackNamed(named) - l.PushBackNamed(named2) - l.PushBack(func(r *request.Request) {}) - assert.Equal(t, 4, l.Len()) - l.Remove(named) - assert.Equal(t, 2, l.Len()) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go deleted file mode 100644 index c0f151eeea6..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_pagination_test.go +++ /dev/null @@ -1,307 +0,0 @@ -package request_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/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 *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - for _, t := range p.TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) - assert.Nil(t, params.ExclusiveStartTableName) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEachPage(t *testing.T) { - db := dynamodb.New(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 *request.Request) { - in := r.Params.(*dynamodb.ListTablesInput) - if in == nil { - tokens = append(tokens, "") - } else if in.ExclusiveStartTableName != nil { - tokens = append(tokens, *in.ExclusiveStartTableName) - } - }) - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - req, _ := db.ListTablesRequest(params) - err := req.EachPage(func(p interface{}, last bool) bool { - numPages++ - for _, t := range p.(*dynamodb.ListTablesOutput).TableNames { - pages = append(pages, *t) - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - - return true - }) - - assert.Equal(t, []string{"Table2", "Table4"}, tokens) - assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages) - assert.Equal(t, 3, numPages) - assert.True(t, gotToEnd) - assert.Nil(t, err) -} - -// Use DynamoDB methods for simplicity -func TestPaginationEarlyExit(t *testing.T) { - db := dynamodb.New(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 *request.Request) { - r.Data = resps[reqNum] - reqNum++ - }) - - params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool { - numPages++ - if numPages == 2 { - return false - } - if last { - if gotToEnd { - assert.Fail(t, "last=true happened twice") - } - gotToEnd = true - } - return true - }) - - assert.Equal(t, 2, numPages) - assert.False(t, gotToEnd) - assert.Nil(t, err) -} - -func TestSkipPagination(t *testing.T) { - client := s3.New(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 *request.Request) { - r.Data = &s3.HeadBucketOutput{} - }) - - req, _ := client.HeadBucketRequest(&s3.HeadBucketInput{Bucket: aws.String("bucket")}) - - numPages, gotToEnd := 0, false - req.EachPage(func(p interface{}, last bool) bool { - numPages++ - if last { - gotToEnd = true - } - return true - }) - assert.Equal(t, 1, numPages) - assert.True(t, gotToEnd) -} - -// Use S3 for simplicity -func TestPaginationTruncation(t *testing.T) { - 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 *request.Request) { - r.Data = resps[*reqNum] - *reqNum++ - }) - - params := &s3.ListObjectsInput{Bucket: aws.String("bucket")} - - results := []string{} - err := client.ListObjectsPages(params, func(p *s3.ListObjectsOutput, last bool) bool { - results = append(results, *p.Contents[0].Key) - return true - }) - - assert.Equal(t, []string{"Key1", "Key2", "Key3"}, results) - assert.Nil(t, err) - - // Try again without truncation token at all - 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 *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error { - page, _ := db.ListTablesRequest(input) - for ; page != nil; page = page.NextPage() { - page.Send() - out := page.Data.(*dynamodb.ListTablesOutput) - if result := fn(out, !page.HasNextPage()); page.Error != nil || !result { - return page.Error - } - } - return nil - } - - for i := 0; i < b.N; i++ { - reqNum = 0 - iter(func(p *dynamodb.ListTablesOutput, last bool) bool { - return true - }) - } -} - -func BenchmarkEachPageIterator(b *testing.B) { - reqNum := 0 - db := benchDb() - db.Handlers.Unmarshal.PushBack(func(r *request.Request) { - r.Data = benchResps[reqNum] - reqNum++ - }) - - input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)} - for i := 0; i < b.N; i++ { - reqNum = 0 - req, _ := db.ListTablesRequest(input) - req.EachPage(func(p interface{}, last bool) bool { - return true - }) - } -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_test.go deleted file mode 100644 index 6cea0bd2fff..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request/request_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package request_test - -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/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/service" - "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.Request) { - defer req.HTTPResponse.Body.Close() - if req.Data != nil { - json.NewDecoder(req.HTTPResponse.Body).Decode(req.Data) - } - return -} - -func unmarshalError(req *request.Request) { - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err) - return - } - if len(bodyBytes) == 0 { - req.Error = awserr.NewRequestFailure( - awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), - req.HTTPResponse.StatusCode, - "", - ) - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err) - return - } - req.Error = awserr.NewRequestFailure( - awserr.New(jsonErr.Code, jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - "", - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} - -// test that retries occur for 5xx status codes -func TestRequestRecoverRetry5xx(t *testing.T) { - reqNum := 0 - reqs := []http.Response{ - {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - {StatusCode: 200, Body: body(`{"data":"valid"}`)}, - } - - s := service.New(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - 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 := service.New(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - 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 := service.New(aws.NewConfig().WithMaxRetries(10)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &http.Response{StatusCode: 401, Body: body(`{"__type":"SignatureDoesNotMatch","message":"Signature does not match."}`)} - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - 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 := service.New(aws.NewConfig().WithMaxRetries(aws.DefaultRetries).WithSleepDelay(sleepDelay)) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, nil) - err := r.Send() - 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 := service.New(&aws.Config{MaxRetries: aws.Int(10), Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) - s.Handlers.Validate.Clear() - s.Handlers.Unmarshal.PushBack(unmarshal) - s.Handlers.UnmarshalError.PushBack(unmarshalError) - - credExpiredBeforeRetry := false - credExpiredAfterRetry := false - - s.Handlers.AfterRetry.PushBack(func(r *request.Request) { - credExpiredAfterRetry = r.Service.Config.Credentials.IsExpired() - }) - - s.Handlers.Sign.Clear() - s.Handlers.Sign.PushBack(func(r *request.Request) { - r.Service.Config.Credentials.Get() - }) - s.Handlers.Send.Clear() // mock sending - s.Handlers.Send.PushBack(func(r *request.Request) { - r.HTTPResponse = &reqs[reqNum] - reqNum++ - }) - out := &testData{} - r := s.NewRequest(&request.Operation{Name: "Operation"}, nil, out) - err := r.Send() - 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/types_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/types_test.go deleted file mode 100644 index a4ed20e7d22..00000000000 --- 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/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 8af65879d40..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go deleted file mode 100644 index 8b2e59a8ae0..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/build_test.go +++ /dev/null @@ -1,880 +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/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/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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService1TestShapeInputService1TestCaseOperation1Input struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService1TestShapeInputService1TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - Bar *string `locationName:"barLocationName" type:"string"` - - Foo *string `type:"string"` - - Yuck *string `locationName:"yuckLocationName" queryName:"yuckQueryName" type:"string"` - - metadataInputService2TestShapeInputService2TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService3TestShapeInputService3TestCaseOperation1Input struct { - StructArg *InputService3TestShapeStructType `locationName:"Struct" type:"structure"` - - metadataInputService3TestShapeInputService3TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService4TestShapeInputService4TestCaseOperation1Input struct { - ListArg []*string `type:"list"` - - metadataInputService4TestShapeInputService4TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - ListArg []*string `locationName:"ListMemberName" locationNameList:"item" type:"list"` - - metadataInputService5TestShapeInputService5TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - ListArg []*string `locationName:"ListMemberName" queryName:"ListQueryName" locationNameList:"item" type:"list"` - - metadataInputService6TestShapeInputService6TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - BlobArg []byte `type:"blob"` - - metadataInputService7TestShapeInputService7TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService8TestShapeInputService8TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output struct { - SDKShapeTraits bool `type:"structure"` -} - -// -// Tests begin here -// - -func TestInputService1ProtocolTestScalarMembersCase1(t *testing.T) { - svc := NewInputService1ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService1TestShapeInputService1TestCaseOperation1Input{ - 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 := &InputService2TestShapeInputService2TestCaseOperation1Input{ - Bar: aws.String("val2"), - Foo: aws.String("val1"), - Yuck: aws.String("val3"), - } - req, _ := svc.InputService2TestCaseOperation1Request(input) - r := req.HTTPRequest - - // build request - ec2query.Build(req) - 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 := &InputService3TestShapeInputService3TestCaseOperation1Input{ - 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 := &InputService4TestShapeInputService4TestCaseOperation1Input{ - 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 := &InputService5TestShapeInputService5TestCaseOperation1Input{ - 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 := &InputService6TestShapeInputService6TestCaseOperation1Input{ - 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 := &InputService7TestShapeInputService7TestCaseOperation1Input{ - 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 := &InputService8TestShapeInputService8TestCaseOperation1Input{ - 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go deleted file mode 100644 index 3d7b0430bdc..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/ec2query/unmarshal_test.go +++ /dev/null @@ -1,836 +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/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/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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, 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 OutputService1TestShapeOutputService1TestCaseOperation1Output 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"` - - metadataOutputService1TestShapeOutputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, 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 OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - Blob []byte `type:"blob"` - - metadataOutputService2TestShapeOutputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, 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 OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - ListMember []*string `type:"list"` - - metadataOutputService3TestShapeOutputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, 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 OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService4TestShapeOutputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, 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 OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService5TestShapeOutputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, 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 OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - Map map[string]*OutputService6TestShapeStructureType `type:"map"` - - metadataOutputService6TestShapeOutputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, 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 OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - Map map[string]*string `type:"map" flattened:"true"` - - metadataOutputService7TestShapeOutputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, 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 OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` - - metadataOutputService8TestShapeOutputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Output 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go deleted file mode 100644 index 7b29fd79d74..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go +++ /dev/null @@ -1,1333 +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/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/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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService1TestCaseOperation1 = "OperationName" - -// InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputService1TestCaseOperation1Input) (req *request.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService1TestCaseOperation1, - } - - if input == nil { - input = &InputService1TestShapeInputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService1TestShapeInputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *InputService1TestShapeInputService1TestCaseOperation1Input) (*InputService1TestShapeInputService1TestCaseOperation1Output, error) { - req, out := c.InputService1TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService1TestShapeInputService1TestCaseOperation1Input struct { - Bar *string `type:"string"` - - Foo *string `type:"string"` - - metadataInputService1TestShapeInputService1TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService1TestShapeInputService1TestCaseOperation1Output struct { - metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService1TestShapeInputService1TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService2TestCaseOperation1 = "OperationName" - -// InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputService2TestCaseOperation1Input) (req *request.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService2TestCaseOperation1, - } - - if input == nil { - input = &InputService2TestShapeInputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService2TestShapeInputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *InputService2TestShapeInputService2TestCaseOperation1Input) (*InputService2TestShapeInputService2TestCaseOperation1Output, error) { - req, out := c.InputService2TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService2TestShapeInputService2TestCaseOperation1Input struct { - StructArg *InputService2TestShapeStructType `type:"structure"` - - metadataInputService2TestShapeInputService2TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService2TestShapeInputService2TestCaseOperation1Output struct { - metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService2TestShapeInputService2TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService3TestCaseOperation1 = "OperationName" - -// InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputService3TestCaseOperation1Input) (req *request.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService3TestCaseOperation1, - } - - if input == nil { - input = &InputService3TestShapeInputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService3TestShapeInputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *InputService3TestShapeInputService3TestCaseOperation1Input) (*InputService3TestShapeInputService3TestCaseOperation1Output, error) { - req, out := c.InputService3TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService3TestShapeInputService3TestCaseOperation1Input struct { - ListArg []*string `type:"list"` - - metadataInputService3TestShapeInputService3TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService3TestShapeInputService3TestCaseOperation1Output struct { - metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService3TestShapeInputService3TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService4TestCaseOperation1 = "OperationName" - -// InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputService4TestCaseOperation1Input) (req *request.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService4TestCaseOperation1, - } - - if input == nil { - input = &InputService4TestShapeInputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService4TestShapeInputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *InputService4TestShapeInputService4TestCaseOperation1Input) (*InputService4TestShapeInputService4TestCaseOperation1Output, error) { - req, out := c.InputService4TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService4TestShapeInputService4TestCaseOperation1Input struct { - ListArg []*string `type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` - - metadataInputService4TestShapeInputService4TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService4TestShapeInputService4TestCaseOperation1Output struct { - metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService4TestShapeInputService4TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService5TestCaseOperation1 = "OperationName" - -// InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputService5TestCaseOperation1Input) (req *request.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService5TestCaseOperation1, - } - - if input == nil { - input = &InputService5TestShapeInputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService5TestShapeInputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *InputService5TestShapeInputService5TestCaseOperation1Input) (*InputService5TestShapeInputService5TestCaseOperation1Output, error) { - req, out := c.InputService5TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService5TestShapeInputService5TestCaseOperation1Input struct { - ListArg []*string `locationNameList:"ListArgLocation" type:"list" flattened:"true"` - - ScalarArg *string `type:"string"` - - metadataInputService5TestShapeInputService5TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService5TestShapeInputService5TestCaseOperation1Output struct { - metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService5TestShapeInputService5TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService6TestCaseOperation1 = "OperationName" - -// InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputService6TestCaseOperation1Input) (req *request.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService6TestCaseOperation1, - } - - if input == nil { - input = &InputService6TestShapeInputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService6TestShapeInputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *InputService6TestShapeInputService6TestCaseOperation1Input) (*InputService6TestShapeInputService6TestCaseOperation1Output, error) { - req, out := c.InputService6TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService6TestShapeInputService6TestCaseOperation1Input struct { - MapArg map[string]*string `type:"map"` - - metadataInputService6TestShapeInputService6TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService6TestShapeInputService6TestCaseOperation1Output struct { - metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService6TestShapeInputService6TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService7TestCaseOperation1 = "OperationName" - -// InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputService7TestCaseOperation1Input) (req *request.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService7TestCaseOperation1, - } - - if input == nil { - input = &InputService7TestShapeInputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService7TestShapeInputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *InputService7TestShapeInputService7TestCaseOperation1Input) (*InputService7TestShapeInputService7TestCaseOperation1Output, error) { - req, out := c.InputService7TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService7TestShapeInputService7TestCaseOperation1Input struct { - BlobArg []byte `type:"blob"` - - metadataInputService7TestShapeInputService7TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService7TestShapeInputService7TestCaseOperation1Output struct { - metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService7TestShapeInputService7TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService8TestCaseOperation1 = "OperationName" - -// InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputService8TestCaseOperation1Input) (req *request.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opInputService8TestCaseOperation1, - } - - if input == nil { - input = &InputService8TestShapeInputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &InputService8TestShapeInputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *InputService8TestShapeInputService8TestCaseOperation1Input) (*InputService8TestShapeInputService8TestCaseOperation1Output, error) { - req, out := c.InputService8TestCaseOperation1Request(input) - err := req.Send() - return out, err -} - -type InputService8TestShapeInputService8TestCaseOperation1Input struct { - TimeArg *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - metadataInputService8TestShapeInputService8TestCaseOperation1Input `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Input struct { - SDKShapeTraits bool `type:"structure"` -} - -type InputService8TestShapeInputService8TestCaseOperation1Output struct { - metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataInputService8TestShapeInputService8TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opInputService9TestCaseOperation1 = "OperationName" - -// InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. -func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *request.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - op := &request.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 *request.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - op := &request.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 *request.Request, output *InputService9TestShapeInputService9TestCaseOperation3Output) { - op := &request.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 *request.Request, output *InputService9TestShapeInputService9TestCaseOperation4Output) { - op := &request.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 *request.Request, output *InputService9TestShapeInputService9TestCaseOperation5Output) { - op := &request.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 *request.Request, output *InputService9TestShapeInputService9TestCaseOperation6Output) { - op := &request.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 := &InputService1TestShapeInputService1TestCaseOperation1Input{ - 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 := &InputService2TestShapeInputService2TestCaseOperation1Input{ - 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 := &InputService3TestShapeInputService3TestCaseOperation1Input{ - 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 TestInputService4ProtocolTestFlattenedListCase1(t *testing.T) { - svc := NewInputService4ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService4TestShapeInputService4TestCaseOperation1Input{ - 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 TestInputService5ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) { - svc := NewInputService5ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService5TestShapeInputService5TestCaseOperation1Input{ - ListArg: []*string{ - aws.String("a"), - aws.String("b"), - aws.String("c"), - }, - ScalarArg: aws.String("foo"), - } - 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&ListArgLocation.1=a&ListArgLocation.2=b&ListArgLocation.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 TestInputService6ProtocolTestSerializeMapTypeCase1(t *testing.T) { - svc := NewInputService6ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService6TestShapeInputService6TestCaseOperation1Input{ - 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.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 TestInputService7ProtocolTestBase64EncodedBlobsCase1(t *testing.T) { - svc := NewInputService7ProtocolTest(nil) - svc.Endpoint = "https://test" - - input := &InputService7TestShapeInputService7TestCaseOperation1Input{ - 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 := &InputService8TestShapeInputService8TestCaseOperation1Input{ - 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go deleted file mode 100644 index a0dcfc43adb..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go +++ /dev/null @@ -1,1450 +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/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/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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService1TestCaseOperation1 = "OperationName" - -// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService1TestCaseOperation1, - } - - if input == nil { - input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, 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 OutputService1TestShapeOutputService1TestCaseOperation1Output 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"` - - metadataOutputService1TestShapeOutputService1TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService1TestShapeOutputService1TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService2TestCaseOperation1 = "OperationName" - -// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService2TestCaseOperation1, - } - - if input == nil { - input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, 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 OutputService2TestShapeOutputService2TestCaseOperation1Output struct { - Num *int64 `type:"integer"` - - Str *string `type:"string"` - - metadataOutputService2TestShapeOutputService2TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService2TestShapeOutputService2TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService3TestCaseOperation1 = "OperationName" - -// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService3TestCaseOperation1, - } - - if input == nil { - input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, 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 OutputService3TestShapeOutputService3TestCaseOperation1Output struct { - Blob []byte `type:"blob"` - - metadataOutputService3TestShapeOutputService3TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService3TestShapeOutputService3TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService4TestCaseOperation1 = "OperationName" - -// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService4TestCaseOperation1, - } - - if input == nil { - input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, 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 OutputService4TestShapeOutputService4TestCaseOperation1Output struct { - ListMember []*string `type:"list"` - - metadataOutputService4TestShapeOutputService4TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService4TestShapeOutputService4TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService5TestCaseOperation1 = "OperationName" - -// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService5TestCaseOperation1, - } - - if input == nil { - input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, 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 OutputService5TestShapeOutputService5TestCaseOperation1Output struct { - ListMember []*string `locationNameList:"item" type:"list"` - - metadataOutputService5TestShapeOutputService5TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService5TestShapeOutputService5TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService6TestCaseOperation1 = "OperationName" - -// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService6TestCaseOperation1, - } - - if input == nil { - input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, 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 OutputService6TestShapeOutputService6TestCaseOperation1Output struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService6TestShapeOutputService6TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService6TestShapeOutputService6TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService7TestCaseOperation1 = "OperationName" - -// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService7TestCaseOperation1, - } - - if input == nil { - input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, 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 OutputService7TestShapeOutputService7TestCaseOperation1Output struct { - ListMember []*string `type:"list" flattened:"true"` - - metadataOutputService7TestShapeOutputService7TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService7TestShapeOutputService7TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService8TestCaseOperation1 = "OperationName" - -// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService8TestCaseOperation1, - } - - if input == nil { - input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, 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 OutputService8TestShapeOutputService8TestCaseOperation1Output struct { - List []*OutputService8TestShapeStructureShape `type:"list"` - - metadataOutputService8TestShapeOutputService8TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService8TestShapeOutputService8TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService9TestCaseOperation1 = "OperationName" - -// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService9TestCaseOperation1, - } - - if input == nil { - input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, 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 OutputService9TestShapeOutputService9TestCaseOperation1Output struct { - List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"` - - metadataOutputService9TestShapeOutputService9TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService9TestShapeOutputService9TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService10TestCaseOperation1 = "OperationName" - -// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService10TestCaseOperation1, - } - - if input == nil { - input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, 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 OutputService10TestShapeOutputService10TestCaseOperation1Output struct { - List []*string `locationNameList:"NamedList" type:"list" flattened:"true"` - - metadataOutputService10TestShapeOutputService10TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService10TestShapeOutputService10TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService11TestCaseOperation1 = "OperationName" - -// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService11TestCaseOperation1, - } - - if input == nil { - input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, 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 OutputService11TestShapeOutputService11TestCaseOperation1Output struct { - Map map[string]*OutputService11TestShapeStructType `type:"map"` - - metadataOutputService11TestShapeOutputService11TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService11TestShapeOutputService11TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService12TestCaseOperation1 = "OperationName" - -// OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *request.Request, output *OutputService12TestShapeOutputService12TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService12TestCaseOperation1, - } - - if input == nil { - input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService12TestShapeOutputService12TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, 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 OutputService12TestShapeOutputService12TestCaseOperation1Output struct { - Map map[string]*string `type:"map" flattened:"true"` - - metadataOutputService12TestShapeOutputService12TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService12TestShapeOutputService12TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService13TestCaseOperation1 = "OperationName" - -// OutputService13TestCaseOperation1Request generates a request for the OutputService13TestCaseOperation1 operation. -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *request.Request, output *OutputService13TestShapeOutputService13TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService13TestCaseOperation1, - } - - if input == nil { - input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService13TestShapeOutputService13TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, 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 OutputService13TestShapeOutputService13TestCaseOperation1Output struct { - Map map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"` - - metadataOutputService13TestShapeOutputService13TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService13TestShapeOutputService13TestCaseOperation1Output 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{ - ServiceInfo: serviceinfo.ServiceInfo{ - 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 *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - return req -} - -const opOutputService14TestCaseOperation1 = "OperationName" - -// OutputService14TestCaseOperation1Request generates a request for the OutputService14TestCaseOperation1 operation. -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *request.Request, output *OutputService14TestShapeOutputService14TestCaseOperation1Output) { - op := &request.Operation{ - Name: opOutputService14TestCaseOperation1, - } - - if input == nil { - input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} - } - - req = c.newRequest(op, input, output) - output = &OutputService14TestShapeOutputService14TestCaseOperation1Output{} - req.Data = output - return -} - -func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, 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 OutputService14TestShapeOutputService14TestCaseOperation1Output struct { - Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"` - - metadataOutputService14TestShapeOutputService14TestCaseOperation1Output `json:"-" xml:"-"` -} - -type metadataOutputService14TestShapeOutputService14TestCaseOperation1Output 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/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 fbb0e41cdc1..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go deleted file mode 100644 index 0ba9ff25f73..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go +++ /dev/null @@ -1,247 +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/request" - "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) { - svc := service.New(&aws.Config{Credentials: credentials.AnonymousCredentials}) - r := svc.NewRequest( - &request.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) { - svc := service.New(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - - Sign(r) - sig := r.HTTPRequest.Header.Get("Authorization") - - Sign(r) - assert.Equal(t, sig, r.HTTPRequest.Header.Get("Authorization")) -} - -func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { - svc := service.New(&aws.Config{ - Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), - Region: aws.String("us-west-2"), - }) - r := svc.NewRequest( - &request.Operation{ - Name: "BatchGetItem", - HTTPMethod: "POST", - HTTPPath: "/", - }, - nil, - nil, - ) - r.ExpireTime = time.Minute * 10 - - 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") - svc := service.New(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.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) - svc := service.New(&aws.Config{Credentials: creds}) - r := svc.NewRequest( - &request.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/autoscaling/autoscalingiface/interface_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface/interface_test.go deleted file mode 100644 index 0c36b19cc1b..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface/interface_test.go +++ /dev/null @@ -1,15 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package autoscalingiface_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface" - "github.com/stretchr/testify/assert" -) - -func TestInterface(t *testing.T) { - assert.Implements(t, (*autoscalingiface.AutoScalingAPI)(nil), autoscaling.New(nil)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go deleted file mode 100644 index bdcac9be04f..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/autoscaling/examples_test.go +++ /dev/null @@ -1,1179 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package autoscaling_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/autoscaling" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleAutoScaling_AttachInstances() { - svc := autoscaling.New(nil) - - params := &autoscaling.AttachInstancesInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - InstanceIds: []*string{ - aws.String("XmlStringMaxLen16"), // Required - // More values... - }, - } - resp, err := svc.AttachInstances(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_AttachLoadBalancers() { - svc := autoscaling.New(nil) - - params := &autoscaling.AttachLoadBalancersInput{ - AutoScalingGroupName: aws.String("ResourceName"), - LoadBalancerNames: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.AttachLoadBalancers(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_CompleteLifecycleAction() { - svc := autoscaling.New(nil) - - params := &autoscaling.CompleteLifecycleActionInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - LifecycleActionResult: aws.String("LifecycleActionResult"), // Required - LifecycleActionToken: aws.String("LifecycleActionToken"), // Required - LifecycleHookName: aws.String("AsciiStringMaxLen255"), // Required - } - resp, err := svc.CompleteLifecycleAction(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_CreateAutoScalingGroup() { - svc := autoscaling.New(nil) - - params := &autoscaling.CreateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("XmlStringMaxLen255"), // Required - MaxSize: aws.Int64(1), // Required - MinSize: aws.Int64(1), // Required - AvailabilityZones: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - DefaultCooldown: aws.Int64(1), - DesiredCapacity: aws.Int64(1), - HealthCheckGracePeriod: aws.Int64(1), - HealthCheckType: aws.String("XmlStringMaxLen32"), - InstanceId: aws.String("XmlStringMaxLen16"), - LaunchConfigurationName: aws.String("ResourceName"), - LoadBalancerNames: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - PlacementGroup: aws.String("XmlStringMaxLen255"), - Tags: []*autoscaling.Tag{ - { // Required - Key: aws.String("TagKey"), // Required - PropagateAtLaunch: aws.Bool(true), - ResourceId: aws.String("XmlString"), - ResourceType: aws.String("XmlString"), - Value: aws.String("TagValue"), - }, - // More values... - }, - TerminationPolicies: []*string{ - aws.String("XmlStringMaxLen1600"), // Required - // More values... - }, - VPCZoneIdentifier: aws.String("XmlStringMaxLen255"), - } - resp, err := svc.CreateAutoScalingGroup(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_CreateLaunchConfiguration() { - svc := autoscaling.New(nil) - - params := &autoscaling.CreateLaunchConfigurationInput{ - LaunchConfigurationName: aws.String("XmlStringMaxLen255"), // Required - AssociatePublicIpAddress: aws.Bool(true), - BlockDeviceMappings: []*autoscaling.BlockDeviceMapping{ - { // Required - DeviceName: aws.String("XmlStringMaxLen255"), // Required - Ebs: &autoscaling.Ebs{ - DeleteOnTermination: aws.Bool(true), - Iops: aws.Int64(1), - SnapshotId: aws.String("XmlStringMaxLen255"), - VolumeSize: aws.Int64(1), - VolumeType: aws.String("BlockDeviceEbsVolumeType"), - }, - NoDevice: aws.Bool(true), - VirtualName: aws.String("XmlStringMaxLen255"), - }, - // More values... - }, - ClassicLinkVPCId: aws.String("XmlStringMaxLen255"), - ClassicLinkVPCSecurityGroups: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - EbsOptimized: aws.Bool(true), - IamInstanceProfile: aws.String("XmlStringMaxLen1600"), - ImageId: aws.String("XmlStringMaxLen255"), - InstanceId: aws.String("XmlStringMaxLen16"), - InstanceMonitoring: &autoscaling.InstanceMonitoring{ - Enabled: aws.Bool(true), - }, - InstanceType: aws.String("XmlStringMaxLen255"), - KernelId: aws.String("XmlStringMaxLen255"), - KeyName: aws.String("XmlStringMaxLen255"), - PlacementTenancy: aws.String("XmlStringMaxLen64"), - RamdiskId: aws.String("XmlStringMaxLen255"), - SecurityGroups: []*string{ - aws.String("XmlString"), // Required - // More values... - }, - SpotPrice: aws.String("SpotPrice"), - UserData: aws.String("XmlStringUserData"), - } - resp, err := svc.CreateLaunchConfiguration(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_CreateOrUpdateTags() { - svc := autoscaling.New(nil) - - params := &autoscaling.CreateOrUpdateTagsInput{ - Tags: []*autoscaling.Tag{ // Required - { // Required - Key: aws.String("TagKey"), // Required - PropagateAtLaunch: aws.Bool(true), - ResourceId: aws.String("XmlString"), - ResourceType: aws.String("XmlString"), - Value: aws.String("TagValue"), - }, - // More values... - }, - } - resp, err := svc.CreateOrUpdateTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteAutoScalingGroup() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ForceDelete: aws.Bool(true), - } - resp, err := svc.DeleteAutoScalingGroup(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteLaunchConfiguration() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteLaunchConfigurationInput{ - LaunchConfigurationName: aws.String("ResourceName"), // Required - } - resp, err := svc.DeleteLaunchConfiguration(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteLifecycleHook() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteLifecycleHookInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - LifecycleHookName: aws.String("AsciiStringMaxLen255"), // Required - } - resp, err := svc.DeleteLifecycleHook(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteNotificationConfiguration() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteNotificationConfigurationInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - TopicARN: aws.String("ResourceName"), // Required - } - resp, err := svc.DeleteNotificationConfiguration(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeletePolicy() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeletePolicyInput{ - PolicyName: aws.String("ResourceName"), // Required - AutoScalingGroupName: aws.String("ResourceName"), - } - resp, err := svc.DeletePolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteScheduledAction() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteScheduledActionInput{ - ScheduledActionName: aws.String("ResourceName"), // Required - AutoScalingGroupName: aws.String("ResourceName"), - } - resp, err := svc.DeleteScheduledAction(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DeleteTags() { - svc := autoscaling.New(nil) - - params := &autoscaling.DeleteTagsInput{ - Tags: []*autoscaling.Tag{ // Required - { // Required - Key: aws.String("TagKey"), // Required - PropagateAtLaunch: aws.Bool(true), - ResourceId: aws.String("XmlString"), - ResourceType: aws.String("XmlString"), - Value: aws.String("TagValue"), - }, - // More values... - }, - } - resp, err := svc.DeleteTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeAccountLimits() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeAccountLimitsInput - resp, err := svc.DescribeAccountLimits(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeAdjustmentTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeAdjustmentTypesInput - resp, err := svc.DescribeAdjustmentTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeAutoScalingGroups() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeAutoScalingGroupsInput{ - AutoScalingGroupNames: []*string{ - aws.String("ResourceName"), // Required - // More values... - }, - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeAutoScalingGroups(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeAutoScalingInstances() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeAutoScalingInstancesInput{ - InstanceIds: []*string{ - aws.String("XmlStringMaxLen16"), // Required - // More values... - }, - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeAutoScalingInstances(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeAutoScalingNotificationTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeAutoScalingNotificationTypesInput - resp, err := svc.DescribeAutoScalingNotificationTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeLaunchConfigurations() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeLaunchConfigurationsInput{ - LaunchConfigurationNames: []*string{ - aws.String("ResourceName"), // Required - // More values... - }, - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeLaunchConfigurations(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeLifecycleHookTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeLifecycleHookTypesInput - resp, err := svc.DescribeLifecycleHookTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeLifecycleHooks() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeLifecycleHooksInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - LifecycleHookNames: []*string{ - aws.String("AsciiStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.DescribeLifecycleHooks(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeLoadBalancers() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeLoadBalancersInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeLoadBalancers(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeMetricCollectionTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeMetricCollectionTypesInput - resp, err := svc.DescribeMetricCollectionTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeNotificationConfigurations() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeNotificationConfigurationsInput{ - AutoScalingGroupNames: []*string{ - aws.String("ResourceName"), // Required - // More values... - }, - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeNotificationConfigurations(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribePolicies() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribePoliciesInput{ - AutoScalingGroupName: aws.String("ResourceName"), - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - PolicyNames: []*string{ - aws.String("ResourceName"), // Required - // More values... - }, - PolicyTypes: []*string{ - aws.String("XmlStringMaxLen64"), // Required - // More values... - }, - } - resp, err := svc.DescribePolicies(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeScalingActivities() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeScalingActivitiesInput{ - ActivityIds: []*string{ - aws.String("XmlString"), // Required - // More values... - }, - AutoScalingGroupName: aws.String("ResourceName"), - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeScalingActivities(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeScalingProcessTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeScalingProcessTypesInput - resp, err := svc.DescribeScalingProcessTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeScheduledActions() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeScheduledActionsInput{ - AutoScalingGroupName: aws.String("ResourceName"), - EndTime: aws.Time(time.Now()), - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - ScheduledActionNames: []*string{ - aws.String("ResourceName"), // Required - // More values... - }, - StartTime: aws.Time(time.Now()), - } - resp, err := svc.DescribeScheduledActions(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeTags() { - svc := autoscaling.New(nil) - - params := &autoscaling.DescribeTagsInput{ - Filters: []*autoscaling.Filter{ - { // Required - Name: aws.String("XmlString"), - Values: []*string{ - aws.String("XmlString"), // Required - // More values... - }, - }, - // More values... - }, - MaxRecords: aws.Int64(1), - NextToken: aws.String("XmlString"), - } - resp, err := svc.DescribeTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DescribeTerminationPolicyTypes() { - svc := autoscaling.New(nil) - - var params *autoscaling.DescribeTerminationPolicyTypesInput - resp, err := svc.DescribeTerminationPolicyTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DetachInstances() { - svc := autoscaling.New(nil) - - params := &autoscaling.DetachInstancesInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ShouldDecrementDesiredCapacity: aws.Bool(true), // Required - InstanceIds: []*string{ - aws.String("XmlStringMaxLen16"), // Required - // More values... - }, - } - resp, err := svc.DetachInstances(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DetachLoadBalancers() { - svc := autoscaling.New(nil) - - params := &autoscaling.DetachLoadBalancersInput{ - AutoScalingGroupName: aws.String("ResourceName"), - LoadBalancerNames: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.DetachLoadBalancers(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_DisableMetricsCollection() { - svc := autoscaling.New(nil) - - params := &autoscaling.DisableMetricsCollectionInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - Metrics: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.DisableMetricsCollection(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_EnableMetricsCollection() { - svc := autoscaling.New(nil) - - params := &autoscaling.EnableMetricsCollectionInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - Granularity: aws.String("XmlStringMaxLen255"), // Required - Metrics: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.EnableMetricsCollection(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_EnterStandby() { - svc := autoscaling.New(nil) - - params := &autoscaling.EnterStandbyInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ShouldDecrementDesiredCapacity: aws.Bool(true), // Required - InstanceIds: []*string{ - aws.String("XmlStringMaxLen16"), // Required - // More values... - }, - } - resp, err := svc.EnterStandby(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_ExecutePolicy() { - svc := autoscaling.New(nil) - - params := &autoscaling.ExecutePolicyInput{ - PolicyName: aws.String("ResourceName"), // Required - AutoScalingGroupName: aws.String("ResourceName"), - BreachThreshold: aws.Float64(1.0), - HonorCooldown: aws.Bool(true), - MetricValue: aws.Float64(1.0), - } - resp, err := svc.ExecutePolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_ExitStandby() { - svc := autoscaling.New(nil) - - params := &autoscaling.ExitStandbyInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - InstanceIds: []*string{ - aws.String("XmlStringMaxLen16"), // Required - // More values... - }, - } - resp, err := svc.ExitStandby(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_PutLifecycleHook() { - svc := autoscaling.New(nil) - - params := &autoscaling.PutLifecycleHookInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - LifecycleHookName: aws.String("AsciiStringMaxLen255"), // Required - DefaultResult: aws.String("LifecycleActionResult"), - HeartbeatTimeout: aws.Int64(1), - LifecycleTransition: aws.String("LifecycleTransition"), - NotificationMetadata: aws.String("XmlStringMaxLen1023"), - NotificationTargetARN: aws.String("ResourceName"), - RoleARN: aws.String("ResourceName"), - } - resp, err := svc.PutLifecycleHook(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_PutNotificationConfiguration() { - svc := autoscaling.New(nil) - - params := &autoscaling.PutNotificationConfigurationInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - NotificationTypes: []*string{ // Required - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - TopicARN: aws.String("ResourceName"), // Required - } - resp, err := svc.PutNotificationConfiguration(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_PutScalingPolicy() { - svc := autoscaling.New(nil) - - params := &autoscaling.PutScalingPolicyInput{ - AdjustmentType: aws.String("XmlStringMaxLen255"), // Required - AutoScalingGroupName: aws.String("ResourceName"), // Required - PolicyName: aws.String("XmlStringMaxLen255"), // Required - Cooldown: aws.Int64(1), - EstimatedInstanceWarmup: aws.Int64(1), - MetricAggregationType: aws.String("XmlStringMaxLen32"), - MinAdjustmentMagnitude: aws.Int64(1), - MinAdjustmentStep: aws.Int64(1), - PolicyType: aws.String("XmlStringMaxLen64"), - ScalingAdjustment: aws.Int64(1), - StepAdjustments: []*autoscaling.StepAdjustment{ - { // Required - ScalingAdjustment: aws.Int64(1), // Required - MetricIntervalLowerBound: aws.Float64(1.0), - MetricIntervalUpperBound: aws.Float64(1.0), - }, - // More values... - }, - } - resp, err := svc.PutScalingPolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_PutScheduledUpdateGroupAction() { - svc := autoscaling.New(nil) - - params := &autoscaling.PutScheduledUpdateGroupActionInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ScheduledActionName: aws.String("XmlStringMaxLen255"), // Required - DesiredCapacity: aws.Int64(1), - EndTime: aws.Time(time.Now()), - MaxSize: aws.Int64(1), - MinSize: aws.Int64(1), - Recurrence: aws.String("XmlStringMaxLen255"), - StartTime: aws.Time(time.Now()), - Time: aws.Time(time.Now()), - } - resp, err := svc.PutScheduledUpdateGroupAction(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_RecordLifecycleActionHeartbeat() { - svc := autoscaling.New(nil) - - params := &autoscaling.RecordLifecycleActionHeartbeatInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - LifecycleActionToken: aws.String("LifecycleActionToken"), // Required - LifecycleHookName: aws.String("AsciiStringMaxLen255"), // Required - } - resp, err := svc.RecordLifecycleActionHeartbeat(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_ResumeProcesses() { - svc := autoscaling.New(nil) - - params := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ScalingProcesses: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.ResumeProcesses(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_SetDesiredCapacity() { - svc := autoscaling.New(nil) - - params := &autoscaling.SetDesiredCapacityInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - DesiredCapacity: aws.Int64(1), // Required - HonorCooldown: aws.Bool(true), - } - resp, err := svc.SetDesiredCapacity(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_SetInstanceHealth() { - svc := autoscaling.New(nil) - - params := &autoscaling.SetInstanceHealthInput{ - HealthStatus: aws.String("XmlStringMaxLen32"), // Required - InstanceId: aws.String("XmlStringMaxLen16"), // Required - ShouldRespectGracePeriod: aws.Bool(true), - } - resp, err := svc.SetInstanceHealth(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_SuspendProcesses() { - svc := autoscaling.New(nil) - - params := &autoscaling.ScalingProcessQuery{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - ScalingProcesses: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - } - resp, err := svc.SuspendProcesses(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_TerminateInstanceInAutoScalingGroup() { - svc := autoscaling.New(nil) - - params := &autoscaling.TerminateInstanceInAutoScalingGroupInput{ - InstanceId: aws.String("XmlStringMaxLen16"), // Required - ShouldDecrementDesiredCapacity: aws.Bool(true), // Required - } - resp, err := svc.TerminateInstanceInAutoScalingGroup(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleAutoScaling_UpdateAutoScalingGroup() { - svc := autoscaling.New(nil) - - params := &autoscaling.UpdateAutoScalingGroupInput{ - AutoScalingGroupName: aws.String("ResourceName"), // Required - AvailabilityZones: []*string{ - aws.String("XmlStringMaxLen255"), // Required - // More values... - }, - DefaultCooldown: aws.Int64(1), - DesiredCapacity: aws.Int64(1), - HealthCheckGracePeriod: aws.Int64(1), - HealthCheckType: aws.String("XmlStringMaxLen32"), - LaunchConfigurationName: aws.String("ResourceName"), - MaxSize: aws.Int64(1), - MinSize: aws.Int64(1), - PlacementGroup: aws.String("XmlStringMaxLen255"), - TerminationPolicies: []*string{ - aws.String("XmlStringMaxLen1600"), // Required - // More values... - }, - VPCZoneIdentifier: aws.String("XmlStringMaxLen255"), - } - resp, err := svc.UpdateAutoScalingGroup(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} 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 38617b1ffee..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface_test.go deleted file mode 100644 index 3941d260db0..00000000000 --- 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 6da3b190cc2..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/ec2/examples_test.go +++ /dev/null @@ -1,5164 +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/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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleEC2_CancelExportTask() { - svc := ec2.New(nil) - - params := &ec2.CancelExportTaskInput{ - ExportTaskId: aws.String("String"), // Required - } - resp, err := svc.CancelExportTask(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleEC2_CancelReservedInstancesListing() { - svc := ec2.New(nil) - - params := &ec2.CancelReservedInstancesListingInput{ - ReservedInstancesListingId: aws.String("String"), // Required - } - resp, err := svc.CancelReservedInstancesListing(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleEC2_CreateInternetGateway() { - svc := ec2.New(nil) - - params := &ec2.CreateInternetGatewayInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.CreateInternetGateway(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleEC2_DeleteSpotDatafeedSubscription() { - svc := ec2.New(nil) - - params := &ec2.DeleteSpotDatafeedSubscriptionInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.DeleteSpotDatafeedSubscription(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleEC2_DescribeSpotDatafeedSubscription() { - svc := ec2.New(nil) - - params := &ec2.DescribeSpotDatafeedSubscriptionInput{ - DryRun: aws.Bool(true), - } - resp, err := svc.DescribeSpotDatafeedSubscription(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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("OperationType"), - 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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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("OperationType"), - UserIds: []*string{ - aws.String("String"), // Required - // More values... - }, - } - resp, err := svc.ModifySnapshotAttribute(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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... - }, - SpotPrice: aws.String("String"), - SubnetId: aws.String("String"), - UserData: aws.String("String"), - WeightedCapacity: aws.Float64(1.0), - }, - // More values... - }, - SpotPrice: aws.String("String"), // Required - TargetCapacity: aws.Int64(1), // Required - AllocationStrategy: aws.String("AllocationStrategy"), - 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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(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 { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/elbiface/interface_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/elbiface/interface_test.go deleted file mode 100644 index acf9105707f..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/elbiface/interface_test.go +++ /dev/null @@ -1,15 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package elbiface_test - -import ( - "testing" - - "github.com/aws/aws-sdk-go/service/elb" - "github.com/aws/aws-sdk-go/service/elb/elbiface" - "github.com/stretchr/testify/assert" -) - -func TestInterface(t *testing.T) { - assert.Implements(t, (*elbiface.ELBAPI)(nil), elb.New(nil)) -} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/examples_test.go deleted file mode 100644 index 765c050eaaf..00000000000 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/elb/examples_test.go +++ /dev/null @@ -1,721 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. - -package elb_test - -import ( - "bytes" - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/elb" -) - -var _ time.Duration -var _ bytes.Buffer - -func ExampleELB_AddTags() { - svc := elb.New(nil) - - params := &elb.AddTagsInput{ - LoadBalancerNames: []*string{ // Required - aws.String("AccessPointName"), // Required - // More values... - }, - Tags: []*elb.Tag{ // Required - { // Required - Key: aws.String("TagKey"), // Required - Value: aws.String("TagValue"), - }, - // More values... - }, - } - resp, err := svc.AddTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_ApplySecurityGroupsToLoadBalancer() { - svc := elb.New(nil) - - params := &elb.ApplySecurityGroupsToLoadBalancerInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - SecurityGroups: []*string{ // Required - aws.String("SecurityGroupId"), // Required - // More values... - }, - } - resp, err := svc.ApplySecurityGroupsToLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_AttachLoadBalancerToSubnets() { - svc := elb.New(nil) - - params := &elb.AttachLoadBalancerToSubnetsInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - Subnets: []*string{ // Required - aws.String("SubnetId"), // Required - // More values... - }, - } - resp, err := svc.AttachLoadBalancerToSubnets(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_ConfigureHealthCheck() { - svc := elb.New(nil) - - params := &elb.ConfigureHealthCheckInput{ - HealthCheck: &elb.HealthCheck{ // Required - HealthyThreshold: aws.Int64(1), // Required - Interval: aws.Int64(1), // Required - Target: aws.String("HealthCheckTarget"), // Required - Timeout: aws.Int64(1), // Required - UnhealthyThreshold: aws.Int64(1), // Required - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.ConfigureHealthCheck(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_CreateAppCookieStickinessPolicy() { - svc := elb.New(nil) - - params := &elb.CreateAppCookieStickinessPolicyInput{ - CookieName: aws.String("CookieName"), // Required - LoadBalancerName: aws.String("AccessPointName"), // Required - PolicyName: aws.String("PolicyName"), // Required - } - resp, err := svc.CreateAppCookieStickinessPolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_CreateLBCookieStickinessPolicy() { - svc := elb.New(nil) - - params := &elb.CreateLBCookieStickinessPolicyInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - PolicyName: aws.String("PolicyName"), // Required - CookieExpirationPeriod: aws.Int64(1), - } - resp, err := svc.CreateLBCookieStickinessPolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_CreateLoadBalancer() { - svc := elb.New(nil) - - params := &elb.CreateLoadBalancerInput{ - Listeners: []*elb.Listener{ // Required - { // Required - InstancePort: aws.Int64(1), // Required - LoadBalancerPort: aws.Int64(1), // Required - Protocol: aws.String("Protocol"), // Required - InstanceProtocol: aws.String("Protocol"), - SSLCertificateId: aws.String("SSLCertificateId"), - }, - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - AvailabilityZones: []*string{ - aws.String("AvailabilityZone"), // Required - // More values... - }, - Scheme: aws.String("LoadBalancerScheme"), - SecurityGroups: []*string{ - aws.String("SecurityGroupId"), // Required - // More values... - }, - Subnets: []*string{ - aws.String("SubnetId"), // Required - // More values... - }, - Tags: []*elb.Tag{ - { // Required - Key: aws.String("TagKey"), // Required - Value: aws.String("TagValue"), - }, - // More values... - }, - } - resp, err := svc.CreateLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_CreateLoadBalancerListeners() { - svc := elb.New(nil) - - params := &elb.CreateLoadBalancerListenersInput{ - Listeners: []*elb.Listener{ // Required - { // Required - InstancePort: aws.Int64(1), // Required - LoadBalancerPort: aws.Int64(1), // Required - Protocol: aws.String("Protocol"), // Required - InstanceProtocol: aws.String("Protocol"), - SSLCertificateId: aws.String("SSLCertificateId"), - }, - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.CreateLoadBalancerListeners(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_CreateLoadBalancerPolicy() { - svc := elb.New(nil) - - params := &elb.CreateLoadBalancerPolicyInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - PolicyName: aws.String("PolicyName"), // Required - PolicyTypeName: aws.String("PolicyTypeName"), // Required - PolicyAttributes: []*elb.PolicyAttribute{ - { // Required - AttributeName: aws.String("AttributeName"), - AttributeValue: aws.String("AttributeValue"), - }, - // More values... - }, - } - resp, err := svc.CreateLoadBalancerPolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DeleteLoadBalancer() { - svc := elb.New(nil) - - params := &elb.DeleteLoadBalancerInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.DeleteLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DeleteLoadBalancerListeners() { - svc := elb.New(nil) - - params := &elb.DeleteLoadBalancerListenersInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - LoadBalancerPorts: []*int64{ // Required - aws.Int64(1), // Required - // More values... - }, - } - resp, err := svc.DeleteLoadBalancerListeners(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DeleteLoadBalancerPolicy() { - svc := elb.New(nil) - - params := &elb.DeleteLoadBalancerPolicyInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - PolicyName: aws.String("PolicyName"), // Required - } - resp, err := svc.DeleteLoadBalancerPolicy(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DeregisterInstancesFromLoadBalancer() { - svc := elb.New(nil) - - params := &elb.DeregisterInstancesFromLoadBalancerInput{ - Instances: []*elb.Instance{ // Required - { // Required - InstanceId: aws.String("InstanceId"), - }, - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.DeregisterInstancesFromLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeInstanceHealth() { - svc := elb.New(nil) - - params := &elb.DescribeInstanceHealthInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - Instances: []*elb.Instance{ - { // Required - InstanceId: aws.String("InstanceId"), - }, - // More values... - }, - } - resp, err := svc.DescribeInstanceHealth(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeLoadBalancerAttributes() { - svc := elb.New(nil) - - params := &elb.DescribeLoadBalancerAttributesInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.DescribeLoadBalancerAttributes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeLoadBalancerPolicies() { - svc := elb.New(nil) - - params := &elb.DescribeLoadBalancerPoliciesInput{ - LoadBalancerName: aws.String("AccessPointName"), - PolicyNames: []*string{ - aws.String("PolicyName"), // Required - // More values... - }, - } - resp, err := svc.DescribeLoadBalancerPolicies(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeLoadBalancerPolicyTypes() { - svc := elb.New(nil) - - params := &elb.DescribeLoadBalancerPolicyTypesInput{ - PolicyTypeNames: []*string{ - aws.String("PolicyTypeName"), // Required - // More values... - }, - } - resp, err := svc.DescribeLoadBalancerPolicyTypes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeLoadBalancers() { - svc := elb.New(nil) - - params := &elb.DescribeLoadBalancersInput{ - LoadBalancerNames: []*string{ - aws.String("AccessPointName"), // Required - // More values... - }, - Marker: aws.String("Marker"), - PageSize: aws.Int64(1), - } - resp, err := svc.DescribeLoadBalancers(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DescribeTags() { - svc := elb.New(nil) - - params := &elb.DescribeTagsInput{ - LoadBalancerNames: []*string{ // Required - aws.String("AccessPointName"), // Required - // More values... - }, - } - resp, err := svc.DescribeTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DetachLoadBalancerFromSubnets() { - svc := elb.New(nil) - - params := &elb.DetachLoadBalancerFromSubnetsInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - Subnets: []*string{ // Required - aws.String("SubnetId"), // Required - // More values... - }, - } - resp, err := svc.DetachLoadBalancerFromSubnets(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_DisableAvailabilityZonesForLoadBalancer() { - svc := elb.New(nil) - - params := &elb.DisableAvailabilityZonesForLoadBalancerInput{ - AvailabilityZones: []*string{ // Required - aws.String("AvailabilityZone"), // Required - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.DisableAvailabilityZonesForLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_EnableAvailabilityZonesForLoadBalancer() { - svc := elb.New(nil) - - params := &elb.EnableAvailabilityZonesForLoadBalancerInput{ - AvailabilityZones: []*string{ // Required - aws.String("AvailabilityZone"), // Required - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.EnableAvailabilityZonesForLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_ModifyLoadBalancerAttributes() { - svc := elb.New(nil) - - params := &elb.ModifyLoadBalancerAttributesInput{ - LoadBalancerAttributes: &elb.LoadBalancerAttributes{ // Required - AccessLog: &elb.AccessLog{ - Enabled: aws.Bool(true), // Required - EmitInterval: aws.Int64(1), - S3BucketName: aws.String("S3BucketName"), - S3BucketPrefix: aws.String("AccessLogPrefix"), - }, - AdditionalAttributes: []*elb.AdditionalAttribute{ - { // Required - Key: aws.String("StringVal"), - Value: aws.String("StringVal"), - }, - // More values... - }, - ConnectionDraining: &elb.ConnectionDraining{ - Enabled: aws.Bool(true), // Required - Timeout: aws.Int64(1), - }, - ConnectionSettings: &elb.ConnectionSettings{ - IdleTimeout: aws.Int64(1), // Required - }, - CrossZoneLoadBalancing: &elb.CrossZoneLoadBalancing{ - Enabled: aws.Bool(true), // Required - }, - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.ModifyLoadBalancerAttributes(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_RegisterInstancesWithLoadBalancer() { - svc := elb.New(nil) - - params := &elb.RegisterInstancesWithLoadBalancerInput{ - Instances: []*elb.Instance{ // Required - { // Required - InstanceId: aws.String("InstanceId"), - }, - // More values... - }, - LoadBalancerName: aws.String("AccessPointName"), // Required - } - resp, err := svc.RegisterInstancesWithLoadBalancer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_RemoveTags() { - svc := elb.New(nil) - - params := &elb.RemoveTagsInput{ - LoadBalancerNames: []*string{ // Required - aws.String("AccessPointName"), // Required - // More values... - }, - Tags: []*elb.TagKeyOnly{ // Required - { // Required - Key: aws.String("TagKey"), - }, - // More values... - }, - } - resp, err := svc.RemoveTags(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_SetLoadBalancerListenerSSLCertificate() { - svc := elb.New(nil) - - params := &elb.SetLoadBalancerListenerSSLCertificateInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - LoadBalancerPort: aws.Int64(1), // Required - SSLCertificateId: aws.String("SSLCertificateId"), // Required - } - resp, err := svc.SetLoadBalancerListenerSSLCertificate(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_SetLoadBalancerPoliciesForBackendServer() { - svc := elb.New(nil) - - params := &elb.SetLoadBalancerPoliciesForBackendServerInput{ - InstancePort: aws.Int64(1), // Required - LoadBalancerName: aws.String("AccessPointName"), // Required - PolicyNames: []*string{ // Required - aws.String("PolicyName"), // Required - // More values... - }, - } - resp, err := svc.SetLoadBalancerPoliciesForBackendServer(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} - -func ExampleELB_SetLoadBalancerPoliciesOfListener() { - svc := elb.New(nil) - - params := &elb.SetLoadBalancerPoliciesOfListenerInput{ - LoadBalancerName: aws.String("AccessPointName"), // Required - LoadBalancerPort: aws.Int64(1), // Required - PolicyNames: []*string{ // Required - aws.String("PolicyName"), // Required - // More values... - }, - } - resp, err := svc.SetLoadBalancerPoliciesOfListener(params) - - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go deleted file mode 100644 index 0bd0e4e7752..00000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package quantile - -import ( - "testing" -) - -func BenchmarkInsertTargeted(b *testing.B) { - b.ReportAllocs() - - s := NewTargeted(Targets) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiased(b *testing.B) { - s := NewLowBiased(0.01) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { - s := NewLowBiased(0.0001) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkQuery(b *testing.B) { - s := NewTargeted(Targets) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} - -func BenchmarkQuerySmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go deleted file mode 100644 index ab3293aaf2a..00000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build go1.1 - -package quantile_test - -import ( - "bufio" - "fmt" - "log" - "os" - "strconv" - "time" - - "github.com/beorn7/perks/quantile" -) - -func Example_simple() { - ch := make(chan float64) - go sendFloats(ch) - - // Compute the 50th, 90th, and 99th percentile. - q := quantile.NewTargeted(map[float64]float64{ - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - }) - for v := range ch { - q.Insert(v) - } - - fmt.Println("perc50:", q.Query(0.50)) - fmt.Println("perc90:", q.Query(0.90)) - fmt.Println("perc99:", q.Query(0.99)) - fmt.Println("count:", q.Count()) - // Output: - // perc50: 5 - // perc90: 16 - // perc99: 223 - // count: 2388 -} - -func Example_mergeMultipleStreams() { - // Scenario: - // We have multiple database shards. On each shard, there is a process - // collecting query response times from the database logs and inserting - // them into a Stream (created via NewTargeted(0.90)), much like the - // Simple example. These processes expose a network interface for us to - // ask them to serialize and send us the results of their - // Stream.Samples so we may Merge and Query them. - // - // NOTES: - // * These sample sets are small, allowing us to get them - // across the network much faster than sending the entire list of data - // points. - // - // * For this to work correctly, we must supply the same quantiles - // a priori the process collecting the samples supplied to NewTargeted, - // even if we do not plan to query them all here. - ch := make(chan quantile.Samples) - getDBQuerySamples(ch) - q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) - for samples := range ch { - q.Merge(samples) - } - fmt.Println("perc90:", q.Query(0.90)) -} - -func Example_window() { - // Scenario: We want the 90th, 95th, and 99th percentiles for each - // minute. - - ch := make(chan float64) - go sendStreamValues(ch) - - tick := time.NewTicker(1 * time.Minute) - q := quantile.NewTargeted(map[float64]float64{ - 0.90: 0.001, - 0.95: 0.0005, - 0.99: 0.0001, - }) - for { - select { - case t := <-tick.C: - flushToDB(t, q.Samples()) - q.Reset() - case v := <-ch: - q.Insert(v) - } - } -} - -func sendStreamValues(ch chan float64) { - // Use your imagination -} - -func flushToDB(t time.Time, samples quantile.Samples) { - // Use your imagination -} - -// This is a stub for the above example. In reality this would hit the remote -// servers via http or something like it. -func getDBQuerySamples(ch chan quantile.Samples) {} - -func sendFloats(ch chan<- float64) { - f, err := os.Open("exampledata.txt") - if err != nil { - log.Fatal(err) - } - sc := bufio.NewScanner(f) - for sc.Scan() { - b := sc.Bytes() - v, err := strconv.ParseFloat(string(b), 64) - if err != nil { - log.Fatal(err) - } - ch <- v - } - if sc.Err() != nil { - log.Fatal(sc.Err()) - } - close(ch) -} diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go deleted file mode 100644 index 4dba05449cb..00000000000 --- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package quantile - -import ( - "math" - "math/rand" - "sort" - "testing" -) - -var ( - Targets = map[float64]float64{ - 0.01: 0.001, - 0.10: 0.01, - 0.50: 0.05, - 0.90: 0.01, - 0.99: 0.001, - } - TargetsSmallEpsilon = map[float64]float64{ - 0.01: 0.0001, - 0.10: 0.001, - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - } - LowQuantiles = []float64{0.01, 0.1, 0.5} - HighQuantiles = []float64{0.99, 0.9, 0.5} -) - -const RelativeEpsilon = 0.01 - -func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for quantile, epsilon := range Targets { - n := float64(len(a)) - k := int(quantile * n) - lower := int((quantile - epsilon) * n) - if lower < 1 { - lower = 1 - } - upper := int(math.Ceil((quantile + epsilon) * n)) - if upper > len(a) { - upper = len(a) - } - w, min, max := a[k-1], a[lower-1], a[upper-1] - if g := s.Query(quantile); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) - } - } -} - -func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range LowQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - RelativeEpsilon) * qu * n) - upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range HighQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) - upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func populateStream(s *Stream) []float64 { - a := make([]float64, 0, 1e5+100) - for i := 0; i < cap(a); i++ { - v := rand.NormFloat64() - // Add 5% asymmetric outliers. - if i%20 == 0 { - v = v*v + 1 - } - s.Insert(v) - a = append(a, v) - } - return a -} - -func TestTargetedQuery(t *testing.T) { - rand.Seed(42) - s := NewTargeted(Targets) - a := populateStream(s) - verifyPercsWithAbsoluteEpsilon(t, a, s) -} - -func TestLowBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewLowBiased(RelativeEpsilon) - a := populateStream(s) - verifyLowPercsWithRelativeEpsilon(t, a, s) -} - -func TestHighBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewHighBiased(RelativeEpsilon) - a := populateStream(s) - verifyHighPercsWithRelativeEpsilon(t, a, s) -} - -// BrokenTestTargetedMerge is broken, see Merge doc comment. -func BrokenTestTargetedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewTargeted(Targets) - s2 := NewTargeted(Targets) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyPercsWithAbsoluteEpsilon(t, a, s1) -} - -// BrokenTestLowBiasedMerge is broken, see Merge doc comment. -func BrokenTestLowBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewLowBiased(RelativeEpsilon) - s2 := NewLowBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyLowPercsWithRelativeEpsilon(t, a, s2) -} - -// BrokenTestHighBiasedMerge is broken, see Merge doc comment. -func BrokenTestHighBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewHighBiased(RelativeEpsilon) - s2 := NewHighBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyHighPercsWithRelativeEpsilon(t, a, s2) -} - -func TestUncompressed(t *testing.T) { - q := NewTargeted(Targets) - for i := 100; i > 0; i-- { - q.Insert(float64(i)) - } - if g := q.Count(); g != 100 { - t.Errorf("want count 100, got %d", g) - } - // Before compression, Query should have 100% accuracy. - for quantile := range Targets { - w := quantile * 100 - if g := q.Query(quantile); g != w { - t.Errorf("want %f, got %f", w, g) - } - } -} - -func TestUncompressedSamples(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.001}) - for i := 1; i <= 100; i++ { - q.Insert(float64(i)) - } - if g := q.Samples().Len(); g != 100 { - t.Errorf("want count 100, got %d", g) - } -} - -func TestUncompressedOne(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.01}) - q.Insert(3.14) - if g := q.Query(0.90); g != 3.14 { - t.Error("want PI, got", g) - } -} - -func TestDefaults(t *testing.T) { - if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { - t.Errorf("want 0, got %f", g) - } -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/negroni/logger_test.go b/Godeps/_workspace/src/github.com/codegangsta/negroni/logger_test.go deleted file mode 100644 index 880337d1a9b..00000000000 --- a/Godeps/_workspace/src/github.com/codegangsta/negroni/logger_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package negroni - -import ( - "bytes" - "log" - "net/http" - "net/http/httptest" - "testing" -) - -func Test_Logger(t *testing.T) { - buff := bytes.NewBufferString("") - recorder := httptest.NewRecorder() - - l := NewLogger() - l.Logger = log.New(buff, "[negroni] ", 0) - - n := New() - // replace log for testing - n.Use(l) - n.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - })) - - req, err := http.NewRequest("GET", "http://localhost:3000/foobar", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(recorder, req) - expect(t, recorder.Code, http.StatusNotFound) - refute(t, len(buff.String()), 0) -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/negroni/negroni_test.go b/Godeps/_workspace/src/github.com/codegangsta/negroni/negroni_test.go deleted file mode 100644 index 9fac0085617..00000000000 --- a/Godeps/_workspace/src/github.com/codegangsta/negroni/negroni_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package negroni - -import ( - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -/* Test Helpers */ -func expect(t *testing.T, a interface{}, b interface{}) { - if a != b { - t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func refute(t *testing.T, a interface{}, b interface{}) { - if a == b { - t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func TestNegroniRun(t *testing.T) { - // just test that Run doesn't bomb - go New().Run(":3000") -} - -func TestNegroniServeHTTP(t *testing.T) { - result := "" - response := httptest.NewRecorder() - - n := New() - n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { - result += "foo" - next(rw, r) - result += "ban" - })) - n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { - result += "bar" - next(rw, r) - result += "baz" - })) - n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { - result += "bat" - rw.WriteHeader(http.StatusBadRequest) - })) - - n.ServeHTTP(response, (*http.Request)(nil)) - - expect(t, result, "foobarbatbazban") - expect(t, response.Code, http.StatusBadRequest) -} - -// Ensures that a Negroni middleware chain -// can correctly return all of its handlers. -func TestHandlers(t *testing.T) { - response := httptest.NewRecorder() - n := New() - handlers := n.Handlers() - expect(t, 0, len(handlers)) - - n.Use(HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { - rw.WriteHeader(http.StatusOK) - })) - - // Expects the length of handlers to be exactly 1 - // after adding exactly one handler to the middleware chain - handlers = n.Handlers() - expect(t, 1, len(handlers)) - - // Ensures that the first handler that is in sequence behaves - // exactly the same as the one that was registered earlier - handlers[0].ServeHTTP(response, (*http.Request)(nil), nil) - expect(t, response.Code, http.StatusOK) -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/negroni/recovery_test.go b/Godeps/_workspace/src/github.com/codegangsta/negroni/recovery_test.go deleted file mode 100644 index 3fa264acba9..00000000000 --- a/Godeps/_workspace/src/github.com/codegangsta/negroni/recovery_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package negroni - -import ( - "bytes" - "log" - "net/http" - "net/http/httptest" - "testing" -) - -func TestRecovery(t *testing.T) { - buff := bytes.NewBufferString("") - recorder := httptest.NewRecorder() - - rec := NewRecovery() - rec.Logger = log.New(buff, "[negroni] ", 0) - - n := New() - // replace log for testing - n.Use(rec) - n.UseHandler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { - panic("here is a panic!") - })) - n.ServeHTTP(recorder, (*http.Request)(nil)) - expect(t, recorder.Code, http.StatusInternalServerError) - refute(t, recorder.Body.Len(), 0) - refute(t, len(buff.String()), 0) -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/negroni/response_writer_test.go b/Godeps/_workspace/src/github.com/codegangsta/negroni/response_writer_test.go deleted file mode 100644 index ed1ee70a6a2..00000000000 --- a/Godeps/_workspace/src/github.com/codegangsta/negroni/response_writer_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package negroni - -import ( - "bufio" - "net" - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type closeNotifyingRecorder struct { - *httptest.ResponseRecorder - closed chan bool -} - -func newCloseNotifyingRecorder() *closeNotifyingRecorder { - return &closeNotifyingRecorder{ - httptest.NewRecorder(), - make(chan bool, 1), - } -} - -func (c *closeNotifyingRecorder) close() { - c.closed <- true -} - -func (c *closeNotifyingRecorder) CloseNotify() <-chan bool { - return c.closed -} - -type hijackableResponse struct { - Hijacked bool -} - -func newHijackableResponse() *hijackableResponse { - return &hijackableResponse{} -} - -func (h *hijackableResponse) Header() http.Header { return nil } -func (h *hijackableResponse) Write(buf []byte) (int, error) { return 0, nil } -func (h *hijackableResponse) WriteHeader(code int) {} -func (h *hijackableResponse) Flush() {} -func (h *hijackableResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { - h.Hijacked = true - return nil, nil, nil -} - -func TestResponseWriterWritingString(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.Write([]byte("Hello world")) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "Hello world") - expect(t, rw.Status(), http.StatusOK) - expect(t, rw.Size(), 11) - expect(t, rw.Written(), true) -} - -func TestResponseWriterWritingStrings(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.Write([]byte("Hello world")) - rw.Write([]byte("foo bar bat baz")) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "Hello worldfoo bar bat baz") - expect(t, rw.Status(), http.StatusOK) - expect(t, rw.Size(), 26) -} - -func TestResponseWriterWritingHeader(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - rw.WriteHeader(http.StatusNotFound) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "") - expect(t, rw.Status(), http.StatusNotFound) - expect(t, rw.Size(), 0) -} - -func TestResponseWriterBefore(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - result := "" - - rw.Before(func(ResponseWriter) { - result += "foo" - }) - rw.Before(func(ResponseWriter) { - result += "bar" - }) - - rw.WriteHeader(http.StatusNotFound) - - expect(t, rec.Code, rw.Status()) - expect(t, rec.Body.String(), "") - expect(t, rw.Status(), http.StatusNotFound) - expect(t, rw.Size(), 0) - expect(t, result, "barfoo") -} - -func TestResponseWriterHijack(t *testing.T) { - hijackable := newHijackableResponse() - rw := NewResponseWriter(hijackable) - hijacker, ok := rw.(http.Hijacker) - expect(t, ok, true) - _, _, err := hijacker.Hijack() - if err != nil { - t.Error(err) - } - expect(t, hijackable.Hijacked, true) -} - -func TestResponseWriteHijackNotOK(t *testing.T) { - hijackable := new(http.ResponseWriter) - rw := NewResponseWriter(*hijackable) - hijacker, ok := rw.(http.Hijacker) - expect(t, ok, true) - _, _, err := hijacker.Hijack() - - refute(t, err, nil) -} - -func TestResponseWriterCloseNotify(t *testing.T) { - rec := newCloseNotifyingRecorder() - rw := NewResponseWriter(rec) - closed := false - notifier := rw.(http.CloseNotifier).CloseNotify() - rec.close() - select { - case <-notifier: - closed = true - case <-time.After(time.Second): - } - expect(t, closed, true) -} - -func TestResponseWriterFlusher(t *testing.T) { - rec := httptest.NewRecorder() - rw := NewResponseWriter(rec) - - _, ok := rw.(http.Flusher) - expect(t, ok, true) -} diff --git a/Godeps/_workspace/src/github.com/codegangsta/negroni/static_test.go b/Godeps/_workspace/src/github.com/codegangsta/negroni/static_test.go deleted file mode 100644 index 637cfcd68e0..00000000000 --- a/Godeps/_workspace/src/github.com/codegangsta/negroni/static_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package negroni - -import ( - "bytes" - "net/http" - "net/http/httptest" - "testing" -) - -func TestStatic(t *testing.T) { - response := httptest.NewRecorder() - response.Body = new(bytes.Buffer) - - n := New() - n.Use(NewStatic(http.Dir("."))) - - req, err := http.NewRequest("GET", "http://localhost:3000/negroni.go", nil) - if err != nil { - t.Error(err) - } - n.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - expect(t, response.Header().Get("Expires"), "") - if response.Body.Len() == 0 { - t.Errorf("Got empty body for GET request") - } -} - -func TestStaticHead(t *testing.T) { - response := httptest.NewRecorder() - response.Body = new(bytes.Buffer) - - n := New() - n.Use(NewStatic(http.Dir("."))) - n.UseHandler(http.NotFoundHandler()) - - req, err := http.NewRequest("HEAD", "http://localhost:3000/negroni.go", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) - if response.Body.Len() != 0 { - t.Errorf("Got non-empty body for HEAD request") - } -} - -func TestStaticAsPost(t *testing.T) { - response := httptest.NewRecorder() - - n := New() - n.Use(NewStatic(http.Dir("."))) - n.UseHandler(http.NotFoundHandler()) - - req, err := http.NewRequest("POST", "http://localhost:3000/negroni.go", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(response, req) - expect(t, response.Code, http.StatusNotFound) -} - -func TestStaticBadDir(t *testing.T) { - response := httptest.NewRecorder() - - n := Classic() - n.UseHandler(http.NotFoundHandler()) - - req, err := http.NewRequest("GET", "http://localhost:3000/negroni.go", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(response, req) - refute(t, response.Code, http.StatusOK) -} - -func TestStaticOptionsServeIndex(t *testing.T) { - response := httptest.NewRecorder() - - n := New() - s := NewStatic(http.Dir(".")) - s.IndexFile = "negroni.go" - n.Use(s) - - req, err := http.NewRequest("GET", "http://localhost:3000/", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) -} - -func TestStaticOptionsPrefix(t *testing.T) { - response := httptest.NewRecorder() - - n := New() - s := NewStatic(http.Dir(".")) - s.Prefix = "/public" - n.Use(s) - - // Check file content behaviour - req, err := http.NewRequest("GET", "http://localhost:3000/public/negroni.go", nil) - if err != nil { - t.Error(err) - } - - n.ServeHTTP(response, req) - expect(t, response.Code, http.StatusOK) -} 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 26223ff1c85..00000000000 --- 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 4720d8d693e..00000000000 --- 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 223e50f2916..00000000000 --- 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 14a1b00f5a7..00000000000 --- 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 97f6d1110bc..00000000000 --- 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 5904971556d..00000000000 --- 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 279c4e26f8b..00000000000 --- 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 53ebdd4bfde..00000000000 --- 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 7a2bd190a10..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go deleted file mode 100644 index 23e0c56eb33..00000000000 --- 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 87c86b83082..00000000000 --- 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 ced0f06e7be..00000000000 --- 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 43e1dfeb81f..00000000000 --- 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/coreos/go-oidc/http/http_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/http/http_test.go deleted file mode 100644 index 8ec76a246d0..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/http/http_test.go +++ /dev/null @@ -1,380 +0,0 @@ -package http - -import ( - "net/http" - "net/url" - "reflect" - "strings" - "testing" - "time" -) - -func TestCacheControlMaxAgeSuccess(t *testing.T) { - tests := []struct { - hdr string - wantAge time.Duration - wantOK bool - }{ - {"max-age=12", 12 * time.Second, true}, - {"max-age=-12", 0, false}, - {"max-age=0", 0, false}, - {"public, max-age=12", 12 * time.Second, true}, - {"public, max-age=40192, must-revalidate", 40192 * time.Second, true}, - {"public, not-max-age=12, must-revalidate", time.Duration(0), false}, - } - - for i, tt := range tests { - maxAge, ok, err := cacheControlMaxAge(tt.hdr) - if err != nil { - t.Errorf("case %d: err=%v", i, err) - } - if tt.wantAge != maxAge { - t.Errorf("case %d: want=%d got=%d", i, tt.wantAge, maxAge) - } - if tt.wantOK != ok { - t.Errorf("case %d: incorrect ok value: want=%t got=%t", i, tt.wantOK, ok) - } - } -} - -func TestCacheControlMaxAgeFail(t *testing.T) { - tests := []string{ - "max-age=aasdf", - "max-age=", - "max-age", - } - - for i, tt := range tests { - _, ok, err := cacheControlMaxAge(tt) - if ok { - t.Errorf("case %d: want ok=false, got true", i) - } - if err == nil { - t.Errorf("case %d: want non-nil err", i) - } - } -} - -func TestMergeQuery(t *testing.T) { - tests := []struct { - u string - q url.Values - w string - }{ - // No values - { - u: "http://example.com", - q: nil, - w: "http://example.com", - }, - // No additional values - { - u: "http://example.com?foo=bar", - q: nil, - w: "http://example.com?foo=bar", - }, - // Simple addition - { - u: "http://example.com", - q: url.Values{ - "foo": []string{"bar"}, - }, - w: "http://example.com?foo=bar", - }, - // Addition with existing values - { - u: "http://example.com?dog=boo", - q: url.Values{ - "foo": []string{"bar"}, - }, - w: "http://example.com?dog=boo&foo=bar", - }, - // Merge - { - u: "http://example.com?dog=boo", - q: url.Values{ - "dog": []string{"elroy"}, - }, - w: "http://example.com?dog=boo&dog=elroy", - }, - // Add and merge - { - u: "http://example.com?dog=boo", - q: url.Values{ - "dog": []string{"elroy"}, - "foo": []string{"bar"}, - }, - w: "http://example.com?dog=boo&dog=elroy&foo=bar", - }, - // Multivalue merge - { - u: "http://example.com?dog=boo", - q: url.Values{ - "dog": []string{"elroy", "penny"}, - }, - w: "http://example.com?dog=boo&dog=elroy&dog=penny", - }, - } - - for i, tt := range tests { - ur, err := url.Parse(tt.u) - if err != nil { - t.Errorf("case %d: failed parsing test url: %v, error: %v", i, tt.u, err) - } - - got := MergeQuery(*ur, tt.q) - want, err := url.Parse(tt.w) - if err != nil { - t.Errorf("case %d: failed parsing want url: %v, error: %v", i, tt.w, err) - } - - if !reflect.DeepEqual(*want, got) { - t.Errorf("case %d: want: %v, got: %v", i, *want, got) - } - } -} - -func TestExpiresPass(t *testing.T) { - tests := []struct { - date string - exp string - wantTTL time.Duration - wantOK bool - }{ - // Expires and Date properly set - { - date: "Thu, 01 Dec 1983 22:00:00 GMT", - exp: "Fri, 02 Dec 1983 01:00:00 GMT", - wantTTL: 10800 * time.Second, - wantOK: true, - }, - // empty headers - { - date: "", - exp: "", - wantOK: false, - }, - // lack of Expirs short-ciruits Date parsing - { - date: "foo", - exp: "", - wantOK: false, - }, - // lack of Date short-ciruits Expires parsing - { - date: "", - exp: "foo", - wantOK: false, - }, - // no Date - { - exp: "Thu, 01 Dec 1983 22:00:00 GMT", - wantTTL: 0, - wantOK: false, - }, - // no Expires - { - date: "Thu, 01 Dec 1983 22:00:00 GMT", - wantTTL: 0, - wantOK: false, - }, - // Expires < Date - { - date: "Fri, 02 Dec 1983 01:00:00 GMT", - exp: "Thu, 01 Dec 1983 22:00:00 GMT", - wantTTL: 0, - wantOK: false, - }, - } - - for i, tt := range tests { - ttl, ok, err := expires(tt.date, tt.exp) - if err != nil { - t.Errorf("case %d: err=%v", i, err) - } - if tt.wantTTL != ttl { - t.Errorf("case %d: want=%d got=%d", i, tt.wantTTL, ttl) - } - if tt.wantOK != ok { - t.Errorf("case %d: incorrect ok value: want=%t got=%t", i, tt.wantOK, ok) - } - } -} - -func TestExpiresFail(t *testing.T) { - tests := []struct { - date string - exp string - }{ - // malformed Date header - { - date: "foo", - exp: "Fri, 02 Dec 1983 01:00:00 GMT", - }, - // malformed exp header - { - date: "Fri, 02 Dec 1983 01:00:00 GMT", - exp: "bar", - }, - } - - for i, tt := range tests { - _, _, err := expires(tt.date, tt.exp) - if err == nil { - t.Errorf("case %d: expected non-nil error", i) - } - } -} - -func TestCacheablePass(t *testing.T) { - tests := []struct { - headers http.Header - wantTTL time.Duration - wantOK bool - }{ - // valid Cache-Control - { - headers: http.Header{ - "Cache-Control": []string{"max-age=100"}, - }, - wantTTL: 100 * time.Second, - wantOK: true, - }, - // valid Date/Expires - { - headers: http.Header{ - "Date": []string{"Thu, 01 Dec 1983 22:00:00 GMT"}, - "Expires": []string{"Fri, 02 Dec 1983 01:00:00 GMT"}, - }, - wantTTL: 10800 * time.Second, - wantOK: true, - }, - // Cache-Control supersedes Date/Expires - { - headers: http.Header{ - "Cache-Control": []string{"max-age=100"}, - "Date": []string{"Thu, 01 Dec 1983 22:00:00 GMT"}, - "Expires": []string{"Fri, 02 Dec 1983 01:00:00 GMT"}, - }, - wantTTL: 100 * time.Second, - wantOK: true, - }, - // no caching headers - { - headers: http.Header{}, - wantOK: false, - }, - } - - for i, tt := range tests { - ttl, ok, err := Cacheable(tt.headers) - if err != nil { - t.Errorf("case %d: err=%v", i, err) - continue - } - if tt.wantTTL != ttl { - t.Errorf("case %d: want=%d got=%d", i, tt.wantTTL, ttl) - } - if tt.wantOK != ok { - t.Errorf("case %d: incorrect ok value: want=%t got=%t", i, tt.wantOK, ok) - } - } -} - -func TestCacheableFail(t *testing.T) { - tests := []http.Header{ - // invalid Cache-Control short-circuits - http.Header{ - "Cache-Control": []string{"max-age"}, - "Date": []string{"Thu, 01 Dec 1983 22:00:00 GMT"}, - "Expires": []string{"Fri, 02 Dec 1983 01:00:00 GMT"}, - }, - // no Cache-Control, invalid Expires - http.Header{ - "Date": []string{"Thu, 01 Dec 1983 22:00:00 GMT"}, - "Expires": []string{"boo"}, - }, - } - - for i, tt := range tests { - _, _, err := Cacheable(tt) - if err == nil { - t.Errorf("case %d: want non-nil err", i) - } - } -} - -func TestNewResourceLocation(t *testing.T) { - tests := []struct { - ru *url.URL - id string - want string - }{ - { - ru: &url.URL{ - Scheme: "http", - Host: "example.com", - }, - id: "foo", - want: "http://example.com/foo", - }, - // https - { - ru: &url.URL{ - Scheme: "https", - Host: "example.com", - }, - id: "foo", - want: "https://example.com/foo", - }, - // with path - { - ru: &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "one/two/three", - }, - id: "foo", - want: "http://example.com/one/two/three/foo", - }, - // with fragment - { - ru: &url.URL{ - Scheme: "http", - Host: "example.com", - Fragment: "frag", - }, - id: "foo", - want: "http://example.com/foo", - }, - // with query - { - ru: &url.URL{ - Scheme: "http", - Host: "example.com", - RawQuery: "dog=elroy", - }, - id: "foo", - want: "http://example.com/foo", - }, - } - - for i, tt := range tests { - got := NewResourceLocation(tt.ru, tt.id) - if tt.want != got { - t.Errorf("case %d: want=%s, got=%s", i, tt.want, got) - } - } -} - -func TestCopyRequest(t *testing.T) { - r1, err := http.NewRequest("GET", "http://example.com", strings.NewReader("foo")) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - r2 := CopyRequest(r1) - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("Result of CopyRequest incorrect: %#v != %#v", r1, r2) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/http/url_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/http/url_test.go deleted file mode 100644 index 2ab250523f7..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/http/url_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package http - -import ( - "net/url" - "testing" -) - -func TestParseNonEmptyURL(t *testing.T) { - tests := []struct { - u string - ok bool - }{ - {"", false}, - {"http://", false}, - {"example.com", false}, - {"example", false}, - {"http://example", true}, - {"http://example:1234", true}, - {"http://example.com", true}, - {"http://example.com:1234", true}, - } - - for i, tt := range tests { - u, err := ParseNonEmptyURL(tt.u) - if err != nil { - t.Logf("err: %v", err) - if tt.ok { - t.Errorf("case %d: unexpected error: %v", i, err) - } else { - continue - } - } - - if !tt.ok { - t.Errorf("case %d: expected error but got none", i) - continue - } - - uu, err := url.Parse(tt.u) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - - if uu.String() != u.String() { - t.Errorf("case %d: incorrect url value, want: %q, got: %q", i, uu.String(), u.String()) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/claims_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/claims_test.go deleted file mode 100644 index 55e245c07df..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/claims_test.go +++ /dev/null @@ -1,240 +0,0 @@ -package jose - -import ( - "testing" - "time" -) - -func TestString(t *testing.T) { - tests := []struct { - cl Claims - key string - ok bool - err bool - val string - }{ - // ok, no err, claim exists - { - cl: Claims{ - "foo": "bar", - }, - key: "foo", - val: "bar", - ok: true, - err: false, - }, - // no claims - { - cl: Claims{}, - key: "foo", - val: "", - ok: false, - err: false, - }, - // missing claim - { - cl: Claims{ - "foo": "bar", - }, - key: "xxx", - val: "", - ok: false, - err: false, - }, - // unparsable: type - { - cl: Claims{ - "foo": struct{}{}, - }, - key: "foo", - val: "", - ok: false, - err: true, - }, - // unparsable: nil value - { - cl: Claims{ - "foo": nil, - }, - key: "foo", - val: "", - ok: false, - err: true, - }, - } - - for i, tt := range tests { - val, ok, err := tt.cl.StringClaim(tt.key) - - if tt.err && err == nil { - t.Errorf("case %d: want err=non-nil, got err=nil", i) - } else if !tt.err && err != nil { - t.Errorf("case %d: want err=nil, got err=%v", i, err) - } - - if tt.ok != ok { - t.Errorf("case %d: want ok=%v, got ok=%v", i, tt.ok, ok) - } - - if tt.val != val { - t.Errorf("case %d: want val=%v, got val=%v", i, tt.val, val) - } - } -} - -func TestInt64(t *testing.T) { - tests := []struct { - cl Claims - key string - ok bool - err bool - val int64 - }{ - // ok, no err, claim exists - { - cl: Claims{ - "foo": int64(100), - }, - key: "foo", - val: int64(100), - ok: true, - err: false, - }, - // no claims - { - cl: Claims{}, - key: "foo", - val: 0, - ok: false, - err: false, - }, - // missing claim - { - cl: Claims{ - "foo": "bar", - }, - key: "xxx", - val: 0, - ok: false, - err: false, - }, - // unparsable: type - { - cl: Claims{ - "foo": struct{}{}, - }, - key: "foo", - val: 0, - ok: false, - err: true, - }, - // unparsable: nil value - { - cl: Claims{ - "foo": nil, - }, - key: "foo", - val: 0, - ok: false, - err: true, - }, - } - - for i, tt := range tests { - val, ok, err := tt.cl.Int64Claim(tt.key) - - if tt.err && err == nil { - t.Errorf("case %d: want err=non-nil, got err=nil", i) - } else if !tt.err && err != nil { - t.Errorf("case %d: want err=nil, got err=%v", i, err) - } - - if tt.ok != ok { - t.Errorf("case %d: want ok=%v, got ok=%v", i, tt.ok, ok) - } - - if tt.val != val { - t.Errorf("case %d: want val=%v, got val=%v", i, tt.val, val) - } - } -} - -func TestTime(t *testing.T) { - now := time.Now().UTC() - unixNow := now.Unix() - - tests := []struct { - cl Claims - key string - ok bool - err bool - val time.Time - }{ - // ok, no err, claim exists - { - cl: Claims{ - "foo": unixNow, - }, - key: "foo", - val: time.Unix(now.Unix(), 0).UTC(), - ok: true, - err: false, - }, - // no claims - { - cl: Claims{}, - key: "foo", - val: time.Time{}, - ok: false, - err: false, - }, - // missing claim - { - cl: Claims{ - "foo": "bar", - }, - key: "xxx", - val: time.Time{}, - ok: false, - err: false, - }, - // unparsable: type - { - cl: Claims{ - "foo": struct{}{}, - }, - key: "foo", - val: time.Time{}, - ok: false, - err: true, - }, - // unparsable: nil value - { - cl: Claims{ - "foo": nil, - }, - key: "foo", - val: time.Time{}, - ok: false, - err: true, - }, - } - - for i, tt := range tests { - val, ok, err := tt.cl.TimeClaim(tt.key) - - if tt.err && err == nil { - t.Errorf("case %d: want err=non-nil, got err=nil", i) - } else if !tt.err && err != nil { - t.Errorf("case %d: want err=nil, got err=%v", i, err) - } - - if tt.ok != ok { - t.Errorf("case %d: want ok=%v, got ok=%v", i, tt.ok, ok) - } - - if tt.val != val { - t.Errorf("case %d: want val=%v, got val=%v", i, tt.val, val) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwk_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwk_test.go deleted file mode 100644 index 63351c45187..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwk_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package jose - -import ( - "testing" -) - -func TestDecodeBase64URLPaddingOptional(t *testing.T) { - tests := []struct { - encoded string - decoded string - err bool - }{ - { - // With padding - encoded: "VGVjdG9uaWM=", - decoded: "Tectonic", - }, - { - // Without padding - encoded: "VGVjdG9uaWM", - decoded: "Tectonic", - }, - { - // Even More padding - encoded: "VGVjdG9uaQ==", - decoded: "Tectoni", - }, - { - // And take it away! - encoded: "VGVjdG9uaQ", - decoded: "Tectoni", - }, - { - // Too much padding. - encoded: "VGVjdG9uaWNh=", - decoded: "", - err: true, - }, - { - // Too much padding. - encoded: "VGVjdG9uaWNh=", - decoded: "", - err: true, - }, - } - - for i, tt := range tests { - got, err := decodeBase64URLPaddingOptional(tt.encoded) - if tt.err { - if err == nil { - t.Errorf("case %d: expected non-nil err", i) - } - continue - } - - if err != nil { - t.Errorf("case %d: want nil err, got: %v", i, err) - } - - if string(got) != tt.decoded { - t.Errorf("case %d: want=%q, got=%q", i, tt.decoded, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jws_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jws_test.go deleted file mode 100644 index 78c8126106b..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jws_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package jose - -import ( - "strings" - "testing" -) - -type testCase struct{ t string } - -var validInput []testCase - -var invalidInput []testCase - -func init() { - validInput = []testCase{ - { - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", - }, - } - - invalidInput = []testCase{ - // empty - { - "", - }, - // undecodeable - { - "aaa.bbb.ccc", - }, - // missing parts - { - "aaa", - }, - // missing parts - { - "aaa.bbb", - }, - // too many parts - { - "aaa.bbb.ccc.ddd", - }, - // invalid header - // EncodeHeader(map[string]string{"foo": "bar"}) - { - "eyJmb28iOiJiYXIifQ.bbb.ccc", - }, - } -} - -func TestParseJWS(t *testing.T) { - for i, tt := range validInput { - jws, err := ParseJWS(tt.t) - if err != nil { - t.Errorf("test: %d. expected: valid, actual: invalid", i) - } - - expectedHeader := strings.Split(tt.t, ".")[0] - if jws.RawHeader != expectedHeader { - t.Errorf("test: %d. expected: %s, actual: %s", i, expectedHeader, jws.RawHeader) - } - - expectedPayload := strings.Split(tt.t, ".")[1] - if jws.RawPayload != expectedPayload { - t.Errorf("test: %d. expected: %s, actual: %s", i, expectedPayload, jws.RawPayload) - } - } - - for i, tt := range invalidInput { - _, err := ParseJWS(tt.t) - if err == nil { - t.Errorf("test: %d. expected: invalid, actual: valid", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwt_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwt_test.go deleted file mode 100644 index 3a1cd9ae156..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/jwt_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package jose - -import ( - "reflect" - "testing" -) - -func TestParseJWT(t *testing.T) { - tests := []struct { - r string - h JOSEHeader - c Claims - }{ - { - // Example from JWT spec: - // http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#ExampleJWT - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", - JOSEHeader{ - HeaderMediaType: "JWT", - HeaderKeyAlgorithm: "HS256", - }, - Claims{ - "iss": "joe", - // NOTE: test numbers must be floats for equality checks to work since values are converted form interface{} to float64 by default. - "exp": 1300819380.0, - "http://example.com/is_root": true, - }, - }, - } - - for i, tt := range tests { - jwt, err := ParseJWT(tt.r) - if err != nil { - t.Errorf("raw token should parse. test: %d. expected: valid, actual: invalid. err=%v", i, err) - } - - if !reflect.DeepEqual(tt.h, jwt.Header) { - t.Errorf("JOSE headers should match. test: %d. expected: %v, actual: %v", i, tt.h, jwt.Header) - } - - claims, err := jwt.Claims() - if err != nil { - t.Errorf("test: %d. expected: valid claim parsing. err=%v", i, err) - } - if !reflect.DeepEqual(tt.c, claims) { - t.Errorf("claims should match. test: %d. expected: %v, actual: %v", i, tt.c, claims) - } - - enc := jwt.Encode() - if enc != tt.r { - t.Errorf("encoded jwt should match raw jwt. test: %d. expected: %v, actual: %v", i, tt.r, enc) - } - } -} - -func TestNewJWTHeaderTyp(t *testing.T) { - jwt, err := NewJWT(JOSEHeader{}, Claims{}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - want := "JWT" - got := jwt.Header[HeaderMediaType] - if want != got { - t.Fatalf("Header %q incorrect: want=%s got=%s", HeaderMediaType, want, got) - } - -} - -func TestNewJWTHeaderKeyID(t *testing.T) { - jwt, err := NewJWT(JOSEHeader{HeaderKeyID: "foo"}, Claims{}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - want := "foo" - got, ok := jwt.KeyID() - if !ok { - t.Fatalf("KeyID not set") - } else if want != got { - t.Fatalf("KeyID incorrect: want=%s got=%s", want, got) - } -} - -func TestNewJWTHeaderKeyIDNotSet(t *testing.T) { - jwt, err := NewJWT(JOSEHeader{}, Claims{}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - if _, ok := jwt.KeyID(); ok { - t.Fatalf("KeyID set, but should not be") - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/sig_hmac_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/sig_hmac_test.go deleted file mode 100644 index 76c6722fd42..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/jose/sig_hmac_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package jose - -import ( - "bytes" - "encoding/base64" - "testing" -) - -var hmacTestCases = []struct { - data string - sig string - jwk JWK - valid bool - desc string -}{ - { - "test", - "Aymga2LNFrM-tnkr6MYLFY2Jou46h2_Omogeu0iMCRQ=", - JWK{ - ID: "fake-key", - Alg: "HS256", - Secret: []byte("secret"), - }, - true, - "valid case", - }, - { - "test", - "Aymga2LNFrM-tnkr6MYLFY2Jou46h2_Omogeu0iMCRQ=", - JWK{ - ID: "different-key", - Alg: "HS256", - Secret: []byte("secret"), - }, - true, - "invalid: different key, should not match", - }, - { - "test sig and non-matching data", - "Aymga2LNFrM-tnkr6MYLFY2Jou46h2_Omogeu0iMCRQ=", - JWK{ - ID: "fake-key", - Alg: "HS256", - Secret: []byte("secret"), - }, - false, - "invalid: sig and data should not match", - }, -} - -func TestVerify(t *testing.T) { - for _, tt := range hmacTestCases { - v, err := NewVerifierHMAC(tt.jwk) - if err != nil { - t.Errorf("should construct hmac verifier. test: %s. err=%v", tt.desc, err) - } - - decSig, _ := base64.URLEncoding.DecodeString(tt.sig) - err = v.Verify(decSig, []byte(tt.data)) - if err == nil && !tt.valid { - t.Errorf("verify failure. test: %s. expected: invalid, actual: valid.", tt.desc) - } - if err != nil && tt.valid { - t.Errorf("verify failure. test: %s. expected: valid, actual: invalid. err=%v", tt.desc, err) - } - } -} - -func TestSign(t *testing.T) { - for _, tt := range hmacTestCases { - s := NewSignerHMAC("test", tt.jwk.Secret) - sig, err := s.Sign([]byte(tt.data)) - if err != nil { - t.Errorf("sign failure. test: %s. err=%v", tt.desc, err) - } - - expSig, _ := base64.URLEncoding.DecodeString(tt.sig) - if tt.valid && !bytes.Equal(sig, expSig) { - t.Errorf("sign failure. test: %s. expected: %s, actual: %s.", tt.desc, tt.sig, base64.URLEncoding.EncodeToString(sig)) - } - if !tt.valid && bytes.Equal(sig, expSig) { - t.Errorf("sign failure. test: %s. expected: invalid signature.", tt.desc) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/key_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/key/key_test.go deleted file mode 100644 index d4985151369..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/key_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package key - -import ( - "crypto/rsa" - "math/big" - "reflect" - "testing" - "time" - - "github.com/coreos/go-oidc/jose" -) - -func TestPrivateRSAKeyJWK(t *testing.T) { - n := big.NewInt(int64(17)) - if n == nil { - panic("NewInt returned nil") - } - - k := &PrivateKey{ - KeyID: "foo", - PrivateKey: &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{N: n, E: 65537}, - }, - } - - want := jose.JWK{ - ID: "foo", - Type: "RSA", - Alg: "RS256", - Use: "sig", - Modulus: n, - Exponent: 65537, - } - - got := k.JWK() - if !reflect.DeepEqual(want, got) { - t.Fatalf("JWK mismatch: want=%#v got=%#v", want, got) - } -} - -func TestPublicKeySetKey(t *testing.T) { - n := big.NewInt(int64(17)) - if n == nil { - panic("NewInt returned nil") - } - - k := jose.JWK{ - ID: "foo", - Type: "RSA", - Alg: "RS256", - Use: "sig", - Modulus: n, - Exponent: 65537, - } - now := time.Now().UTC() - ks := NewPublicKeySet([]jose.JWK{k}, now) - - want := &PublicKey{jwk: k} - got := ks.Key("foo") - if !reflect.DeepEqual(want, got) { - t.Errorf("Unexpected response from PublicKeySet.Key: want=%#v got=%#v", want, got) - } - - got = ks.Key("bar") - if got != nil { - t.Errorf("Expected nil response from PublicKeySet.Key, got %#v", got) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/manager_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/key/manager_test.go deleted file mode 100644 index f3c753e7cc0..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/manager_test.go +++ /dev/null @@ -1,225 +0,0 @@ -package key - -import ( - "crypto/rsa" - "math/big" - "reflect" - "strconv" - "testing" - "time" - - "github.com/jonboulle/clockwork" - - "github.com/coreos/go-oidc/jose" -) - -var ( - jwk1 jose.JWK - jwk2 jose.JWK - jwk3 jose.JWK -) - -func init() { - jwk1 = jose.JWK{ - ID: "1", - Type: "RSA", - Alg: "RS256", - Use: "sig", - Modulus: big.NewInt(1), - Exponent: 65537, - } - - jwk2 = jose.JWK{ - ID: "2", - Type: "RSA", - Alg: "RS256", - Use: "sig", - Modulus: big.NewInt(2), - Exponent: 65537, - } - - jwk3 = jose.JWK{ - ID: "3", - Type: "RSA", - Alg: "RS256", - Use: "sig", - Modulus: big.NewInt(3), - Exponent: 65537, - } -} - -func generatePrivateKeyStatic(t *testing.T, idAndN int) *PrivateKey { - n := big.NewInt(int64(idAndN)) - if n == nil { - t.Fatalf("Call to NewInt(%d) failed", idAndN) - } - - pk := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{N: n, E: 65537}, - } - - return &PrivateKey{ - KeyID: strconv.Itoa(idAndN), - PrivateKey: pk, - } -} - -func TestPrivateKeyManagerJWKsRotate(t *testing.T) { - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - km := NewPrivateKeyManager() - err := km.Set(&PrivateKeySet{ - keys: []*PrivateKey{k1, k2, k3}, - ActiveKeyID: k1.KeyID, - expiresAt: time.Now().Add(time.Minute), - }) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - want := []jose.JWK{jwk1, jwk2, jwk3} - got, err := km.JWKs() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if !reflect.DeepEqual(want, got) { - t.Fatalf("JWK mismatch: want=%#v got=%#v", want, got) - } -} - -func TestPrivateKeyManagerSigner(t *testing.T) { - k := generatePrivateKeyStatic(t, 13) - - km := NewPrivateKeyManager() - err := km.Set(&PrivateKeySet{ - keys: []*PrivateKey{k}, - ActiveKeyID: k.KeyID, - expiresAt: time.Now().Add(time.Minute), - }) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - signer, err := km.Signer() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - wantID := "13" - gotID := signer.ID() - if wantID != gotID { - t.Fatalf("Signer has incorrect ID: want=%s got=%s", wantID, gotID) - } -} - -func TestPrivateKeyManagerHealthyFail(t *testing.T) { - keyFixture := generatePrivateKeyStatic(t, 1) - tests := []*privateKeyManager{ - // keySet nil - &privateKeyManager{ - keySet: nil, - clock: clockwork.NewRealClock(), - }, - // zero keys - &privateKeyManager{ - keySet: &PrivateKeySet{ - keys: []*PrivateKey{}, - expiresAt: time.Now().Add(time.Minute), - }, - clock: clockwork.NewRealClock(), - }, - // key set expired - &privateKeyManager{ - keySet: &PrivateKeySet{ - keys: []*PrivateKey{keyFixture}, - expiresAt: time.Now().Add(-1 * time.Minute), - }, - clock: clockwork.NewRealClock(), - }, - } - - for i, tt := range tests { - if err := tt.Healthy(); err == nil { - t.Errorf("case %d: nil error", i) - } - } -} - -func TestPrivateKeyManagerHealthyFailsOtherMethods(t *testing.T) { - km := NewPrivateKeyManager() - if _, err := km.JWKs(); err == nil { - t.Fatalf("Expected non-nil error") - } - if _, err := km.Signer(); err == nil { - t.Fatalf("Expected non-nil error") - } -} - -func TestPrivateKeyManagerExpiresAt(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - k := generatePrivateKeyStatic(t, 17) - km := &privateKeyManager{ - clock: fc, - } - - want := fc.Now().UTC() - got := km.ExpiresAt() - if want != got { - t.Fatalf("Incorrect expiration time: want=%v got=%v", want, got) - } - - err := km.Set(&PrivateKeySet{ - keys: []*PrivateKey{k}, - ActiveKeyID: k.KeyID, - expiresAt: now.Add(2 * time.Minute), - }) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - want = fc.Now().UTC().Add(2 * time.Minute) - got = km.ExpiresAt() - if want != got { - t.Fatalf("Incorrect expiration time: want=%v got=%v", want, got) - } -} - -func TestPublicKeys(t *testing.T) { - km := NewPrivateKeyManager() - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - - tests := [][]*PrivateKey{ - []*PrivateKey{k1}, - []*PrivateKey{k1, k2}, - []*PrivateKey{k1, k2, k3}, - } - - for i, tt := range tests { - ks := &PrivateKeySet{ - keys: tt, - expiresAt: time.Now().Add(time.Hour), - } - km.Set(ks) - - jwks, err := km.JWKs() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - pks := NewPublicKeySet(jwks, time.Now().Add(time.Hour)) - want := pks.Keys() - got, err := km.PublicKeys() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - if !reflect.DeepEqual(want, got) { - t.Errorf("case %d: Invalid public keys: want=%v got=%v", i, want, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/rotate_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/key/rotate_test.go deleted file mode 100644 index 394a84f0291..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/rotate_test.go +++ /dev/null @@ -1,311 +0,0 @@ -package key - -import ( - "reflect" - "testing" - "time" - - "github.com/jonboulle/clockwork" -) - -func generatePrivateKeySerialFunc(t *testing.T) GeneratePrivateKeyFunc { - var n int - return func() (*PrivateKey, error) { - n++ - return generatePrivateKeyStatic(t, n), nil - } -} - -func TestRotate(t *testing.T) { - now := time.Now() - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - - tests := []struct { - start *PrivateKeySet - key *PrivateKey - keep int - exp time.Time - want *PrivateKeySet - }{ - // start with nil keys - { - start: nil, - key: k1, - keep: 2, - exp: now.Add(time.Second), - want: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(time.Second), - }, - }, - // start with zero keys - { - start: &PrivateKeySet{}, - key: k1, - keep: 2, - exp: now.Add(time.Second), - want: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(time.Second), - }, - }, - // add second key - { - start: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now, - }, - key: k2, - keep: 2, - exp: now.Add(time.Second), - want: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(time.Second), - }, - }, - // rotate in third key - { - start: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now, - }, - key: k3, - keep: 2, - exp: now.Add(time.Second), - want: &PrivateKeySet{ - keys: []*PrivateKey{k3, k2}, - ActiveKeyID: k3.KeyID, - expiresAt: now.Add(time.Second), - }, - }, - } - - for i, tt := range tests { - repo := NewPrivateKeySetRepo() - if tt.start != nil { - err := repo.Set(tt.start) - if err != nil { - log.Fatalf("case %d: unexpected error: %v", i, err) - } - } - - rotatePrivateKeys(repo, tt.key, tt.keep, tt.exp) - got, err := repo.Get() - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - if !reflect.DeepEqual(tt.want, got) { - t.Errorf("case %d: unexpected result: want=%#v got=%#v", i, tt.want, got) - } - } -} - -func TestPrivateKeyRotatorRun(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - k4 := generatePrivateKeyStatic(t, 4) - - kRepo := NewPrivateKeySetRepo() - krot := NewPrivateKeyRotator(kRepo, 4*time.Second) - krot.clock = fc - krot.generateKey = generatePrivateKeySerialFunc(t) - - steps := []*PrivateKeySet{ - &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(4 * time.Second), - }, - &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(6 * time.Second), - }, - &PrivateKeySet{ - keys: []*PrivateKey{k3, k2}, - ActiveKeyID: k3.KeyID, - expiresAt: now.Add(8 * time.Second), - }, - &PrivateKeySet{ - keys: []*PrivateKey{k4, k3}, - ActiveKeyID: k4.KeyID, - expiresAt: now.Add(10 * time.Second), - }, - } - - stop := krot.Run() - defer close(stop) - - for i, st := range steps { - // wait for the rotater to get sleepy - fc.BlockUntil(1) - - got, err := kRepo.Get() - if err != nil { - t.Fatalf("step %d: unexpected error: %v", i, err) - } - if !reflect.DeepEqual(st, got) { - t.Fatalf("step %d: unexpected state: want=%#v got=%#v", i, st, got) - } - fc.Advance(2 * time.Second) - } -} - -func TestPrivateKeyRotatorExpiresAt(t *testing.T) { - fc := clockwork.NewFakeClock() - krot := &PrivateKeyRotator{ - clock: fc, - ttl: time.Minute, - } - got := krot.expiresAt() - want := fc.Now().UTC().Add(time.Minute) - if !reflect.DeepEqual(want, got) { - t.Errorf("Incorrect expiration time: want=%v got=%v", want, got) - } -} - -func TestNextRotation(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - tests := []struct { - expiresAt time.Time - ttl time.Duration - numKeys int - expected time.Duration - }{ - { - // closest to prod - expiresAt: now.Add(time.Hour * 24), - ttl: time.Hour * 24, - numKeys: 2, - expected: time.Hour * 12, - }, - { - expiresAt: now.Add(time.Hour * 2), - ttl: time.Hour * 4, - numKeys: 2, - expected: 0, - }, - { - // No keys. - expiresAt: now.Add(time.Hour * 2), - ttl: time.Hour * 4, - numKeys: 0, - expected: 0, - }, - { - // Nil keyset. - expiresAt: now.Add(time.Hour * 2), - ttl: time.Hour * 4, - numKeys: -1, - expected: 0, - }, - { - // KeySet expired. - expiresAt: now.Add(time.Hour * -2), - ttl: time.Hour * 4, - numKeys: 2, - expected: 0, - }, - { - // Expiry past now + TTL - expiresAt: now.Add(time.Hour * 5), - ttl: time.Hour * 4, - numKeys: 2, - expected: 3 * time.Hour, - }, - } - - for i, tt := range tests { - kRepo := NewPrivateKeySetRepo() - krot := NewPrivateKeyRotator(kRepo, tt.ttl) - krot.clock = fc - pks := &PrivateKeySet{ - expiresAt: tt.expiresAt, - } - if tt.numKeys != -1 { - for n := 0; n < tt.numKeys; n++ { - pks.keys = append(pks.keys, generatePrivateKeyStatic(t, n)) - } - err := kRepo.Set(pks) - if err != nil { - log.Fatalf("case %d: unexpected error: %v", i, err) - } - - } - actual, err := krot.nextRotation() - if err != nil { - t.Errorf("case %d: error calling shouldRotate(): %v", i, err) - } - if actual != tt.expected { - t.Errorf("case %d: actual == %v, want %v", i, actual, tt.expected) - } - } -} - -func TestHealthy(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - tests := []struct { - expiresAt time.Time - numKeys int - expected error - }{ - { - expiresAt: now.Add(time.Hour), - numKeys: 2, - expected: nil, - }, - { - expiresAt: now.Add(time.Hour), - numKeys: -1, - expected: ErrorNoKeys, - }, - { - expiresAt: now.Add(time.Hour), - numKeys: 0, - expected: ErrorNoKeys, - }, - { - expiresAt: now.Add(-time.Hour), - numKeys: 2, - expected: ErrorPrivateKeysExpired, - }, - } - - for i, tt := range tests { - kRepo := NewPrivateKeySetRepo() - krot := NewPrivateKeyRotator(kRepo, time.Hour) - krot.clock = fc - pks := &PrivateKeySet{ - expiresAt: tt.expiresAt, - } - if tt.numKeys != -1 { - for n := 0; n < tt.numKeys; n++ { - pks.keys = append(pks.keys, generatePrivateKeyStatic(t, n)) - } - err := kRepo.Set(pks) - if err != nil { - log.Fatalf("case %d: unexpected error: %v", i, err) - } - - } - if err := krot.Healthy(); err != tt.expected { - t.Errorf("case %d: got==%q, want==%q", i, err, tt.expected) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/sync_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/key/sync_test.go deleted file mode 100644 index ec8ef7369e5..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/key/sync_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package key - -import ( - "errors" - "reflect" - "testing" - "time" - - "github.com/jonboulle/clockwork" -) - -type staticReadableKeySetRepo struct { - ks KeySet - err error -} - -func (r *staticReadableKeySetRepo) Get() (KeySet, error) { - return r.ks, r.err -} - -func TestKeySyncerSync(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - - steps := []struct { - fromKS KeySet - fromErr error - advance time.Duration - want *PrivateKeySet - }{ - // on startup, first sync should trigger within a second - { - fromKS: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(10 * time.Second), - }, - advance: time.Second, - want: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(10 * time.Second), - }, - }, - // advance halfway into TTL, triggering sync - { - fromKS: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(15 * time.Second), - }, - advance: 5 * time.Second, - want: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(15 * time.Second), - }, - }, - - // advance halfway into TTL, triggering sync that fails - { - fromErr: errors.New("fail!"), - advance: 10 * time.Second, - want: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(15 * time.Second), - }, - }, - - // sync retries quickly, and succeeds with fixed data - { - fromKS: &PrivateKeySet{ - keys: []*PrivateKey{k3, k2, k1}, - ActiveKeyID: k3.KeyID, - expiresAt: now.Add(25 * time.Second), - }, - advance: 3 * time.Second, - want: &PrivateKeySet{ - keys: []*PrivateKey{k3, k2, k1}, - ActiveKeyID: k3.KeyID, - expiresAt: now.Add(25 * time.Second), - }, - }, - } - - from := &staticReadableKeySetRepo{} - to := NewPrivateKeySetRepo() - - syncer := NewKeySetSyncer(from, to) - syncer.clock = fc - stop := syncer.Run() - defer close(stop) - - for i, st := range steps { - from.ks = st.fromKS - from.err = st.fromErr - - fc.Advance(st.advance) - fc.BlockUntil(1) - - ks, err := to.Get() - if err != nil { - t.Fatalf("step %d: unable to get keys: %v", i, err) - } - if !reflect.DeepEqual(st.want, ks) { - t.Fatalf("step %d: incorrect state: want=%#v got=%#v", i, st.want, ks) - } - } -} - -func TestSync(t *testing.T) { - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - k1 := generatePrivateKeyStatic(t, 1) - k2 := generatePrivateKeyStatic(t, 2) - k3 := generatePrivateKeyStatic(t, 3) - - tests := []struct { - keySet *PrivateKeySet - want time.Duration - }{ - { - keySet: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(time.Minute), - }, - want: time.Minute, - }, - { - keySet: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(time.Minute), - }, - want: time.Minute, - }, - { - keySet: &PrivateKeySet{ - keys: []*PrivateKey{k3, k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(time.Minute), - }, - want: time.Minute, - }, - { - keySet: &PrivateKeySet{ - keys: []*PrivateKey{k2, k1}, - ActiveKeyID: k2.KeyID, - expiresAt: now.Add(time.Hour), - }, - want: time.Hour, - }, - { - keySet: &PrivateKeySet{ - keys: []*PrivateKey{k1}, - ActiveKeyID: k1.KeyID, - expiresAt: now.Add(-time.Hour), - }, - want: 0, - }, - } - - for i, tt := range tests { - from := NewPrivateKeySetRepo() - to := NewPrivateKeySetRepo() - - err := from.Set(tt.keySet) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - exp, err := sync(from, to, fc) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - - if tt.want != exp { - t.Errorf("case %d: want=%v got=%v", i, tt.want, exp) - } - } -} - -func TestSyncFail(t *testing.T) { - tests := []error{ - nil, - errors.New("fail!"), - } - - for i, tt := range tests { - from := &staticReadableKeySetRepo{ks: nil, err: tt} - to := NewPrivateKeySetRepo() - - if _, err := sync(from, to, clockwork.NewFakeClock()); err == nil { - t.Errorf("case %d: expected non-nil error", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/error_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/error_test.go deleted file mode 100644 index 41174893b53..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/error_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package oauth2 - -import ( - "fmt" - "reflect" - "testing" -) - -func TestUnmarshalError(t *testing.T) { - tests := []struct { - b []byte - e *Error - o bool - }{ - { - b: []byte("{ \"error\": \"invalid_client\", \"state\": \"foo\" }"), - e: &Error{Type: ErrorInvalidClient, State: "foo"}, - o: true, - }, - { - b: []byte("{ \"error\": \"invalid_grant\", \"state\": \"bar\" }"), - e: &Error{Type: ErrorInvalidGrant, State: "bar"}, - o: true, - }, - { - b: []byte("{ \"error\": \"invalid_request\", \"state\": \"\" }"), - e: &Error{Type: ErrorInvalidRequest, State: ""}, - o: true, - }, - { - b: []byte("{ \"error\": \"server_error\", \"state\": \"elroy\" }"), - e: &Error{Type: ErrorServerError, State: "elroy"}, - o: true, - }, - { - b: []byte("{ \"error\": \"unsupported_grant_type\", \"state\": \"\" }"), - e: &Error{Type: ErrorUnsupportedGrantType, State: ""}, - o: true, - }, - { - b: []byte("{ \"error\": \"unsupported_response_type\", \"state\": \"\" }"), - e: &Error{Type: ErrorUnsupportedResponseType, State: ""}, - o: true, - }, - // Should fail json unmarshal - { - b: nil, - e: nil, - o: false, - }, - { - b: []byte("random string"), - e: nil, - o: false, - }, - } - - for i, tt := range tests { - err := unmarshalError(tt.b) - oerr, ok := err.(*Error) - - if ok != tt.o { - t.Errorf("%v != %v, %v", ok, tt.o, oerr) - t.Errorf("case %d: want=%+v, got=%+v", i, tt.e, oerr) - } - - if ok && !reflect.DeepEqual(tt.e, oerr) { - t.Errorf("case %d: want=%+v, got=%+v", i, tt.e, oerr) - } - - if !ok && tt.e != nil { - want := fmt.Sprintf("unrecognized error: %s", string(tt.b)) - got := tt.e.Error() - if want != got { - t.Errorf("case %d: want=%+v, got=%+v", i, want, got) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/oauth2_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/oauth2_test.go deleted file mode 100644 index 9e5fd9a3606..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oauth2/oauth2_test.go +++ /dev/null @@ -1,262 +0,0 @@ -package oauth2 - -import ( - "errors" - "net/url" - "reflect" - "strings" - "testing" - - phttp "github.com/coreos/go-oidc/http" -) - -func TestParseAuthCodeRequest(t *testing.T) { - tests := []struct { - query url.Values - wantACR AuthCodeRequest - wantErr error - }{ - // no redirect_uri - { - query: url.Values{ - "response_type": []string{"code"}, - "scope": []string{"foo bar baz"}, - "client_id": []string{"XXX"}, - "state": []string{"pants"}, - }, - wantACR: AuthCodeRequest{ - ResponseType: "code", - ClientID: "XXX", - Scope: []string{"foo", "bar", "baz"}, - State: "pants", - RedirectURL: nil, - }, - }, - - // with redirect_uri - { - query: url.Values{ - "response_type": []string{"code"}, - "redirect_uri": []string{"https://127.0.0.1:5555/callback?foo=bar"}, - "scope": []string{"foo bar baz"}, - "client_id": []string{"XXX"}, - "state": []string{"pants"}, - }, - wantACR: AuthCodeRequest{ - ResponseType: "code", - ClientID: "XXX", - Scope: []string{"foo", "bar", "baz"}, - State: "pants", - RedirectURL: &url.URL{ - Scheme: "https", - Host: "127.0.0.1:5555", - Path: "/callback", - RawQuery: "foo=bar", - }, - }, - }, - - // unsupported response_type doesn't trigger error - { - query: url.Values{ - "response_type": []string{"token"}, - "redirect_uri": []string{"https://127.0.0.1:5555/callback?foo=bar"}, - "scope": []string{"foo bar baz"}, - "client_id": []string{"XXX"}, - "state": []string{"pants"}, - }, - wantACR: AuthCodeRequest{ - ResponseType: "token", - ClientID: "XXX", - Scope: []string{"foo", "bar", "baz"}, - State: "pants", - RedirectURL: &url.URL{ - Scheme: "https", - Host: "127.0.0.1:5555", - Path: "/callback", - RawQuery: "foo=bar", - }, - }, - }, - - // unparseable redirect_uri - { - query: url.Values{ - "response_type": []string{"code"}, - "redirect_uri": []string{":"}, - "scope": []string{"foo bar baz"}, - "client_id": []string{"XXX"}, - "state": []string{"pants"}, - }, - wantACR: AuthCodeRequest{ - ResponseType: "code", - ClientID: "XXX", - Scope: []string{"foo", "bar", "baz"}, - State: "pants", - }, - wantErr: NewError(ErrorInvalidRequest), - }, - - // no client_id, redirect_uri not parsed - { - query: url.Values{ - "response_type": []string{"code"}, - "redirect_uri": []string{"https://127.0.0.1:5555/callback?foo=bar"}, - "scope": []string{"foo bar baz"}, - "client_id": []string{}, - "state": []string{"pants"}, - }, - wantACR: AuthCodeRequest{ - ResponseType: "code", - ClientID: "", - Scope: []string{"foo", "bar", "baz"}, - State: "pants", - RedirectURL: nil, - }, - wantErr: NewError(ErrorInvalidRequest), - }, - } - - for i, tt := range tests { - got, err := ParseAuthCodeRequest(tt.query) - if !reflect.DeepEqual(tt.wantErr, err) { - t.Errorf("case %d: incorrect error value: want=%q got=%q", i, tt.wantErr, err) - } - - if !reflect.DeepEqual(tt.wantACR, got) { - t.Errorf("case %d: incorrect AuthCodeRequest value: want=%#v got=%#v", i, tt.wantACR, got) - } - } -} - -func TestClientCredsToken(t *testing.T) { - hc := &phttp.RequestRecorder{Error: errors.New("error")} - cfg := Config{ - Credentials: ClientCredentials{ID: "cid", Secret: "csecret"}, - Scope: []string{"foo-scope", "bar-scope"}, - TokenURL: "http://example.com/token", - AuthMethod: AuthMethodClientSecretBasic, - RedirectURL: "http://example.com/redirect", - AuthURL: "http://example.com/auth", - } - - c, err := NewClient(hc, cfg) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - scope := []string{"openid"} - c.ClientCredsToken(scope) - if hc.Request == nil { - t.Error("request is empty") - } - - tu := hc.Request.URL.String() - if cfg.TokenURL != tu { - t.Errorf("wrong token url, want=%v, got=%v", cfg.TokenURL, tu) - } - - ct := hc.Request.Header.Get("Content-Type") - if ct != "application/x-www-form-urlencoded" { - t.Errorf("wrong content-type, want=application/x-www-form-urlencoded, got=%v", ct) - } - - cid, secret, ok := phttp.BasicAuth(hc.Request) - if !ok { - t.Error("unexpected error parsing basic auth") - } - - if cfg.Credentials.ID != cid { - t.Errorf("wrong client ID, want=%v, got=%v", cfg.Credentials.ID, cid) - } - - if cfg.Credentials.Secret != secret { - t.Errorf("wrong client secret, want=%v, got=%v", cfg.Credentials.Secret, secret) - } - - err = hc.Request.ParseForm() - if err != nil { - t.Error("unexpected error parsing form") - } - - gt := hc.Request.PostForm.Get("grant_type") - if gt != GrantTypeClientCreds { - t.Errorf("wrong grant_type, want=client_credentials, got=%v", gt) - } - - sc := strings.Split(hc.Request.PostForm.Get("scope"), " ") - if !reflect.DeepEqual(scope, sc) { - t.Errorf("wrong scope, want=%v, got=%v", scope, sc) - } -} - -func TestNewAuthenticatedRequest(t *testing.T) { - tests := []struct { - authMethod string - url string - values url.Values - }{ - { - authMethod: AuthMethodClientSecretBasic, - url: "http://example.com/token", - values: url.Values{}, - }, - { - authMethod: AuthMethodClientSecretPost, - url: "http://example.com/token", - values: url.Values{}, - }, - } - - for i, tt := range tests { - hc := &phttp.HandlerClient{} - cfg := Config{ - Credentials: ClientCredentials{ID: "cid", Secret: "csecret"}, - Scope: []string{"foo-scope", "bar-scope"}, - TokenURL: "http://example.com/token", - AuthURL: "http://example.com/auth", - RedirectURL: "http://example.com/redirect", - AuthMethod: tt.authMethod, - } - c, err := NewClient(hc, cfg) - req, err := c.newAuthenticatedRequest(tt.url, tt.values) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - err = req.ParseForm() - if err != nil { - t.Errorf("case %d: want nil err, got %v", i, err) - } - - if tt.authMethod == AuthMethodClientSecretBasic { - cid, secret, ok := phttp.BasicAuth(req) - if !ok { - t.Errorf("case %d: !ok parsing Basic Auth headers", i) - continue - } - if cid != cfg.Credentials.ID { - t.Errorf("case %d: want CID == %q, got CID == %q", i, cfg.Credentials.ID, cid) - } - if secret != cfg.Credentials.Secret { - t.Errorf("case %d: want secret == %q, got secret == %q", i, cfg.Credentials.Secret, secret) - } - } else if tt.authMethod == AuthMethodClientSecretPost { - if req.PostFormValue("client_secret") != cfg.Credentials.Secret { - t.Errorf("case %d: want client_secret == %q, got client_secret == %q", - i, cfg.Credentials.Secret, req.PostFormValue("client_secret")) - } - } - - for k, v := range tt.values { - if !reflect.DeepEqual(v, req.PostForm[k]) { - t.Errorf("case %d: key:%q want==%q, got==%q", i, k, v, req.PostForm[k]) - } - } - - if req.URL.String() != tt.url { - t.Errorf("case %d: want URL==%q, got URL==%q", i, tt.url, req.URL.String()) - } - - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/client_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/client_test.go deleted file mode 100644 index e66688fc2d8..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/client_test.go +++ /dev/null @@ -1,367 +0,0 @@ -package oidc - -import ( - "net/url" - "reflect" - "testing" - "time" - - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/key" - "github.com/coreos/go-oidc/oauth2" -) - -func TestNewClientScopeDefault(t *testing.T) { - tests := []struct { - c ClientConfig - e []string - }{ - { - // No scope - c: ClientConfig{RedirectURL: "http://example.com/redirect"}, - e: DefaultScope, - }, - { - // Nil scope - c: ClientConfig{RedirectURL: "http://example.com/redirect", Scope: nil}, - e: DefaultScope, - }, - { - // Empty scope - c: ClientConfig{RedirectURL: "http://example.com/redirect", Scope: []string{}}, - e: []string{}, - }, - { - // Custom scope equal to default - c: ClientConfig{RedirectURL: "http://example.com/redirect", Scope: []string{"openid", "email", "profile"}}, - e: DefaultScope, - }, - { - // Custom scope not including defaults - c: ClientConfig{RedirectURL: "http://example.com/redirect", Scope: []string{"foo", "bar"}}, - e: []string{"foo", "bar"}, - }, - { - // Custom scopes overlapping with defaults - c: ClientConfig{RedirectURL: "http://example.com/redirect", Scope: []string{"openid", "foo"}}, - e: []string{"openid", "foo"}, - }, - } - - for i, tt := range tests { - c, err := NewClient(tt.c) - if err != nil { - t.Errorf("case %d: unexpected error from NewClient: %v", i, err) - continue - } - if !reflect.DeepEqual(tt.e, c.scope) { - t.Errorf("case %d: want: %v, got: %v", i, tt.e, c.scope) - } - } -} - -func TestHealthy(t *testing.T) { - now := time.Now().UTC() - - tests := []struct { - c *Client - h bool - }{ - // all ok - { - c: &Client{ - providerConfig: ProviderConfig{ - Issuer: "http://example.com", - ExpiresAt: now.Add(time.Hour), - }, - }, - h: true, - }, - // zero-value ProviderConfig.ExpiresAt - { - c: &Client{ - providerConfig: ProviderConfig{ - Issuer: "http://example.com", - }, - }, - h: true, - }, - // expired ProviderConfig - { - c: &Client{ - providerConfig: ProviderConfig{ - Issuer: "http://example.com", - ExpiresAt: now.Add(time.Hour * -1), - }, - }, - h: false, - }, - // empty ProviderConfig - { - c: &Client{}, - h: false, - }, - } - - for i, tt := range tests { - err := tt.c.Healthy() - want := tt.h - got := (err == nil) - - if want != got { - t.Errorf("case %d: want: healthy=%v, got: healhty=%v, err: %v", i, want, got, err) - } - } -} - -func TestClientKeysFuncAll(t *testing.T) { - priv1, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - - priv2, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - - now := time.Now() - future := now.Add(time.Hour) - past := now.Add(-1 * time.Hour) - - tests := []struct { - keySet *key.PublicKeySet - want []key.PublicKey - }{ - // two keys, non-expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{priv2.JWK(), priv1.JWK()}, future), - want: []key.PublicKey{*key.NewPublicKey(priv2.JWK()), *key.NewPublicKey(priv1.JWK())}, - }, - - // no keys, non-expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{}, future), - want: []key.PublicKey{}, - }, - - // two keys, expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{priv2.JWK(), priv1.JWK()}, past), - want: []key.PublicKey{}, - }, - - // no keys, expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{}, past), - want: []key.PublicKey{}, - }, - } - - for i, tt := range tests { - var c Client - c.keySet = *tt.keySet - keysFunc := c.keysFuncAll() - got := keysFunc() - if !reflect.DeepEqual(tt.want, got) { - t.Errorf("case %d: want=%#v got=%#v", i, tt.want, got) - } - } -} - -func TestClientKeysFuncWithID(t *testing.T) { - priv1, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - - priv2, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - - now := time.Now() - future := now.Add(time.Hour) - past := now.Add(-1 * time.Hour) - - tests := []struct { - keySet *key.PublicKeySet - argID string - want []key.PublicKey - }{ - // two keys, match, non-expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{priv2.JWK(), priv1.JWK()}, future), - argID: priv2.ID(), - want: []key.PublicKey{*key.NewPublicKey(priv2.JWK())}, - }, - - // two keys, no match, non-expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{priv2.JWK(), priv1.JWK()}, future), - argID: "XXX", - want: []key.PublicKey{}, - }, - - // no keys, no match, non-expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{}, future), - argID: priv2.ID(), - want: []key.PublicKey{}, - }, - - // two keys, match, expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{priv2.JWK(), priv1.JWK()}, past), - argID: priv2.ID(), - want: []key.PublicKey{}, - }, - - // no keys, no match, expired set - { - keySet: key.NewPublicKeySet([]jose.JWK{}, past), - argID: priv2.ID(), - want: []key.PublicKey{}, - }, - } - - for i, tt := range tests { - var c Client - c.keySet = *tt.keySet - keysFunc := c.keysFuncWithID(tt.argID) - got := keysFunc() - if !reflect.DeepEqual(tt.want, got) { - t.Errorf("case %d: want=%#v got=%#v", i, tt.want, got) - } - } -} - -func TestClientMetadataValid(t *testing.T) { - tests := []ClientMetadata{ - // one RedirectURL - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "http", Host: "example.com"}}, - }, - - // one RedirectURL w/ nonempty path - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "http", Host: "example.com", Path: "/foo"}}, - }, - - // two RedirectURLs - ClientMetadata{ - RedirectURLs: []url.URL{ - url.URL{Scheme: "http", Host: "foo.example.com"}, - url.URL{Scheme: "http", Host: "bar.example.com"}, - }, - }, - } - - for i, tt := range tests { - if err := tt.Valid(); err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - } - } -} - -func TestClientMetadataInvalid(t *testing.T) { - tests := []ClientMetadata{ - // nil RedirectURls slice - ClientMetadata{ - RedirectURLs: nil, - }, - - // empty RedirectURLs slice - ClientMetadata{ - RedirectURLs: []url.URL{}, - }, - - // empty url.URL - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{}}, - }, - - // empty url.URL following OK item - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "http", Host: "example.com"}, url.URL{}}, - }, - - // url.URL with empty Host - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "http", Host: ""}}, - }, - - // url.URL with empty Scheme - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "", Host: "example.com"}}, - }, - - // url.URL with non-HTTP(S) Scheme - ClientMetadata{ - RedirectURLs: []url.URL{url.URL{Scheme: "tcp", Host: "127.0.0.1"}}, - }, - } - - for i, tt := range tests { - if err := tt.Valid(); err == nil { - t.Errorf("case %d: expected non-nil error", i) - } - } -} - -func TestChooseAuthMethod(t *testing.T) { - tests := []struct { - supported []string - chosen string - err bool - }{ - { - supported: []string{}, - chosen: oauth2.AuthMethodClientSecretBasic, - }, - { - supported: []string{oauth2.AuthMethodClientSecretBasic}, - chosen: oauth2.AuthMethodClientSecretBasic, - }, - { - supported: []string{oauth2.AuthMethodClientSecretPost}, - chosen: oauth2.AuthMethodClientSecretPost, - }, - { - supported: []string{oauth2.AuthMethodClientSecretPost, oauth2.AuthMethodClientSecretBasic}, - chosen: oauth2.AuthMethodClientSecretPost, - }, - { - supported: []string{oauth2.AuthMethodClientSecretBasic, oauth2.AuthMethodClientSecretPost}, - chosen: oauth2.AuthMethodClientSecretBasic, - }, - { - supported: []string{oauth2.AuthMethodClientSecretJWT, oauth2.AuthMethodClientSecretPost}, - chosen: oauth2.AuthMethodClientSecretPost, - }, - { - supported: []string{oauth2.AuthMethodClientSecretJWT}, - chosen: "", - err: true, - }, - } - - for i, tt := range tests { - client := Client{ - providerConfig: ProviderConfig{ - TokenEndpointAuthMethodsSupported: tt.supported, - }, - } - got, err := client.chooseAuthMethod() - if tt.err { - if err == nil { - t.Errorf("case %d: expected non-nil err", i) - } - continue - } - - if got != tt.chosen { - t.Errorf("case %d: want=%q, got=%q", i, tt.chosen, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/identity_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/identity_test.go deleted file mode 100644 index d286c669393..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/identity_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package oidc - -import ( - "reflect" - "testing" - "time" - - "github.com/coreos/go-oidc/jose" -) - -func TestIdentityFromClaims(t *testing.T) { - tests := []struct { - claims jose.Claims - want Identity - }{ - { - claims: jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "email": "elroy@example.com", - "exp": float64(1.416935146e+09), - }, - want: Identity{ - ID: "123850281", - Name: "", - Email: "elroy@example.com", - ExpiresAt: time.Date(2014, time.November, 25, 17, 05, 46, 0, time.UTC), - }, - }, - { - claims: jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "exp": float64(1.416935146e+09), - }, - want: Identity{ - ID: "123850281", - Name: "", - Email: "", - ExpiresAt: time.Date(2014, time.November, 25, 17, 05, 46, 0, time.UTC), - }, - }, - { - claims: jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "email": "elroy@example.com", - "exp": int64(1416935146), - }, - want: Identity{ - ID: "123850281", - Name: "", - Email: "elroy@example.com", - ExpiresAt: time.Date(2014, time.November, 25, 17, 05, 46, 0, time.UTC), - }, - }, - { - claims: jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "email": "elroy@example.com", - }, - want: Identity{ - ID: "123850281", - Name: "", - Email: "elroy@example.com", - ExpiresAt: time.Time{}, - }, - }, - } - - for i, tt := range tests { - got, err := IdentityFromClaims(tt.claims) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - continue - } - if !reflect.DeepEqual(tt.want, *got) { - t.Errorf("case %d: want=%#v got=%#v", i, tt.want, *got) - } - } -} - -func TestIdentityFromClaimsFail(t *testing.T) { - tests := []jose.Claims{ - // sub incorrect type - jose.Claims{ - "sub": 123, - "name": "foo", - "email": "elroy@example.com", - }, - // email incorrect type - jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "email": false, - }, - // exp incorrect type - jose.Claims{ - "sub": "123850281", - "name": "Elroy", - "email": "elroy@example.com", - "exp": "2014-11-25 18:05:46 +0000 UTC", - }, - } - - for i, tt := range tests { - _, err := IdentityFromClaims(tt) - if err == nil { - t.Errorf("case %d: expected non-nil error", i) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/provider_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/provider_test.go deleted file mode 100644 index 83f139ef0c9..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/provider_test.go +++ /dev/null @@ -1,466 +0,0 @@ -package oidc - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "testing" - "time" - - "github.com/jonboulle/clockwork" - - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/oauth2" -) - -type fakeProviderConfigGetterSetter struct { - cfg *ProviderConfig - getCount int - setCount int -} - -func (g *fakeProviderConfigGetterSetter) Get() (ProviderConfig, error) { - g.getCount++ - return *g.cfg, nil -} - -func (g *fakeProviderConfigGetterSetter) Set(cfg ProviderConfig) error { - g.cfg = &cfg - g.setCount++ - return nil -} - -type fakeProviderConfigHandler struct { - cfg ProviderConfig - maxAge time.Duration -} - -func (s *fakeProviderConfigHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - b, _ := json.Marshal(s.cfg) - if s.maxAge.Seconds() >= 0 { - w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(s.maxAge.Seconds()))) - } - w.Header().Set("Content-Type", "application/json") - w.Write(b) -} - -func TestHTTPProviderConfigGetter(t *testing.T) { - svr := &fakeProviderConfigHandler{} - hc := &phttp.HandlerClient{Handler: svr} - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - - tests := []struct { - dsc string - age time.Duration - cfg ProviderConfig - ok bool - }{ - // everything is good - { - dsc: "https://example.com", - age: time.Minute, - cfg: ProviderConfig{ - Issuer: "https://example.com", - ExpiresAt: now.Add(time.Minute), - }, - ok: true, - }, - // iss and disco url differ by scheme only (how google works) - { - dsc: "https://example.com", - age: time.Minute, - cfg: ProviderConfig{ - Issuer: "example.com", - ExpiresAt: now.Add(time.Minute), - }, - ok: true, - }, - // issuer and discovery URL mismatch - { - dsc: "https://foo.com", - age: time.Minute, - cfg: ProviderConfig{ - Issuer: "https://example.com", - ExpiresAt: now.Add(time.Minute), - }, - ok: false, - }, - // missing cache header results in zero ExpiresAt - { - dsc: "https://example.com", - age: -1, - cfg: ProviderConfig{ - Issuer: "https://example.com", - }, - ok: true, - }, - } - - for i, tt := range tests { - svr.cfg = tt.cfg - svr.maxAge = tt.age - getter := NewHTTPProviderConfigGetter(hc, tt.dsc) - getter.clock = fc - - got, err := getter.Get() - if err != nil { - if tt.ok { - t.Fatalf("test %d: unexpected error: %v", i, err) - } - continue - } - - if !tt.ok { - t.Fatalf("test %d: expected error", i) - continue - } - - if !reflect.DeepEqual(tt.cfg, got) { - t.Fatalf("test %d: want: %#v, got: %#v", i, tt.cfg, got) - } - } -} - -func TestProviderConfigSyncerRun(t *testing.T) { - c1 := &ProviderConfig{ - Issuer: "http://first.example.com", - } - c2 := &ProviderConfig{ - Issuer: "http://second.example.com", - } - - tests := []struct { - first *ProviderConfig - advance time.Duration - second *ProviderConfig - firstExp time.Duration - secondExp time.Duration - count int - }{ - // exp is 10m, should have same config after 1s - { - first: c1, - firstExp: time.Duration(10 * time.Minute), - advance: time.Minute, - second: c1, - secondExp: time.Duration(10 * time.Minute), - count: 1, - }, - // exp is 10m, should have new config after 10/2 = 5m - { - first: c1, - firstExp: time.Duration(10 * time.Minute), - advance: time.Duration(5 * time.Minute), - second: c2, - secondExp: time.Duration(10 * time.Minute), - count: 2, - }, - // exp is 20m, should have new config after 20/2 = 10m - { - first: c1, - firstExp: time.Duration(20 * time.Minute), - advance: time.Duration(10 * time.Minute), - second: c2, - secondExp: time.Duration(30 * time.Minute), - count: 2, - }, - } - - assertCfg := func(i int, to *fakeProviderConfigGetterSetter, want ProviderConfig) { - got, err := to.Get() - if err != nil { - t.Fatalf("test %d: unable to get config: %v", i, err) - } - if !reflect.DeepEqual(want, got) { - t.Fatalf("test %d: incorrect state:\nwant=%#v\ngot=%#v", i, want, got) - } - } - - for i, tt := range tests { - from := &fakeProviderConfigGetterSetter{} - to := &fakeProviderConfigGetterSetter{} - - fc := clockwork.NewFakeClock() - now := fc.Now().UTC() - syncer := NewProviderConfigSyncer(from, to) - syncer.clock = fc - - tt.first.ExpiresAt = now.Add(tt.firstExp) - tt.second.ExpiresAt = now.Add(tt.secondExp) - if err := from.Set(*tt.first); err != nil { - t.Fatalf("test %d: unexpected error: %v", i, err) - } - - stop := syncer.Run() - defer close(stop) - fc.BlockUntil(1) - - // first sync - assertCfg(i, to, *tt.first) - - if err := from.Set(*tt.second); err != nil { - t.Fatalf("test %d: unexpected error: %v", i, err) - } - - fc.Advance(tt.advance) - fc.BlockUntil(1) - - // second sync - assertCfg(i, to, *tt.second) - - if tt.count != from.getCount { - t.Fatalf("test %d: want: %v, got: %v", i, tt.count, from.getCount) - } - } -} - -type staticProviderConfigGetter struct { - cfg ProviderConfig - err error -} - -func (g *staticProviderConfigGetter) Get() (ProviderConfig, error) { - return g.cfg, g.err -} - -type staticProviderConfigSetter struct { - cfg *ProviderConfig - err error -} - -func (s *staticProviderConfigSetter) Set(cfg ProviderConfig) error { - s.cfg = &cfg - return s.err -} - -func TestProviderConfigSyncerSyncFailure(t *testing.T) { - fc := clockwork.NewFakeClock() - - tests := []struct { - from *staticProviderConfigGetter - to *staticProviderConfigSetter - - // want indicates what ProviderConfig should be passed to Set. - // If nil, the Set should not be called. - want *ProviderConfig - }{ - // generic Get failure - { - from: &staticProviderConfigGetter{err: errors.New("fail")}, - to: &staticProviderConfigSetter{}, - want: nil, - }, - // generic Set failure - { - from: &staticProviderConfigGetter{cfg: ProviderConfig{ExpiresAt: fc.Now().Add(time.Minute)}}, - to: &staticProviderConfigSetter{err: errors.New("fail")}, - want: &ProviderConfig{ExpiresAt: fc.Now().Add(time.Minute)}, - }, - } - - for i, tt := range tests { - pcs := &ProviderConfigSyncer{ - from: tt.from, - to: tt.to, - clock: fc, - } - _, err := pcs.sync() - if err == nil { - t.Errorf("case %d: expected non-nil error", i) - } - if !reflect.DeepEqual(tt.want, tt.to.cfg) { - t.Errorf("case %d: Set mismatch: want=%#v got=%#v", i, tt.want, tt.to.cfg) - } - } -} - -func TestNextSyncAfter(t *testing.T) { - fc := clockwork.NewFakeClock() - - tests := []struct { - exp time.Time - want time.Duration - }{ - { - exp: fc.Now().Add(time.Hour), - want: 30 * time.Minute, - }, - // override large values with the maximum - { - exp: fc.Now().Add(168 * time.Hour), // one week - want: 24 * time.Hour, - }, - // override "now" values with the minimum - { - exp: fc.Now(), - want: time.Minute, - }, - // override negative values with the minimum - { - exp: fc.Now().Add(-1 * time.Minute), - want: time.Minute, - }, - // zero-value Time results in maximum sync interval - { - exp: time.Time{}, - want: 24 * time.Hour, - }, - } - - for i, tt := range tests { - got := nextSyncAfter(tt.exp, fc) - if tt.want != got { - t.Errorf("case %d: want=%v got=%v", i, tt.want, got) - } - } -} - -func TestProviderConfigEmpty(t *testing.T) { - cfg := ProviderConfig{} - if !cfg.Empty() { - t.Fatalf("Empty provider config reports non-empty") - } - cfg = ProviderConfig{Issuer: "http://example.com"} - if cfg.Empty() { - t.Fatalf("Non-empty provider config reports empty") - } -} - -func TestPCSStepAfter(t *testing.T) { - pass := func() (time.Duration, error) { return 7 * time.Second, nil } - fail := func() (time.Duration, error) { return 0, errors.New("fail") } - - tests := []struct { - stepper pcsStepper - stepFunc pcsStepFunc - want pcsStepper - }{ - // good step results in retry at TTL - { - stepper: &pcsStepNext{}, - stepFunc: pass, - want: &pcsStepNext{aft: 7 * time.Second}, - }, - - // good step after failed step results results in retry at TTL - { - stepper: &pcsStepRetry{aft: 2 * time.Second}, - stepFunc: pass, - want: &pcsStepNext{aft: 7 * time.Second}, - }, - - // failed step results in a retry in 1s - { - stepper: &pcsStepNext{}, - stepFunc: fail, - want: &pcsStepRetry{aft: time.Second}, - }, - - // failed retry backs off by a factor of 2 - { - stepper: &pcsStepRetry{aft: time.Second}, - stepFunc: fail, - want: &pcsStepRetry{aft: 2 * time.Second}, - }, - - // failed retry backs off by a factor of 2, up to 1m - { - stepper: &pcsStepRetry{aft: 32 * time.Second}, - stepFunc: fail, - want: &pcsStepRetry{aft: 60 * time.Second}, - }, - } - - for i, tt := range tests { - got := tt.stepper.step(tt.stepFunc) - if !reflect.DeepEqual(tt.want, got) { - t.Errorf("case %d: want=%#v got=%#v", i, tt.want, got) - } - } -} - -func TestProviderConfigSupportsGrantType(t *testing.T) { - tests := []struct { - types []string - typ string - want bool - }{ - // explicitly supported - { - types: []string{"foo_type"}, - typ: "foo_type", - want: true, - }, - - // explicitly unsupported - { - types: []string{"bar_type"}, - typ: "foo_type", - want: false, - }, - - // default type explicitly unsupported - { - types: []string{oauth2.GrantTypeImplicit}, - typ: oauth2.GrantTypeAuthCode, - want: false, - }, - - // type not found in default set - { - types: []string{}, - typ: "foo_type", - want: false, - }, - - // type found in default set - { - types: []string{}, - typ: oauth2.GrantTypeAuthCode, - want: true, - }, - } - - for i, tt := range tests { - cfg := ProviderConfig{ - GrantTypesSupported: tt.types, - } - got := cfg.SupportsGrantType(tt.typ) - if tt.want != got { - t.Errorf("case %d: assert %v supports %v: want=%t got=%t", i, tt.types, tt.typ, tt.want, got) - } - } -} - -func TestWaitForProviderConfigImmediateSuccess(t *testing.T) { - cfg := ProviderConfig{Issuer: "http://example.com"} - b, err := json.Marshal(cfg) - if err != nil { - t.Fatalf("Failed marshaling provider config") - } - - resp := http.Response{Body: ioutil.NopCloser(bytes.NewBuffer(b))} - hc := &phttp.RequestRecorder{Response: &resp} - fc := clockwork.NewFakeClock() - - reschan := make(chan ProviderConfig) - go func() { - reschan <- waitForProviderConfig(hc, cfg.Issuer, fc) - }() - - var got ProviderConfig - select { - case got = <-reschan: - case <-time.After(time.Second): - t.Fatalf("Did not receive result within 1s") - } - - if !reflect.DeepEqual(cfg, got) { - t.Fatalf("Received incorrect provider config: want=%#v got=%#v", cfg, got) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/transport_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/transport_test.go deleted file mode 100644 index 9d5c7eeee10..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/transport_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package oidc - -import ( - "errors" - "net/http" - "reflect" - "testing" - - phttp "github.com/coreos/go-oidc/http" - "github.com/coreos/go-oidc/jose" -) - -type staticTokenRefresher struct { - verify func(jose.JWT) error - refresh func() (jose.JWT, error) -} - -func (s *staticTokenRefresher) Verify(jwt jose.JWT) error { - return s.verify(jwt) -} - -func (s *staticTokenRefresher) Refresh() (jose.JWT, error) { - return s.refresh() -} - -func TestAuthenticatedTransportVerifiedJWT(t *testing.T) { - tests := []struct { - refresher TokenRefresher - startJWT jose.JWT - wantJWT jose.JWT - wantError error - }{ - // verification succeeds, so refresh is not called - { - refresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return nil }, - refresh: func() (jose.JWT, error) { return jose.JWT{RawPayload: "2"}, nil }, - }, - startJWT: jose.JWT{RawPayload: "1"}, - wantJWT: jose.JWT{RawPayload: "1"}, - }, - - // verification fails, refresh succeeds so cached JWT changes - { - refresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return errors.New("fail!") }, - refresh: func() (jose.JWT, error) { return jose.JWT{RawPayload: "2"}, nil }, - }, - startJWT: jose.JWT{RawPayload: "1"}, - wantJWT: jose.JWT{RawPayload: "2"}, - }, - - // verification succeeds, so failing refresh isn't attempted - { - refresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return nil }, - refresh: func() (jose.JWT, error) { return jose.JWT{}, errors.New("fail!") }, - }, - startJWT: jose.JWT{RawPayload: "1"}, - wantJWT: jose.JWT{RawPayload: "1"}, - }, - - // verification fails, but refresh fails, too - { - refresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return errors.New("fail!") }, - refresh: func() (jose.JWT, error) { return jose.JWT{}, errors.New("fail!") }, - }, - startJWT: jose.JWT{RawPayload: "1"}, - wantJWT: jose.JWT{}, - wantError: errors.New("unable to acquire valid JWT: fail!"), - }, - } - - for i, tt := range tests { - at := &AuthenticatedTransport{ - TokenRefresher: tt.refresher, - jwt: tt.startJWT, - } - - gotJWT, err := at.verifiedJWT() - if !reflect.DeepEqual(tt.wantError, err) { - t.Errorf("#%d: unexpected error: want=%#v got=%#v", i, tt.wantError, err) - } - if !reflect.DeepEqual(tt.wantJWT, gotJWT) { - t.Errorf("#%d: incorrect JWT returned from verifiedJWT: want=%#v got=%#v", i, tt.wantJWT, gotJWT) - } - } -} - -func TestAuthenticatedTransportJWTCaching(t *testing.T) { - at := &AuthenticatedTransport{ - TokenRefresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return errors.New("fail!") }, - refresh: func() (jose.JWT, error) { return jose.JWT{RawPayload: "2"}, nil }, - }, - jwt: jose.JWT{RawPayload: "1"}, - } - - wantJWT := jose.JWT{RawPayload: "2"} - gotJWT, err := at.verifiedJWT() - if err != nil { - t.Fatalf("got non-nil error: %#v", err) - } - if !reflect.DeepEqual(wantJWT, gotJWT) { - t.Fatalf("incorrect JWT returned from verifiedJWT: want=%#v got=%#v", wantJWT, gotJWT) - } - - at.TokenRefresher = &staticTokenRefresher{ - verify: func(jose.JWT) error { return nil }, - refresh: func() (jose.JWT, error) { return jose.JWT{RawPayload: "3"}, nil }, - } - - // the previous JWT should still be cached on the AuthenticatedTransport since - // it is still valid, even though there's a new token ready to refresh - gotJWT, err = at.verifiedJWT() - if err != nil { - t.Fatalf("got non-nil error: %#v", err) - } - if !reflect.DeepEqual(wantJWT, gotJWT) { - t.Fatalf("incorrect JWT returned from verifiedJWT: want=%#v got=%#v", wantJWT, gotJWT) - } -} - -func TestAuthenticatedTransportRoundTrip(t *testing.T) { - rr := &phttp.RequestRecorder{Response: &http.Response{StatusCode: http.StatusOK}} - at := &AuthenticatedTransport{ - TokenRefresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return nil }, - }, - RoundTripper: rr, - jwt: jose.JWT{RawPayload: "1"}, - } - - req := http.Request{} - _, err := at.RoundTrip(&req) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if !reflect.DeepEqual(req, http.Request{}) { - t.Errorf("http.Request object was modified") - } - - want := []string{"Bearer .1."} - got := rr.Request.Header["Authorization"] - if !reflect.DeepEqual(want, got) { - t.Errorf("incorrect Authorization header: want=%#v got=%#v", want, got) - } -} - -func TestAuthenticatedTransportRoundTripRefreshFail(t *testing.T) { - rr := &phttp.RequestRecorder{Response: &http.Response{StatusCode: http.StatusOK}} - at := &AuthenticatedTransport{ - TokenRefresher: &staticTokenRefresher{ - verify: func(jose.JWT) error { return errors.New("fail!") }, - refresh: func() (jose.JWT, error) { return jose.JWT{}, errors.New("fail!") }, - }, - RoundTripper: rr, - jwt: jose.JWT{RawPayload: "1"}, - } - - _, err := at.RoundTrip(&http.Request{}) - if err == nil { - t.Errorf("expected non-nil error") - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/util_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/util_test.go deleted file mode 100644 index b7e0af767d0..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/util_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package oidc - -import ( - "fmt" - "net/http" - "reflect" - "testing" - "time" - - "github.com/coreos/go-oidc/jose" -) - -func TestCookieTokenExtractorInvalid(t *testing.T) { - ckName := "tokenCookie" - tests := []*http.Cookie{ - &http.Cookie{}, - &http.Cookie{Name: ckName}, - &http.Cookie{Name: ckName, Value: ""}, - } - - for i, tt := range tests { - r, _ := http.NewRequest("", "", nil) - r.AddCookie(tt) - _, err := CookieTokenExtractor(ckName)(r) - if err == nil { - t.Errorf("case %d: want: error for invalid cookie token, got: no error.", i) - } - } -} - -func TestCookieTokenExtractorValid(t *testing.T) { - validToken := "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" - ckName := "tokenCookie" - tests := []*http.Cookie{ - &http.Cookie{Name: ckName, Value: "some non-empty value"}, - &http.Cookie{Name: ckName, Value: validToken}, - } - - for i, tt := range tests { - r, _ := http.NewRequest("", "", nil) - r.AddCookie(tt) - _, err := CookieTokenExtractor(ckName)(r) - if err != nil { - t.Errorf("case %d: want: valid cookie with no error, got: %v", i, err) - } - } -} - -func TestExtractBearerTokenInvalid(t *testing.T) { - tests := []string{"", "x", "Bearer", "xxxxxxx", "Bearer "} - - for i, tt := range tests { - r, _ := http.NewRequest("", "", nil) - r.Header.Add("Authorization", tt) - _, err := ExtractBearerToken(r) - if err == nil { - t.Errorf("case %d: want: invalid Authorization header, got: valid Authorization header.", i) - } - } -} - -func TestExtractBearerTokenValid(t *testing.T) { - validToken := "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" - tests := []string{ - fmt.Sprintf("Bearer %s", validToken), - } - - for i, tt := range tests { - r, _ := http.NewRequest("", "", nil) - r.Header.Add("Authorization", tt) - _, err := ExtractBearerToken(r) - if err != nil { - t.Errorf("case %d: want: valid Authorization header, got: invalid Authorization header: %v.", i, err) - } - } -} - -func TestNewClaims(t *testing.T) { - issAt := time.Date(2, time.January, 1, 0, 0, 0, 0, time.UTC) - expAt := time.Date(2, time.January, 1, 1, 0, 0, 0, time.UTC) - - want := jose.Claims{ - "iss": "https://example.com", - "sub": "user-123", - "aud": "client-abc", - "iat": float64(issAt.Unix()), - "exp": float64(expAt.Unix()), - } - - got := NewClaims("https://example.com", "user-123", "client-abc", issAt, expAt) - - if !reflect.DeepEqual(want, got) { - t.Fatalf("want=%#v got=%#v", want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/verification_test.go b/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/verification_test.go deleted file mode 100644 index 5fa694791f1..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-oidc/oidc/verification_test.go +++ /dev/null @@ -1,297 +0,0 @@ -package oidc - -import ( - "testing" - "time" - - "github.com/coreos/go-oidc/jose" - "github.com/coreos/go-oidc/key" -) - -func TestVerifyClientClaims(t *testing.T) { - validIss := "https://example.com" - validClientID := "valid-client" - now := time.Now() - tomorrow := now.Add(24 * time.Hour) - header := jose.JOSEHeader{ - jose.HeaderKeyAlgorithm: "test-alg", - jose.HeaderKeyID: "1", - } - - tests := []struct { - claims jose.Claims - ok bool - }{ - // valid token - { - claims: jose.Claims{ - "iss": validIss, - "sub": validClientID, - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: true, - }, - // missing 'iss' claim - { - claims: jose.Claims{ - "sub": validClientID, - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // invalid 'iss' claim - { - claims: jose.Claims{ - "iss": "INVALID", - "sub": validClientID, - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // missing 'sub' claim - { - claims: jose.Claims{ - "iss": validIss, - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // invalid 'sub' claim - { - claims: jose.Claims{ - "iss": validIss, - "sub": "INVALID", - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // missing 'aud' claim - { - claims: jose.Claims{ - "iss": validIss, - "sub": validClientID, - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // invalid 'aud' claim - { - claims: jose.Claims{ - "iss": validIss, - "sub": validClientID, - "aud": "INVALID", - "iat": float64(now.Unix()), - "exp": float64(tomorrow.Unix()), - }, - ok: false, - }, - // expired - { - claims: jose.Claims{ - "iss": validIss, - "sub": validClientID, - "aud": validClientID, - "iat": float64(now.Unix()), - "exp": float64(now.Unix()), - }, - ok: false, - }, - } - - for i, tt := range tests { - jwt, err := jose.NewJWT(header, tt.claims) - if err != nil { - t.Fatalf("case %d: Failed to generate JWT, error=%v", i, err) - } - - got, err := VerifyClientClaims(jwt, validIss) - if tt.ok { - if err != nil { - t.Errorf("case %d: unexpected error, err=%v", i, err) - } - if got != validClientID { - t.Errorf("case %d: incorrect client ID, want=%s, got=%s", i, validClientID, got) - } - } else if err == nil { - t.Errorf("case %d: expected error but err is nil", i) - } - } -} - -func TestJWTVerifier(t *testing.T) { - iss := "http://example.com" - now := time.Now() - future12 := now.Add(12 * time.Hour) - past36 := now.Add(-36 * time.Hour) - past12 := now.Add(-12 * time.Hour) - - priv1, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - pk1 := *key.NewPublicKey(priv1.JWK()) - - priv2, err := key.GeneratePrivateKey() - if err != nil { - t.Fatalf("failed to generate private key, error=%v", err) - } - pk2 := *key.NewPublicKey(priv2.JWK()) - - jwtPK1, err := jose.NewSignedJWT(NewClaims(iss, "XXX", "XXX", past12, future12), priv1.Signer()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - jwtPK1BadClaims, err := jose.NewSignedJWT(NewClaims(iss, "XXX", "YYY", past12, future12), priv1.Signer()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - jwtExpired, err := jose.NewSignedJWT(NewClaims(iss, "XXX", "XXX", past36, past12), priv1.Signer()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - jwtPK2, err := jose.NewSignedJWT(NewClaims(iss, "XXX", "XXX", past12, future12), priv2.Signer()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - tests := []struct { - verifier JWTVerifier - jwt jose.JWT - wantErr bool - }{ - // JWT signed with available key - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() []key.PublicKey { - return []key.PublicKey{pk1} - }, - }, - jwt: *jwtPK1, - wantErr: false, - }, - - // JWT signed with available key, with bad claims - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() []key.PublicKey { - return []key.PublicKey{pk1} - }, - }, - jwt: *jwtPK1BadClaims, - wantErr: true, - }, - - // expired JWT signed with available key - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() []key.PublicKey { - return []key.PublicKey{pk1} - }, - }, - jwt: *jwtExpired, - wantErr: true, - }, - - // JWT signed with unrecognized key, verifiable after sync - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() func() []key.PublicKey { - var i int - return func() []key.PublicKey { - defer func() { i++ }() - return [][]key.PublicKey{ - []key.PublicKey{pk1}, - []key.PublicKey{pk2}, - }[i] - } - }(), - }, - jwt: *jwtPK2, - wantErr: false, - }, - - // JWT signed with unrecognized key, not verifiable after sync - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() []key.PublicKey { - return []key.PublicKey{pk1} - }, - }, - jwt: *jwtPK2, - wantErr: true, - }, - - // verifier gets no keys from keysFunc, still not verifiable after sync - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() []key.PublicKey { - return []key.PublicKey{} - }, - }, - jwt: *jwtPK1, - wantErr: true, - }, - - // verifier gets no keys from keysFunc, verifiable after sync - { - verifier: JWTVerifier{ - issuer: "example.com", - clientID: "XXX", - syncFunc: func() error { return nil }, - keysFunc: func() func() []key.PublicKey { - var i int - return func() []key.PublicKey { - defer func() { i++ }() - return [][]key.PublicKey{ - []key.PublicKey{}, - []key.PublicKey{pk2}, - }[i] - } - }(), - }, - jwt: *jwtPK2, - wantErr: false, - }, - } - - for i, tt := range tests { - err := tt.verifier.Verify(tt.jwt) - if tt.wantErr && (err == nil) { - t.Errorf("case %d: wanted non-nil error", i) - } else if !tt.wantErr && (err != nil) { - t.Errorf("case %d: wanted nil error, got %v", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-semver/semver/semver_test.go b/Godeps/_workspace/src/github.com/coreos/go-semver/semver/semver_test.go deleted file mode 100644 index de09cd7dc0c..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-semver/semver/semver_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package semver - -import ( - "math/rand" - "testing" - "time" -) - -type fixture struct { - greaterVersion string - lesserVersion string -} - -var fixtures = []fixture{ - fixture{"0.0.0", "0.0.0-foo"}, - fixture{"0.0.1", "0.0.0"}, - fixture{"1.0.0", "0.9.9"}, - fixture{"0.10.0", "0.9.0"}, - fixture{"0.99.0", "0.10.0"}, - fixture{"2.0.0", "1.2.3"}, - fixture{"0.0.0", "0.0.0-foo"}, - fixture{"0.0.1", "0.0.0"}, - fixture{"1.0.0", "0.9.9"}, - fixture{"0.10.0", "0.9.0"}, - fixture{"0.99.0", "0.10.0"}, - fixture{"2.0.0", "1.2.3"}, - fixture{"0.0.0", "0.0.0-foo"}, - fixture{"0.0.1", "0.0.0"}, - fixture{"1.0.0", "0.9.9"}, - fixture{"0.10.0", "0.9.0"}, - fixture{"0.99.0", "0.10.0"}, - fixture{"2.0.0", "1.2.3"}, - fixture{"1.2.3", "1.2.3-asdf"}, - fixture{"1.2.3", "1.2.3-4"}, - fixture{"1.2.3", "1.2.3-4-foo"}, - fixture{"1.2.3-5-foo", "1.2.3-5"}, - fixture{"1.2.3-5", "1.2.3-4"}, - fixture{"1.2.3-5-foo", "1.2.3-5-Foo"}, - fixture{"3.0.0", "2.7.2+asdf"}, - fixture{"3.0.0+foobar", "2.7.2"}, - fixture{"1.2.3-a.10", "1.2.3-a.5"}, - fixture{"1.2.3-a.b", "1.2.3-a.5"}, - fixture{"1.2.3-a.b", "1.2.3-a"}, - fixture{"1.2.3-a.b.c.10.d.5", "1.2.3-a.b.c.5.d.100"}, - fixture{"1.0.0", "1.0.0-rc.1"}, - fixture{"1.0.0-rc.2", "1.0.0-rc.1"}, - fixture{"1.0.0-rc.1", "1.0.0-beta.11"}, - fixture{"1.0.0-beta.11", "1.0.0-beta.2"}, - fixture{"1.0.0-beta.2", "1.0.0-beta"}, - fixture{"1.0.0-beta", "1.0.0-alpha.beta"}, - fixture{"1.0.0-alpha.beta", "1.0.0-alpha.1"}, - fixture{"1.0.0-alpha.1", "1.0.0-alpha"}, -} - -func TestCompare(t *testing.T) { - for _, v := range fixtures { - gt, err := NewVersion(v.greaterVersion) - if err != nil { - t.Error(err) - } - - lt, err := NewVersion(v.lesserVersion) - if err != nil { - t.Error(err) - } - - if gt.LessThan(*lt) == true { - t.Errorf("%s should not be less than %s", gt, lt) - } - } -} - -func testString(t *testing.T, orig string, version *Version) { - if orig != version.String() { - t.Errorf("%s != %s", orig, version) - } -} - -func TestString(t *testing.T) { - for _, v := range fixtures { - gt, err := NewVersion(v.greaterVersion) - if err != nil { - t.Error(err) - } - testString(t, v.greaterVersion, gt) - - lt, err := NewVersion(v.lesserVersion) - if err != nil { - t.Error(err) - } - testString(t, v.lesserVersion, lt) - } -} - -func shuffleStringSlice(src []string) []string { - dest := make([]string, len(src)) - rand.Seed(time.Now().Unix()) - perm := rand.Perm(len(src)) - for i, v := range perm { - dest[v] = src[i] - } - return dest -} - -func TestSort(t *testing.T) { - sortedVersions := []string{"1.0.0", "1.0.2", "1.2.0", "3.1.1"} - unsortedVersions := shuffleStringSlice(sortedVersions) - - semvers := []*Version{} - for _, v := range unsortedVersions { - sv, err := NewVersion(v) - if err != nil { - t.Fatal(err) - } - semvers = append(semvers, sv) - } - - Sort(semvers) - - for idx, sv := range semvers { - if sv.String() != sortedVersions[idx] { - t.Fatalf("incorrect sort at index %v", idx) - } - } -} - -func TestBumpMajor(t *testing.T) { - version, _ := NewVersion("1.0.0") - version.BumpMajor() - if version.Major != 2 { - t.Fatalf("bumping major on 1.0.0 resulted in %v", version) - } - - version, _ = NewVersion("1.5.2") - version.BumpMajor() - if version.Minor != 0 && version.Patch != 0 { - t.Fatalf("bumping major on 1.5.2 resulted in %v", version) - } - - version, _ = NewVersion("1.0.0+build.1-alpha.1") - version.BumpMajor() - if version.PreRelease != "" && version.PreRelease != "" { - t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) - } -} - -func TestBumpMinor(t *testing.T) { - version, _ := NewVersion("1.0.0") - version.BumpMinor() - - if version.Major != 1 { - t.Fatalf("bumping minor on 1.0.0 resulted in %v", version) - } - - if version.Minor != 1 { - t.Fatalf("bumping major on 1.0.0 resulted in %v", version) - } - - version, _ = NewVersion("1.0.0+build.1-alpha.1") - version.BumpMinor() - if version.PreRelease != "" && version.PreRelease != "" { - t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) - } -} - -func TestBumpPatch(t *testing.T) { - version, _ := NewVersion("1.0.0") - version.BumpPatch() - - if version.Major != 1 { - t.Fatalf("bumping minor on 1.0.0 resulted in %v", version) - } - - if version.Minor != 0 { - t.Fatalf("bumping major on 1.0.0 resulted in %v", version) - } - - if version.Patch != 1 { - t.Fatalf("bumping major on 1.0.0 resulted in %v", version) - } - - version, _ = NewVersion("1.0.0+build.1-alpha.1") - version.BumpPatch() - if version.PreRelease != "" && version.PreRelease != "" { - t.Fatalf("bumping major on 1.0.0+build.1-alpha.1 resulted in %v", version) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus_test.go deleted file mode 100644 index 4cfbe8296c7..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/dbus_test.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2013 CoreOS 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 dbus - -import ( - "testing" -) - -func TestNeedsEscape(t *testing.T) { - // Anything not 0-9a-zA-Z should always be escaped - for want, vals := range map[bool][]byte{ - false: []byte{'a', 'b', 'z', 'A', 'Q', '1', '4', '9'}, - true: []byte{'#', '%', '$', '!', '.', '_', '-', '%', '\\'}, - } { - for i := 1; i < 10; i++ { - for _, b := range vals { - got := needsEscape(i, b) - if got != want { - t.Errorf("needsEscape(%d, %c) returned %t, want %t", i, b, got, want) - } - } - } - } - - // 0-9 in position 0 should be escaped - for want, vals := range map[bool][]byte{ - false: []byte{'A', 'a', 'e', 'x', 'Q', 'Z'}, - true: []byte{'0', '4', '5', '9'}, - } { - for _, b := range vals { - got := needsEscape(0, b) - if got != want { - t.Errorf("needsEscape(0, %c) returned %t, want %t", b, got, want) - } - } - } - -} - -func TestPathBusEscape(t *testing.T) { - for in, want := range map[string]string{ - "": "_", - "foo.service": "foo_2eservice", - "foobar": "foobar", - "woof@woof.service": "woof_40woof_2eservice", - "0123456": "_30123456", - "account_db.service": "account_5fdb_2eservice", - "got-dashes": "got_2ddashes", - } { - got := PathBusEscape(in) - if got != want { - t.Errorf("bad result for PathBusEscape(%s): got %q, want %q", in, got, want) - } - } - -} - -// TestNew ensures that New() works without errors. -func TestNew(t *testing.T) { - _, err := New() - - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods_test.go deleted file mode 100644 index 8c7ab93eb36..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/methods_test.go +++ /dev/null @@ -1,332 +0,0 @@ -/* -Copyright 2013 CoreOS 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 dbus - -import ( - "fmt" - "math/rand" - "os" - "path/filepath" - "reflect" - "testing" - - "github.com/godbus/dbus" -) - -func setupConn(t *testing.T) *Conn { - conn, err := New() - if err != nil { - t.Fatal(err) - } - - return conn -} - -func findFixture(target string, t *testing.T) string { - abs, err := filepath.Abs("../fixtures/" + target) - if err != nil { - t.Fatal(err) - } - return abs -} - -func setupUnit(target string, conn *Conn, t *testing.T) { - // Blindly stop the unit in case it is running - conn.StopUnit(target, "replace") - - // Blindly remove the symlink in case it exists - targetRun := filepath.Join("/run/systemd/system/", target) - os.Remove(targetRun) -} - -func linkUnit(target string, conn *Conn, t *testing.T) { - abs := findFixture(target, t) - fixture := []string{abs} - - changes, err := conn.LinkUnitFiles(fixture, true, true) - if err != nil { - t.Fatal(err) - } - - if len(changes) < 1 { - t.Fatalf("Expected one change, got %v", changes) - } - - runPath := filepath.Join("/run/systemd/system/", target) - if changes[0].Filename != runPath { - t.Fatal("Unexpected target filename") - } -} - -// Ensure that basic unit starting and stopping works. -func TestStartStopUnit(t *testing.T) { - target := "start-stop.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - // 2. Start the unit - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Job is not done:", job) - } - - units, err := conn.ListUnits() - - var unit *UnitStatus - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit == nil { - t.Fatalf("Test unit not found in list") - } - - if unit.ActiveState != "active" { - t.Fatalf("Test unit not active") - } - - // 3. Stop the unit - job, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - units, err = conn.ListUnits() - - unit = nil - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit != nil { - t.Fatalf("Test unit found in list, should be stopped") - } -} - -// Enables a unit and then immediately tears it down -func TestEnableDisableUnit(t *testing.T) { - target := "enable-disable.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - abs := findFixture(target, t) - runPath := filepath.Join("/run/systemd/system/", target) - - // 1. Enable the unit - install, changes, err := conn.EnableUnitFiles([]string{abs}, true, true) - if err != nil { - t.Fatal(err) - } - - if install != false { - t.Fatal("Install was true") - } - - if len(changes) < 1 { - t.Fatalf("Expected one change, got %v", changes) - } - - if changes[0].Filename != runPath { - t.Fatal("Unexpected target filename") - } - - // 2. Disable the unit - dChanges, err := conn.DisableUnitFiles([]string{abs}, true) - if err != nil { - t.Fatal(err) - } - - if len(dChanges) != 1 { - t.Fatalf("Changes should include the path, %v", dChanges) - } - if dChanges[0].Filename != runPath { - t.Fatalf("Change should include correct filename, %+v", dChanges[0]) - } - if dChanges[0].Destination != "" { - t.Fatalf("Change destination should be empty, %+v", dChanges[0]) - } -} - -// TestGetUnitProperties reads the `-.mount` which should exist on all systemd -// systems and ensures that one of its properties is valid. -func TestGetUnitProperties(t *testing.T) { - conn := setupConn(t) - - unit := "-.mount" - - info, err := conn.GetUnitProperties(unit) - if err != nil { - t.Fatal(err) - } - - names := info["Wants"].([]string) - - if len(names) < 1 { - t.Fatal("/ is unwanted") - } - - if names[0] != "system.slice" { - t.Fatal("unexpected wants for /") - } - - prop, err := conn.GetUnitProperty(unit, "Wants") - if err != nil { - t.Fatal(err) - } - - if prop.Name != "Wants" { - t.Fatal("unexpected property name") - } - - val := prop.Value.Value().([]string) - if !reflect.DeepEqual(val, names) { - t.Fatal("unexpected property value") - } -} - -// TestGetUnitPropertiesRejectsInvalidName attempts to get the properties for a -// unit with an invalid name. This test should be run with --test.timeout set, -// as a fail will manifest as GetUnitProperties hanging indefinitely. -func TestGetUnitPropertiesRejectsInvalidName(t *testing.T) { - conn := setupConn(t) - - unit := "//invalid#$^/" - - _, err := conn.GetUnitProperties(unit) - if err == nil { - t.Fatal("Expected an error, got nil") - } - - _, err = conn.GetUnitProperty(unit, "Wants") - if err == nil { - t.Fatal("Expected an error, got nil") - } -} - -// TestSetUnitProperties changes a cgroup setting on the `tmp.mount` -// which should exist on all systemd systems and ensures that the -// property was set. -func TestSetUnitProperties(t *testing.T) { - conn := setupConn(t) - - unit := "tmp.mount" - - if err := conn.SetUnitProperties(unit, true, Property{"CPUShares", dbus.MakeVariant(uint64(1023))}); err != nil { - t.Fatal(err) - } - - info, err := conn.GetUnitTypeProperties(unit, "Mount") - if err != nil { - t.Fatal(err) - } - - value := info["CPUShares"].(uint64) - if value != 1023 { - t.Fatal("CPUShares of unit is not 1023:", value) - } -} - -// Ensure that basic transient unit starting and stopping works. -func TestStartStopTransientUnit(t *testing.T) { - conn := setupConn(t) - - props := []Property{ - PropExecStart([]string{"/bin/sleep", "400"}, false), - } - target := fmt.Sprintf("testing-transient-%d.service", rand.Int()) - - // Start the unit - job, err := conn.StartTransientUnit(target, "replace", props...) - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Job is not done:", job) - } - - units, err := conn.ListUnits() - - var unit *UnitStatus - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit == nil { - t.Fatalf("Test unit not found in list") - } - - if unit.ActiveState != "active" { - t.Fatalf("Test unit not active") - } - - // 3. Stop the unit - job, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - units, err = conn.ListUnits() - - unit = nil - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit != nil { - t.Fatalf("Test unit found in list, should be stopped") - } -} - -func TestConnJobListener(t *testing.T) { - target := "start-stop.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - jobSize := len(conn.jobListener.jobs) - - _, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - _, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - currentJobSize := len(conn.jobListener.jobs) - if jobSize != currentJobSize { - t.Fatal("JobListener jobs leaked") - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set_test.go deleted file mode 100644 index c4435f8800c..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/set_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package dbus - -import ( - "testing" -) - -// TestBasicSetActions asserts that Add & Remove behavior is correct -func TestBasicSetActions(t *testing.T) { - s := newSet() - - if s.Contains("foo") { - t.Fatal("set should not contain 'foo'") - } - - s.Add("foo") - - if !s.Contains("foo") { - t.Fatal("set should contain 'foo'") - } - - v := s.Values() - if len(v) != 1 { - t.Fatal("set.Values did not report correct number of values") - } - if v[0] != "foo" { - t.Fatal("set.Values did not report value") - } - - s.Remove("foo") - - if s.Contains("foo") { - t.Fatal("set should not contain 'foo'") - } - - v = s.Values() - if len(v) != 0 { - t.Fatal("set.Values did not report correct number of values") - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go deleted file mode 100644 index 4ecd15376d3..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package dbus - -import ( - "testing" - "time" -) - -// TestSubscribeUnit exercises the basics of subscription of a particular unit. -func TestSubscriptionSetUnit(t *testing.T) { - target := "subscribe-events-set.service" - - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - subSet := conn.NewSubscriptionSet() - evChan, errChan := subSet.Subscribe() - - subSet.Add(target) - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Couldn't start", target) - } - - timeout := make(chan bool, 1) - go func() { - time.Sleep(3 * time.Second) - close(timeout) - }() - - for { - select { - case changes := <-evChan: - tCh, ok := changes[target] - - if !ok { - t.Fatal("Unexpected event:", changes) - } - - if tCh.ActiveState == "active" && tCh.Name == target { - goto success - } - case err = <-errChan: - t.Fatal(err) - case <-timeout: - t.Fatal("Reached timeout") - } - } - -success: - return -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_test.go deleted file mode 100644 index f2b5dfc28c1..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/dbus/subscription_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package dbus - -import ( - "testing" - "time" -) - -// TestSubscribe exercises the basics of subscription -func TestSubscribe(t *testing.T) { - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - err = conn.Unsubscribe() - if err != nil { - t.Fatal(err) - } -} - -// TestSubscribeUnit exercises the basics of subscription of a particular unit. -func TestSubscribeUnit(t *testing.T) { - target := "subscribe-events.service" - - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - err = conn.Unsubscribe() - if err != nil { - t.Fatal(err) - } - - evChan, errChan := conn.SubscribeUnits(time.Second) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Couldn't start", target) - } - - timeout := make(chan bool, 1) - go func() { - time.Sleep(3 * time.Second) - close(timeout) - }() - - for { - select { - case changes := <-evChan: - tCh, ok := changes[target] - - // Just continue until we see our event. - if !ok { - continue - } - - if tCh.ActiveState == "active" && tCh.Name == target { - goto success - } - case err = <-errChan: - t.Fatal(err) - case <-timeout: - t.Fatal("Reached timeout") - } - } - -success: - return -} - - diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/deserialize_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/deserialize_test.go deleted file mode 100644 index bb98b82984e..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/deserialize_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package unit - -import ( - "bytes" - "fmt" - "reflect" - "testing" -) - -func TestDeserialize(t *testing.T) { - tests := []struct { - input []byte - output []*UnitOption - }{ - // multiple options underneath a section - { - []byte(`[Unit] -Description=Foo -Description=Bar -Requires=baz.service -After=baz.service -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Unit", "Description", "Bar"}, - &UnitOption{"Unit", "Requires", "baz.service"}, - &UnitOption{"Unit", "After", "baz.service"}, - }, - }, - - // multiple sections - { - []byte(`[Unit] -Description=Foo - -[Service] -ExecStart=/usr/bin/sleep infinity - -[X-Third-Party] -Pants=on - -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"}, - &UnitOption{"X-Third-Party", "Pants", "on"}, - }, - }, - - // multiple sections with no options - { - []byte(`[Unit] -[Service] -[X-Third-Party] -`), - []*UnitOption{}, - }, - - // multiple values not special-cased - { - []byte(`[Service] -Environment= "FOO=BAR" "BAZ=QUX" -`), - []*UnitOption{ - &UnitOption{"Service", "Environment", "\"FOO=BAR\" \"BAZ=QUX\""}, - }, - }, - - // line continuations respected - { - []byte(`[Unit] -Description= Unnecessarily wrapped \ - words here -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Unnecessarily wrapped words here"}, - }, - }, - - // comments ignored - { - []byte(`; comment alpha -# comment bravo -[Unit] -; comment charlie -# comment delta -#Description=Foo -Description=Bar -; comment echo -# comment foxtrot -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar"}, - }, - }, - - // apparent comment lines inside of line continuations not ignored - { - []byte(`[Unit] -Description=Bar\ -# comment alpha - -Description=Bar\ -# comment bravo \ -Baz -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar # comment alpha"}, - &UnitOption{"Unit", "Description", "Bar # comment bravo Baz"}, - }, - }, - - // options outside of sections are ignored - { - []byte(`Description=Foo -[Unit] -Description=Bar -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar"}, - }, - }, - - // garbage outside of sections are ignored - { - []byte(`<<<<<<<< -[Unit] -Description=Bar -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar"}, - }, - }, - - // garbage used as unit option - { - []byte(`[Unit] -<<<<<<<<=Bar -`), - []*UnitOption{ - &UnitOption{"Unit", "<<<<<<<<", "Bar"}, - }, - }, - - // option name with spaces are valid - { - []byte(`[Unit] -Some Thing = Bar -`), - []*UnitOption{ - &UnitOption{"Unit", "Some Thing", "Bar"}, - }, - }, - - // lack of trailing newline doesn't cause problem for non-continued file - { - []byte(`[Unit] -Description=Bar`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar"}, - }, - }, - - // unit file with continuation but no following line is ok, too - { - []byte(`[Unit] -Description=Bar \`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "Bar"}, - }, - }, - - // Assert utf8 characters are preserved - { - []byte(`[©] -µ☃=ÇôrèÕ$`), - []*UnitOption{ - &UnitOption{"©", "µ☃", "ÇôrèÕ$"}, - }, - }, - - // whitespace removed around option name - { - []byte(`[Unit] - Description =words here -`), - []*UnitOption{ - &UnitOption{"Unit", "Description", "words here"}, - }, - }, - - // whitespace around option value stripped - { - []byte(`[Unit] -Description= words here `), - []*UnitOption{ - &UnitOption{"Unit", "Description", "words here"}, - }, - }, - - // whitespace around option value stripped, regardless of continuation - { - []byte(`[Unit] -Description= words here \ - `), - []*UnitOption{ - &UnitOption{"Unit", "Description", "words here"}, - }, - }, - - // backslash not considered continuation if followed by text - { - []byte(`[Service] -ExecStart=/bin/bash -c "while true; do echo \"ping\"; sleep 1; done" -`), - []*UnitOption{ - &UnitOption{"Service", "ExecStart", `/bin/bash -c "while true; do echo \"ping\"; sleep 1; done"`}, - }, - }, - - // backslash not considered continuation if followed by whitespace, but still trimmed - { - []byte(`[Service] -ExecStart=/bin/bash echo poof \ `), - []*UnitOption{ - &UnitOption{"Service", "ExecStart", `/bin/bash echo poof \`}, - }, - }, - } - - assert := func(expect, output []*UnitOption) error { - if len(expect) != len(output) { - return fmt.Errorf("expected %d items, got %d", len(expect), len(output)) - } - - for i, _ := range expect { - if !reflect.DeepEqual(expect[i], output[i]) { - return fmt.Errorf("item %d: expected %v, got %v", i, expect[i], output[i]) - } - } - - return nil - } - - for i, tt := range tests { - output, err := Deserialize(bytes.NewReader(tt.input)) - if err != nil { - t.Errorf("case %d: unexpected error parsing unit: %v", i, err) - continue - } - - err = assert(tt.output, output) - if err != nil { - t.Errorf("case %d: %v", i, err) - t.Log("Expected options:") - logUnitOptionSlice(t, tt.output) - t.Log("Actual options:") - logUnitOptionSlice(t, output) - } - } -} - -func TestDeserializeFail(t *testing.T) { - tests := [][]byte{ - // malformed section header - []byte(`[Unit -Description=Foo -`), - - // garbage following section header - []byte(`[Unit] pants -Description=Foo -`), - - // option without value - []byte(`[Unit] -Description -`), - - // garbage inside of section - []byte(`[Unit] -<<<<<< -Description=Foo -`), - } - - for i, tt := range tests { - output, err := Deserialize(bytes.NewReader(tt)) - if err == nil { - t.Errorf("case %d: unexpected non-nil error, received nil", i) - t.Log("Output:") - logUnitOptionSlice(t, output) - } - } -} - -func logUnitOptionSlice(t *testing.T, opts []*UnitOption) { - for idx, opt := range opts { - t.Logf("%d: %v", idx, opt) - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/option_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/option_test.go deleted file mode 100644 index ebdc062f797..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/option_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package unit - -import ( - "testing" -) - -func TestAllMatch(t *testing.T) { - tests := []struct { - u1 []*UnitOption - u2 []*UnitOption - match bool - }{ - // empty lists match - { - u1: []*UnitOption{}, - u2: []*UnitOption{}, - match: true, - }, - - // simple match of a single option - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - }, - u2: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - }, - match: true, - }, - - // single option mismatched - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - }, - u2: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "BAR"}, - }, - match: false, - }, - - // multiple options match - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - }, - u2: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - }, - match: true, - }, - - // mismatch length - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - }, - u2: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - }, - match: false, - }, - - // multiple options misordered - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - }, - u2: []*UnitOption{ - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - {Section: "Unit", Name: "Description", Value: "FOO"}, - }, - match: false, - }, - - // interleaved sections mismatch - { - u1: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - {Section: "Service", Name: "ExecStop", Value: "/bin/true"}, - }, - u2: []*UnitOption{ - {Section: "Unit", Name: "Description", Value: "FOO"}, - {Section: "Service", Name: "ExecStart", Value: "/bin/true"}, - {Section: "Unit", Name: "BindsTo", Value: "bar.service"}, - {Section: "Service", Name: "ExecStop", Value: "/bin/true"}, - }, - match: false, - }, - } - - for i, tt := range tests { - match := AllMatch(tt.u1, tt.u2) - if match != tt.match { - t.Errorf("case %d: failed comparing u1 to u2 - expected match=%t, got %t", i, tt.match, match) - } - - match = AllMatch(tt.u2, tt.u1) - if match != tt.match { - t.Errorf("case %d: failed comparing u2 to u1 - expected match=%t, got %t", i, tt.match, match) - } - } -} - -func TestMatch(t *testing.T) { - tests := []struct { - o1 *UnitOption - o2 *UnitOption - match bool - }{ - // empty options match - { - o1: &UnitOption{}, - o2: &UnitOption{}, - match: true, - }, - - // all fields match - { - o1: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "FOO", - }, - o2: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "FOO", - }, - match: true, - }, - - // Section mismatch - { - o1: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "FOO", - }, - o2: &UnitOption{ - Section: "X-Other", - Name: "Description", - Value: "FOO", - }, - match: false, - }, - - // Name mismatch - { - o1: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "FOO", - }, - o2: &UnitOption{ - Section: "Unit", - Name: "BindsTo", - Value: "FOO", - }, - match: false, - }, - - // Value mismatch - { - o1: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "FOO", - }, - o2: &UnitOption{ - Section: "Unit", - Name: "Description", - Value: "BAR", - }, - match: false, - }, - } - - for i, tt := range tests { - match := tt.o1.Match(tt.o2) - if match != tt.match { - t.Errorf("case %d: failed comparing o1 to o2 - expected match=%t, got %t", i, tt.match, match) - } - - match = tt.o2.Match(tt.o1) - if match != tt.match { - t.Errorf("case %d: failed comparing o2 to o1 - expected match=%t, got %t", i, tt.match, match) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/serialize_test.go b/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/serialize_test.go deleted file mode 100644 index e5ec0f13b7a..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/go-systemd/unit/serialize_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package unit - -import ( - "io/ioutil" - "testing" -) - -func TestSerialize(t *testing.T) { - tests := []struct { - input []*UnitOption - output string - }{ - // no options results in empty file - { - []*UnitOption{}, - ``, - }, - - // options with same section share the header - { - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Unit", "BindsTo", "bar.service"}, - }, - `[Unit] -Description=Foo -BindsTo=bar.service -`, - }, - - // options with same name are not combined - { - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Unit", "Description", "Bar"}, - }, - `[Unit] -Description=Foo -Description=Bar -`, - }, - - // multiple options printed under different section headers - { - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"}, - }, - `[Unit] -Description=Foo - -[Service] -ExecStart=/usr/bin/sleep infinity -`, - }, - - // no optimization for unsorted options - { - []*UnitOption{ - &UnitOption{"Unit", "Description", "Foo"}, - &UnitOption{"Service", "ExecStart", "/usr/bin/sleep infinity"}, - &UnitOption{"Unit", "BindsTo", "bar.service"}, - }, - `[Unit] -Description=Foo - -[Service] -ExecStart=/usr/bin/sleep infinity - -[Unit] -BindsTo=bar.service -`, - }, - - // utf8 characters are not a problem - { - []*UnitOption{ - &UnitOption{"©", "µ☃", "ÇôrèÕ$"}, - }, - `[©] -µ☃=ÇôrèÕ$ -`, - }, - - // no verification is done on section names - { - []*UnitOption{ - &UnitOption{"Un\nit", "Description", "Foo"}, - }, - `[Un -it] -Description=Foo -`, - }, - - // no verification is done on option names - { - []*UnitOption{ - &UnitOption{"Unit", "Desc\nription", "Foo"}, - }, - `[Unit] -Desc -ription=Foo -`, - }, - - // no verification is done on option values - { - []*UnitOption{ - &UnitOption{"Unit", "Description", "Fo\no"}, - }, - `[Unit] -Description=Fo -o -`, - }, - } - - for i, tt := range tests { - outReader := Serialize(tt.input) - outBytes, err := ioutil.ReadAll(outReader) - if err != nil { - t.Errorf("case %d: encountered error while reading output: %v", i, err) - continue - } - - output := string(outBytes) - if tt.output != output { - t.Errorf("case %d: incorrect output") - t.Logf("Expected:\n%s", tt.output) - t.Logf("Actual:\n%s", output) - } - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/pkg/health/health_test.go b/Godeps/_workspace/src/github.com/coreos/pkg/health/health_test.go deleted file mode 100644 index 99428eb7387..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/pkg/health/health_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package health - -import ( - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "testing" - - "github.com/coreos/pkg/httputil" -) - -type boolChecker bool - -func (b boolChecker) Healthy() error { - if b { - return nil - } - return errors.New("Unhealthy") -} - -func errString(err error) string { - if err == nil { - return "" - } - return err.Error() -} - -func TestCheck(t *testing.T) { - for i, test := range []struct { - checks []Checkable - expected string - }{ - {[]Checkable{}, ""}, - - {[]Checkable{boolChecker(true)}, ""}, - - {[]Checkable{boolChecker(true), boolChecker(true)}, ""}, - - {[]Checkable{boolChecker(true), boolChecker(false)}, "Unhealthy"}, - - {[]Checkable{boolChecker(true), boolChecker(false), boolChecker(false)}, "multiple health check failure: [Unhealthy Unhealthy]"}, - } { - err := Check(test.checks) - - if errString(err) != test.expected { - t.Errorf("case %d: want %v, got %v", i, test.expected, errString(err)) - } - } -} - -func TestHandlerFunc(t *testing.T) { - for i, test := range []struct { - checker Checker - method string - expectedStatus string - expectedCode int - expectedMessage string - }{ - { - Checker{ - Checks: []Checkable{ - boolChecker(true), - }, - }, - "GET", - "ok", - http.StatusOK, - "", - }, - - // Wrong method. - { - Checker{ - Checks: []Checkable{ - boolChecker(true), - }, - }, - "POST", - "", - http.StatusMethodNotAllowed, - "GET only acceptable method", - }, - - // Health check fails. - { - Checker{ - Checks: []Checkable{ - boolChecker(false), - }, - }, - "GET", - "error", - http.StatusInternalServerError, - "Unhealthy", - }, - - // Health check fails, with overridden ErrorHandler. - { - Checker{ - Checks: []Checkable{ - boolChecker(false), - }, - UnhealthyHandler: func(w http.ResponseWriter, r *http.Request, err error) { - httputil.WriteJSONResponse(w, - http.StatusInternalServerError, StatusResponse{ - Status: "error", - Details: &StatusResponseDetails{ - Code: http.StatusInternalServerError, - Message: "Override!", - }, - }) - }, - }, - "GET", - "error", - http.StatusInternalServerError, - "Override!", - }, - - // Health check succeeds, with overridden SuccessHandler. - { - Checker{ - Checks: []Checkable{ - boolChecker(true), - }, - HealthyHandler: func(w http.ResponseWriter, r *http.Request) { - httputil.WriteJSONResponse(w, - http.StatusOK, StatusResponse{ - Status: "okey-dokey", - }) - }, - }, - "GET", - "okey-dokey", - http.StatusOK, - "", - }, - } { - w := httptest.NewRecorder() - r := &http.Request{} - r.Method = test.method - test.checker.ServeHTTP(w, r) - if w.Code != test.expectedCode { - t.Errorf("case %d: w.code == %v, want %v", i, w.Code, test.expectedCode) - } - - if test.expectedStatus == "" { - // This is to handle the wrong-method case, when the - // body of the response is empty. - continue - } - - statusMap := make(map[string]interface{}) - err := json.Unmarshal(w.Body.Bytes(), &statusMap) - if err != nil { - t.Fatalf("case %d: failed to Unmarshal response body: %v", i, err) - } - - status, ok := statusMap["status"].(string) - if !ok { - t.Errorf("case %d: status not present or not a string in json: %q", i, w.Body.Bytes()) - } - if status != test.expectedStatus { - t.Errorf("case %d: status == %v, want %v", i, status, test.expectedStatus) - } - - detailMap, ok := statusMap["details"].(map[string]interface{}) - if test.expectedMessage != "" { - if !ok { - t.Fatalf("case %d: could not find/unmarshal detailMap", i) - } - message, ok := detailMap["message"].(string) - if !ok { - t.Fatalf("case %d: message not present or not a string in json: %q", - i, w.Body.Bytes()) - } - if message != test.expectedMessage { - t.Errorf("case %d: message == %v, want %v", i, message, test.expectedMessage) - } - - code, ok := detailMap["code"].(float64) - if !ok { - t.Fatalf("case %d: code not present or not an int in json: %q", - i, w.Body.Bytes()) - } - if int(code) != test.expectedCode { - t.Errorf("case %d: code == %v, want %v", i, code, test.expectedCode) - } - - } else { - if ok { - t.Errorf("case %d: unwanted detailMap present: %q", i, detailMap) - } - } - - } -} diff --git a/Godeps/_workspace/src/github.com/coreos/pkg/httputil/json_test.go b/Godeps/_workspace/src/github.com/coreos/pkg/httputil/json_test.go deleted file mode 100644 index 92108927b3b..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/pkg/httputil/json_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package httputil - -import ( - "net/http/httptest" - "testing" -) - -func TestWriteJSONResponse(t *testing.T) { - for i, test := range []struct { - code int - resp interface{} - expectedJSON string - expectErr bool - }{ - { - 200, - struct { - A string - B string - }{A: "foo", B: "bar"}, - `{"A":"foo","B":"bar"}`, - false, - }, - { - 500, - // Something that json.Marshal cannot serialize. - make(chan int), - "", - true, - }, - } { - w := httptest.NewRecorder() - err := WriteJSONResponse(w, test.code, test.resp) - - if w.Code != test.code { - t.Errorf("case %d: w.code == %v, want %v", i, w.Code, test.code) - } - - if (err != nil) != test.expectErr { - t.Errorf("case %d: (err != nil) == %v, want %v. err: %v", i, err != nil, test.expectErr, err) - } - - if string(w.Body.Bytes()) != test.expectedJSON { - t.Errorf("case %d: w.Body.Bytes()) == %q, want %q", i, - string(w.Body.Bytes()), test.expectedJSON) - } - - if !test.expectErr { - contentType := w.Header()["Content-Type"][0] - if contentType != JSONContentType { - t.Errorf("case %d: contentType == %v, want %v", i, contentType, JSONContentType) - } - } - } - -} diff --git a/Godeps/_workspace/src/github.com/coreos/pkg/timeutil/backoff_test.go b/Godeps/_workspace/src/github.com/coreos/pkg/timeutil/backoff_test.go deleted file mode 100644 index d8392bc54ce..00000000000 --- a/Godeps/_workspace/src/github.com/coreos/pkg/timeutil/backoff_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package timeutil - -import ( - "testing" - "time" -) - -func TestExpBackoff(t *testing.T) { - tests := []struct { - prev time.Duration - max time.Duration - want time.Duration - }{ - { - prev: time.Duration(0), - max: time.Minute, - want: time.Second, - }, - { - prev: time.Second, - max: time.Minute, - want: 2 * time.Second, - }, - { - prev: 16 * time.Second, - max: time.Minute, - want: 32 * time.Second, - }, - { - prev: 32 * time.Second, - max: time.Minute, - want: time.Minute, - }, - { - prev: time.Minute, - max: time.Minute, - want: time.Minute, - }, - { - prev: 2 * time.Minute, - max: time.Minute, - want: time.Minute, - }, - } - - for i, tt := range tests { - got := ExpBackoff(tt.prev, tt.max) - if tt.want != got { - t.Errorf("case %d: want=%v got=%v", i, tt.want, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 39b7525b3d1..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 3dd9089177e..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1021 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be perfomed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := `(map[int]string) (len=3) { -(int) 1: (string) (len=1) "1", -(int) 2: (string) (len=1) "2", -(int) 3: (string) (len=1) "3" -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = `(map[spew_test.stringer]int) (len=3) { -(spew_test.stringer) (len=1) stringer 1: (int) 1, -(spew_test.stringer) (len=1) stringer 2: (int) 2, -(spew_test.stringer) (len=1) stringer 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = `(map[spew_test.pstringer]int) (len=3) { -(spew_test.pstringer) (len=1) stringer 1: (int) 1, -(spew_test.pstringer) (len=1) stringer 2: (int) 2, -(spew_test.pstringer) (len=1) stringer 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = `(map[spew_test.customError]int) (len=3) { -(spew_test.customError) error: 1: (int) 1, -(spew_test.customError) error: 2: (int) 2, -(spew_test.customError) error: 3: (int) 3 -} -` - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 9b8a358ec8d..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n") -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971fb3f..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index a7acd141257..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - flag Flag - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - flag Flag - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{Flag(flagTwo), uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{Flag(flagTwo), uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // flag: (spew_test.Flag) flagTwo, - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index b0f9761a4c4..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1535 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be perfomed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3s2 := "{s:stringer test S:stringer test2}" - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index b583bfdef3c..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2013 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" - "unsafe" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - if f == int('+') { - return true - } - return false -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) - *rvf = *rvf | ((1< - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "github.com/davecgh/go-spew/spew" - "io/ioutil" - "os" - "testing" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go b/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go deleted file mode 100644 index 5c87dd456ed..00000000000 --- a/Godeps/_workspace/src/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This code should really only be in the dumpcgo_test.go file, -// but unfortunately Go will not allow cgo in test files, so this is a -// workaround to allow cgo types to be tested. This configuration is used -// because spew itself does not require cgo to run even though it does handle -// certain cgo types specially. Rather than forcing all clients to require cgo -// and an external C compiler just to run the tests, this scheme makes them -// optional. -// +build cgo,testcgo - -package testdata - -/* -#include -typedef unsigned char custom_uchar_t; - -char *ncp = 0; -char *cp = "test"; -char ca[6] = {'t', 'e', 's', 't', '2', '\0'}; -unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'}; -signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'}; -uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'}; -custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'}; -*/ -import "C" - -// GetCgoNullCharPointer returns a null char pointer via cgo. This is only -// used for tests. -func GetCgoNullCharPointer() interface{} { - return C.ncp -} - -// GetCgoCharPointer returns a char pointer via cgo. This is only used for -// tests. -func GetCgoCharPointer() interface{} { - return C.cp -} - -// GetCgoCharArray returns a char array via cgo and the array's len and cap. -// This is only used for tests. -func GetCgoCharArray() (interface{}, int, int) { - return C.ca, len(C.ca), cap(C.ca) -} - -// GetCgoUnsignedCharArray returns an unsigned char array via cgo and the -// array's len and cap. This is only used for tests. -func GetCgoUnsignedCharArray() (interface{}, int, int) { - return C.uca, len(C.uca), cap(C.uca) -} - -// GetCgoSignedCharArray returns a signed char array via cgo and the array's len -// and cap. This is only used for tests. -func GetCgoSignedCharArray() (interface{}, int, int) { - return C.sca, len(C.sca), cap(C.sca) -} - -// GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and -// cap. This is only used for tests. -func GetCgoUint8tArray() (interface{}, int, int) { - return C.ui8ta, len(C.ui8ta), cap(C.ui8ta) -} - -// GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via -// cgo and the array's len and cap. This is only used for tests. -func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) { - return C.tuca, len(C.tuca), cap(C.tuca) -} diff --git a/Godeps/_workspace/src/github.com/daviddengcn/go-colortext/ct_test.go b/Godeps/_workspace/src/github.com/daviddengcn/go-colortext/ct_test.go deleted file mode 100644 index b2db7384d49..00000000000 --- a/Godeps/_workspace/src/github.com/daviddengcn/go-colortext/ct_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package ct - -import ( - "fmt" - "testing" -) - -func TestChangeColor(t *testing.T) { - defer ResetColor() - fmt.Println("Normal text...") - text := "This is an demo of using ChangeColor to output colorful texts" - i := 1 - for _, c := range text { - ChangeColor(Color(i/2%8)+Black, i%2 == 1, Color((i+2)/2%8)+Black, false) - fmt.Print(string(c)) - i++ - } // for c - fmt.Println() - ChangeColor(Red, true, White, false) - fmt.Println("Before reset.") - ChangeColor(Red, false, White, true) - fmt.Println("Before reset.") - ResetColor() - fmt.Println("After reset.") - fmt.Println("After reset.") -} 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 edb48e4dbd7..00000000000 --- 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 c7e114f4f97..00000000000 --- 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 9108dedb4f6..00000000000 --- 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_test.go b/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_test.go deleted file mode 100644 index 13ba1fcdc12..00000000000 --- 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/docker/docker/pkg/jsonmessage/jsonmessage_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/jsonmessage/jsonmessage_test.go deleted file mode 100644 index 2e78fa7ebf9..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/jsonmessage/jsonmessage_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package jsonmessage - -import ( - "bytes" - "fmt" - "testing" - "time" - - "github.com/docker/docker/pkg/term" - "github.com/docker/docker/pkg/timeutils" - "strings" -) - -func TestError(t *testing.T) { - je := JSONError{404, "Not found"} - if je.Error() != "Not found" { - t.Fatalf("Expected 'Not found' got '%s'", je.Error()) - } -} - -func TestProgress(t *testing.T) { - jp := JSONProgress{} - if jp.String() != "" { - t.Fatalf("Expected empty string, got '%s'", jp.String()) - } - - expected := " 1 B" - jp2 := JSONProgress{Current: 1} - if jp2.String() != expected { - t.Fatalf("Expected %q, got %q", expected, jp2.String()) - } - - expectedStart := "[==========> ] 20 B/100 B" - jp3 := JSONProgress{Current: 20, Total: 100, Start: time.Now().Unix()} - // Just look at the start of the string - // (the remaining time is really hard to test -_-) - if jp3.String()[:len(expectedStart)] != expectedStart { - t.Fatalf("Expected to start with %q, got %q", expectedStart, jp3.String()) - } - - expected = "[=========================> ] 50 B/100 B" - jp4 := JSONProgress{Current: 50, Total: 100} - if jp4.String() != expected { - t.Fatalf("Expected %q, got %q", expected, jp4.String()) - } - - // this number can't be negative gh#7136 - expected = "[==================================================>] 50 B/40 B" - jp5 := JSONProgress{Current: 50, Total: 40} - if jp5.String() != expected { - t.Fatalf("Expected %q, got %q", expected, jp5.String()) - } -} - -func TestJSONMessageDisplay(t *testing.T) { - now := time.Now().Unix() - messages := map[JSONMessage][]string{ - // Empty - JSONMessage{}: {"\n", "\n"}, - // Status - JSONMessage{ - Status: "status", - }: { - "status\n", - "status\n", - }, - // General - JSONMessage{ - Time: now, - ID: "ID", - From: "From", - Status: "status", - }: { - fmt.Sprintf("%v ID: (from From) status\n", time.Unix(now, 0).Format(timeutils.RFC3339NanoFixed)), - fmt.Sprintf("%v ID: (from From) status\n", time.Unix(now, 0).Format(timeutils.RFC3339NanoFixed)), - }, - // Stream over status - JSONMessage{ - Status: "status", - Stream: "stream", - }: { - "stream", - "stream", - }, - // With progress message - JSONMessage{ - Status: "status", - ProgressMessage: "progressMessage", - }: { - "status progressMessage", - "status progressMessage", - }, - // With progress, stream empty - JSONMessage{ - Status: "status", - Stream: "", - Progress: &JSONProgress{Current: 1}, - }: { - "", - fmt.Sprintf("%c[2K\rstatus 1 B\r", 27), - }, - } - - // The tests :) - for jsonMessage, expectedMessages := range messages { - // Without terminal - data := bytes.NewBuffer([]byte{}) - if err := jsonMessage.Display(data, false); err != nil { - t.Fatal(err) - } - if data.String() != expectedMessages[0] { - t.Fatalf("Expected [%v], got [%v]", expectedMessages[0], data.String()) - } - // With terminal - data = bytes.NewBuffer([]byte{}) - if err := jsonMessage.Display(data, true); err != nil { - t.Fatal(err) - } - if data.String() != expectedMessages[1] { - t.Fatalf("Expected [%v], got [%v]", expectedMessages[1], data.String()) - } - } -} - -// Test JSONMessage with an Error. It will return an error with the text as error, not the meaning of the HTTP code. -func TestJSONMessageDisplayWithJSONError(t *testing.T) { - data := bytes.NewBuffer([]byte{}) - jsonMessage := JSONMessage{Error: &JSONError{404, "Can't find it"}} - - err := jsonMessage.Display(data, true) - if err == nil || err.Error() != "Can't find it" { - t.Fatalf("Expected a JSONError 404, got [%v]", err) - } - - jsonMessage = JSONMessage{Error: &JSONError{401, "Anything"}} - err = jsonMessage.Display(data, true) - if err == nil || err.Error() != "Authentication is required." { - t.Fatalf("Expected an error [Authentication is required.], got [%v]", err) - } -} - -func TestDisplayJSONMessagesStreamInvalidJSON(t *testing.T) { - var ( - inFd uintptr - ) - data := bytes.NewBuffer([]byte{}) - reader := strings.NewReader("This is not a 'valid' JSON []") - inFd, _ = term.GetFdInfo(reader) - - if err := DisplayJSONMessagesStream(reader, data, inFd, false); err == nil && err.Error()[:17] != "invalid character" { - t.Fatalf("Should have thrown an error (invalid character in ..), got [%v]", err) - } -} - -func TestDisplayJSONMessagesStream(t *testing.T) { - var ( - inFd uintptr - ) - - messages := map[string][]string{ - // empty string - "": { - "", - ""}, - // Without progress & ID - "{ \"status\": \"status\" }": { - "status\n", - "status\n", - }, - // Without progress, with ID - "{ \"id\": \"ID\",\"status\": \"status\" }": { - "ID: status\n", - fmt.Sprintf("ID: status\n%c[%dB", 27, 0), - }, - // With progress - "{ \"id\": \"ID\", \"status\": \"status\", \"progress\": \"ProgressMessage\" }": { - "ID: status ProgressMessage", - fmt.Sprintf("\n%c[%dAID: status ProgressMessage%c[%dB", 27, 0, 27, 0), - }, - // With progressDetail - "{ \"id\": \"ID\", \"status\": \"status\", \"progressDetail\": { \"Current\": 1} }": { - "", // progressbar is disabled in non-terminal - fmt.Sprintf("\n%c[%dA%c[2K\rID: status 1 B\r%c[%dB", 27, 0, 27, 27, 0), - }, - } - for jsonMessage, expectedMessages := range messages { - data := bytes.NewBuffer([]byte{}) - reader := strings.NewReader(jsonMessage) - inFd, _ = term.GetFdInfo(reader) - - // Without terminal - if err := DisplayJSONMessagesStream(reader, data, inFd, false); err != nil { - t.Fatal(err) - } - if data.String() != expectedMessages[0] { - t.Fatalf("Expected an [%v], got [%v]", expectedMessages[0], data.String()) - } - - // With terminal - data = bytes.NewBuffer([]byte{}) - reader = strings.NewReader(jsonMessage) - if err := DisplayJSONMessagesStream(reader, data, inFd, true); err != nil { - t.Fatal(err) - } - if data.String() != expectedMessages[1] { - t.Fatalf("Expected an [%v], got [%v]", expectedMessages[1], data.String()) - } - } - -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go deleted file mode 100644 index 5c7f1b86a0a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mount_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package mount - -import ( - "os" - "path" - "testing" -) - -func TestMountOptionsParsing(t *testing.T) { - options := "noatime,ro,size=10k" - - flag, data := parseOptions(options) - - if data != "size=10k" { - t.Fatalf("Expected size=10 got %s", data) - } - - expectedFlag := NOATIME | RDONLY - - if flag != expectedFlag { - t.Fatalf("Expected %d got %d", expectedFlag, flag) - } -} - -func TestMounted(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - sourcePath = path.Join(sourceDir, "file.txt") - targetPath = path.Join(targetDir, "file.txt") - ) - - os.Mkdir(sourceDir, 0777) - os.Mkdir(targetDir, 0777) - - f, err := os.Create(sourcePath) - if err != nil { - t.Fatal(err) - } - f.WriteString("hello") - f.Close() - - f, err = os.Create(targetPath) - if err != nil { - t.Fatal(err) - } - f.Close() - - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - mounted, err := Mounted(targetDir) - if err != nil { - t.Fatal(err) - } - if !mounted { - t.Fatalf("Expected %s to be mounted", targetDir) - } - if _, err := os.Stat(targetDir); err != nil { - t.Fatal(err) - } -} - -func TestMountReadonly(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - sourcePath = path.Join(sourceDir, "file.txt") - targetPath = path.Join(targetDir, "file.txt") - ) - - os.Mkdir(sourceDir, 0777) - os.Mkdir(targetDir, 0777) - - f, err := os.Create(sourcePath) - if err != nil { - t.Fatal(err) - } - f.WriteString("hello") - f.Close() - - f, err = os.Create(targetPath) - if err != nil { - t.Fatal(err) - } - f.Close() - - if err := Mount(sourceDir, targetDir, "none", "bind,ro"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - f, err = os.OpenFile(targetPath, os.O_RDWR, 0777) - if err == nil { - t.Fatal("Should not be able to open a ro file as rw") - } -} - -func TestGetMounts(t *testing.T) { - mounts, err := GetMounts() - if err != nil { - t.Fatal(err) - } - - root := false - for _, entry := range mounts { - if entry.Mountpoint == "/" { - root = true - } - } - - if !root { - t.Fatal("/ should be mounted at least") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go deleted file mode 100644 index e92b7e2c741..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go +++ /dev/null @@ -1,477 +0,0 @@ -// +build linux - -package mount - -import ( - "bytes" - "testing" -) - -const ( - fedoraMountinfo = `15 35 0:3 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw - 16 35 0:14 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel - 17 35 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,seclabel,size=8056484k,nr_inodes=2014121,mode=755 - 18 16 0:15 / /sys/kernel/security rw,nosuid,nodev,noexec,relatime shared:7 - securityfs securityfs rw - 19 16 0:13 / /sys/fs/selinux rw,relatime shared:8 - selinuxfs selinuxfs rw - 20 17 0:16 / /dev/shm rw,nosuid,nodev shared:3 - tmpfs tmpfs rw,seclabel - 21 17 0:10 / /dev/pts rw,nosuid,noexec,relatime shared:4 - devpts devpts rw,seclabel,gid=5,mode=620,ptmxmode=000 - 22 35 0:17 / /run rw,nosuid,nodev shared:21 - tmpfs tmpfs rw,seclabel,mode=755 - 23 16 0:18 / /sys/fs/cgroup rw,nosuid,nodev,noexec shared:9 - tmpfs tmpfs rw,seclabel,mode=755 - 24 23 0:19 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:10 - cgroup cgroup rw,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd - 25 16 0:20 / /sys/fs/pstore rw,nosuid,nodev,noexec,relatime shared:20 - pstore pstore rw - 26 23 0:21 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:11 - cgroup cgroup rw,cpuset,clone_children - 27 23 0:22 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,cpuacct,cpu,clone_children - 28 23 0:23 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:13 - cgroup cgroup rw,memory,clone_children - 29 23 0:24 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:14 - cgroup cgroup rw,devices,clone_children - 30 23 0:25 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime shared:15 - cgroup cgroup rw,freezer,clone_children - 31 23 0:26 / /sys/fs/cgroup/net_cls rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,net_cls,clone_children - 32 23 0:27 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime shared:17 - cgroup cgroup rw,blkio,clone_children - 33 23 0:28 / /sys/fs/cgroup/perf_event rw,nosuid,nodev,noexec,relatime shared:18 - cgroup cgroup rw,perf_event,clone_children - 34 23 0:29 / /sys/fs/cgroup/hugetlb rw,nosuid,nodev,noexec,relatime shared:19 - cgroup cgroup rw,hugetlb,clone_children - 35 1 253:2 / / rw,relatime shared:1 - ext4 /dev/mapper/ssd-root--f20 rw,seclabel,data=ordered - 36 15 0:30 / /proc/sys/fs/binfmt_misc rw,relatime shared:22 - autofs systemd-1 rw,fd=38,pgrp=1,timeout=300,minproto=5,maxproto=5,direct - 37 17 0:12 / /dev/mqueue rw,relatime shared:23 - mqueue mqueue rw,seclabel - 38 35 0:31 / /tmp rw shared:24 - tmpfs tmpfs rw,seclabel - 39 17 0:32 / /dev/hugepages rw,relatime shared:25 - hugetlbfs hugetlbfs rw,seclabel - 40 16 0:7 / /sys/kernel/debug rw,relatime shared:26 - debugfs debugfs rw - 41 16 0:33 / /sys/kernel/config rw,relatime shared:27 - configfs configfs rw - 42 35 0:34 / /var/lib/nfs/rpc_pipefs rw,relatime shared:28 - rpc_pipefs sunrpc rw - 43 15 0:35 / /proc/fs/nfsd rw,relatime shared:29 - nfsd sunrpc rw - 45 35 8:17 / /boot rw,relatime shared:30 - ext4 /dev/sdb1 rw,seclabel,data=ordered - 46 35 253:4 / /home rw,relatime shared:31 - ext4 /dev/mapper/ssd-home rw,seclabel,data=ordered - 47 35 253:5 / /var/lib/libvirt/images rw,noatime,nodiratime shared:32 - ext4 /dev/mapper/ssd-virt rw,seclabel,discard,data=ordered - 48 35 253:12 / /mnt/old rw,relatime shared:33 - ext4 /dev/mapper/HelpDeskRHEL6-FedoraRoot rw,seclabel,data=ordered - 121 22 0:36 / /run/user/1000/gvfs rw,nosuid,nodev,relatime shared:104 - fuse.gvfsd-fuse gvfsd-fuse rw,user_id=1000,group_id=1000 - 124 16 0:37 / /sys/fs/fuse/connections rw,relatime shared:107 - fusectl fusectl rw - 165 38 253:3 / /tmp/mnt rw,relatime shared:147 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered - 167 35 253:15 / /var/lib/docker/devicemapper/mnt/aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,relatime shared:149 - ext4 /dev/mapper/docker-253:2-425882-aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,seclabel,discard,stripe=16,data=ordered - 171 35 253:16 / /var/lib/docker/devicemapper/mnt/c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,relatime shared:153 - ext4 /dev/mapper/docker-253:2-425882-c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,seclabel,discard,stripe=16,data=ordered - 175 35 253:17 / /var/lib/docker/devicemapper/mnt/1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,relatime shared:157 - ext4 /dev/mapper/docker-253:2-425882-1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,seclabel,discard,stripe=16,data=ordered - 179 35 253:18 / /var/lib/docker/devicemapper/mnt/d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,relatime shared:161 - ext4 /dev/mapper/docker-253:2-425882-d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,seclabel,discard,stripe=16,data=ordered - 183 35 253:19 / /var/lib/docker/devicemapper/mnt/6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,relatime shared:165 - ext4 /dev/mapper/docker-253:2-425882-6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,seclabel,discard,stripe=16,data=ordered - 187 35 253:20 / /var/lib/docker/devicemapper/mnt/8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,relatime shared:169 - ext4 /dev/mapper/docker-253:2-425882-8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,seclabel,discard,stripe=16,data=ordered - 191 35 253:21 / /var/lib/docker/devicemapper/mnt/c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,relatime shared:173 - ext4 /dev/mapper/docker-253:2-425882-c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,seclabel,discard,stripe=16,data=ordered - 195 35 253:22 / /var/lib/docker/devicemapper/mnt/2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,relatime shared:177 - ext4 /dev/mapper/docker-253:2-425882-2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,seclabel,discard,stripe=16,data=ordered - 199 35 253:23 / /var/lib/docker/devicemapper/mnt/37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,relatime shared:181 - ext4 /dev/mapper/docker-253:2-425882-37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,seclabel,discard,stripe=16,data=ordered - 203 35 253:24 / /var/lib/docker/devicemapper/mnt/aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,relatime shared:185 - ext4 /dev/mapper/docker-253:2-425882-aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,seclabel,discard,stripe=16,data=ordered - 207 35 253:25 / /var/lib/docker/devicemapper/mnt/928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,relatime shared:189 - ext4 /dev/mapper/docker-253:2-425882-928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,seclabel,discard,stripe=16,data=ordered - 211 35 253:26 / /var/lib/docker/devicemapper/mnt/0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,relatime shared:193 - ext4 /dev/mapper/docker-253:2-425882-0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,seclabel,discard,stripe=16,data=ordered - 215 35 253:27 / /var/lib/docker/devicemapper/mnt/d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,relatime shared:197 - ext4 /dev/mapper/docker-253:2-425882-d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,seclabel,discard,stripe=16,data=ordered - 219 35 253:28 / /var/lib/docker/devicemapper/mnt/bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,relatime shared:201 - ext4 /dev/mapper/docker-253:2-425882-bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,seclabel,discard,stripe=16,data=ordered - 223 35 253:29 / /var/lib/docker/devicemapper/mnt/7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,relatime shared:205 - ext4 /dev/mapper/docker-253:2-425882-7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,seclabel,discard,stripe=16,data=ordered - 227 35 253:30 / /var/lib/docker/devicemapper/mnt/c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,relatime shared:209 - ext4 /dev/mapper/docker-253:2-425882-c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,seclabel,discard,stripe=16,data=ordered - 231 35 253:31 / /var/lib/docker/devicemapper/mnt/8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,relatime shared:213 - ext4 /dev/mapper/docker-253:2-425882-8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,seclabel,discard,stripe=16,data=ordered - 235 35 253:32 / /var/lib/docker/devicemapper/mnt/1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,relatime shared:217 - ext4 /dev/mapper/docker-253:2-425882-1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,seclabel,discard,stripe=16,data=ordered - 239 35 253:33 / /var/lib/docker/devicemapper/mnt/e9aa60c60128cad1 rw,relatime shared:221 - ext4 /dev/mapper/docker-253:2-425882-e9aa60c60128cad1 rw,seclabel,discard,stripe=16,data=ordered - 243 35 253:34 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,relatime shared:225 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,seclabel,discard,stripe=16,data=ordered - 247 35 253:35 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,relatime shared:229 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,seclabel,discard,stripe=16,data=ordered - 31 21 0:23 / /DATA/foo_bla_bla rw,relatime - cifs //foo/BLA\040BLA\040BLA/ rw,sec=ntlm,cache=loose,unc=\\foo\BLA BLA BLA,username=my_login,domain=mydomain.com,uid=12345678,forceuid,gid=12345678,forcegid,addr=10.1.30.10,file_mode=0755,dir_mode=0755,nounix,rsize=61440,wsize=65536,actimeo=1` - - ubuntuMountInfo = `15 20 0:14 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw -16 20 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw -17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1015140k,nr_inodes=253785,mode=755 -18 17 0:11 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 -19 20 0:15 / /run rw,nosuid,noexec,relatime - tmpfs tmpfs rw,size=205044k,mode=755 -20 1 253:0 / / rw,relatime - ext4 /dev/disk/by-label/DOROOT rw,errors=remount-ro,data=ordered -21 15 0:16 / /sys/fs/cgroup rw,relatime - tmpfs none rw,size=4k,mode=755 -22 15 0:17 / /sys/fs/fuse/connections rw,relatime - fusectl none rw -23 15 0:6 / /sys/kernel/debug rw,relatime - debugfs none rw -24 15 0:10 / /sys/kernel/security rw,relatime - securityfs none rw -25 19 0:18 / /run/lock rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=5120k -26 21 0:19 / /sys/fs/cgroup/cpuset rw,relatime - cgroup cgroup rw,cpuset,clone_children -27 19 0:20 / /run/shm rw,nosuid,nodev,relatime - tmpfs none rw -28 21 0:21 / /sys/fs/cgroup/cpu rw,relatime - cgroup cgroup rw,cpu -29 19 0:22 / /run/user rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=102400k,mode=755 -30 15 0:23 / /sys/fs/pstore rw,relatime - pstore none rw -31 21 0:24 / /sys/fs/cgroup/cpuacct rw,relatime - cgroup cgroup rw,cpuacct -32 21 0:25 / /sys/fs/cgroup/memory rw,relatime - cgroup cgroup rw,memory -33 21 0:26 / /sys/fs/cgroup/devices rw,relatime - cgroup cgroup rw,devices -34 21 0:27 / /sys/fs/cgroup/freezer rw,relatime - cgroup cgroup rw,freezer -35 21 0:28 / /sys/fs/cgroup/blkio rw,relatime - cgroup cgroup rw,blkio -36 21 0:29 / /sys/fs/cgroup/perf_event rw,relatime - cgroup cgroup rw,perf_event -37 21 0:30 / /sys/fs/cgroup/hugetlb rw,relatime - cgroup cgroup rw,hugetlb -38 21 0:31 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime - cgroup systemd rw,name=systemd -39 20 0:32 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=caafa54fdc06525 -40 20 0:33 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8-init rw,relatime - aufs none rw,si=caafa54f882b525 -41 20 0:34 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8 rw,relatime - aufs none rw,si=caafa54f8829525 -42 20 0:35 / /var/lib/docker/aufs/mnt/16f4d7e96dd612903f425bfe856762f291ff2e36a8ecd55a2209b7d7cd81c30b rw,relatime - aufs none rw,si=caafa54f882d525 -43 20 0:36 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e-init rw,relatime - aufs none rw,si=caafa54f882f525 -44 20 0:37 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e rw,relatime - aufs none rw,si=caafa54f88ba525 -45 20 0:38 / /var/lib/docker/aufs/mnt/283f35a910233c756409313be71ecd8fcfef0df57108b8d740b61b3e88860452 rw,relatime - aufs none rw,si=caafa54f88b8525 -46 20 0:39 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1-init rw,relatime - aufs none rw,si=caafa54f88be525 -47 20 0:40 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1 rw,relatime - aufs none rw,si=caafa54f882c525 -48 20 0:41 / /var/lib/docker/aufs/mnt/de2b538c97d6366cc80e8658547c923ea1d042f85580df379846f36a4df7049d rw,relatime - aufs none rw,si=caafa54f85bb525 -49 20 0:42 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49-init rw,relatime - aufs none rw,si=caafa54fdc00525 -50 20 0:43 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49 rw,relatime - aufs none rw,si=caafa54fbaec525 -51 20 0:44 / /var/lib/docker/aufs/mnt/6ac1cace985c9fc9bea32234de8b36dba49bdd5e29a2972b327ff939d78a6274 rw,relatime - aufs none rw,si=caafa54f8e1a525 -52 20 0:45 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b-init rw,relatime - aufs none rw,si=caafa54f8e1d525 -53 20 0:46 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b rw,relatime - aufs none rw,si=caafa54f8e1b525 -54 20 0:47 / /var/lib/docker/aufs/mnt/cabb117d997f0f93519185aea58389a9762770b7496ed0b74a3e4a083fa45902 rw,relatime - aufs none rw,si=caafa54f810a525 -55 20 0:48 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33-init rw,relatime - aufs none rw,si=caafa54f8529525 -56 20 0:49 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33 rw,relatime - aufs none rw,si=caafa54f852f525 -57 20 0:50 / /var/lib/docker/aufs/mnt/16a1526fa445b84ce84f89506d219e87fa488a814063baf045d88b02f21166b3 rw,relatime - aufs none rw,si=caafa54f9e1d525 -58 20 0:51 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f-init rw,relatime - aufs none rw,si=caafa54f854d525 -59 20 0:52 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f rw,relatime - aufs none rw,si=caafa54f854e525 -60 20 0:53 / /var/lib/docker/aufs/mnt/e370c3e286bea027917baa0e4d251262681a472a87056e880dfd0513516dffd9 rw,relatime - aufs none rw,si=caafa54f840a525 -61 20 0:54 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e-init rw,relatime - aufs none rw,si=caafa54f8408525 -62 20 0:55 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e rw,relatime - aufs none rw,si=caafa54f8409525 -63 20 0:56 / /var/lib/docker/aufs/mnt/abd0b5ea5d355a67f911475e271924a5388ee60c27185fcd60d095afc4a09dc7 rw,relatime - aufs none rw,si=caafa54f9eb1525 -64 20 0:57 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2-init rw,relatime - aufs none rw,si=caafa54f85bf525 -65 20 0:58 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2 rw,relatime - aufs none rw,si=caafa54f85b8525 -66 20 0:59 / /var/lib/docker/aufs/mnt/912e1bf28b80a09644503924a8a1a4fb8ed10b808ca847bda27a369919aa52fa rw,relatime - aufs none rw,si=caafa54fbaea525 -67 20 0:60 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576-init rw,relatime - aufs none rw,si=caafa54f8472525 -68 20 0:61 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576 rw,relatime - aufs none rw,si=caafa54f8474525 -69 20 0:62 / /var/lib/docker/aufs/mnt/5aaebb79ef3097dfca377889aeb61a0c9d5e3795117d2b08d0751473c671dfb2 rw,relatime - aufs none rw,si=caafa54f8c5e525 -70 20 0:63 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2-init rw,relatime - aufs none rw,si=caafa54f8c3b525 -71 20 0:64 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2 rw,relatime - aufs none rw,si=caafa54f8c3d525 -72 20 0:65 / /var/lib/docker/aufs/mnt/2777f0763da4de93f8bebbe1595cc77f739806a158657b033eca06f827b6028a rw,relatime - aufs none rw,si=caafa54f8c3e525 -73 20 0:66 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e-init rw,relatime - aufs none rw,si=caafa54f8c39525 -74 20 0:67 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e rw,relatime - aufs none rw,si=caafa54f854f525 -75 20 0:68 / /var/lib/docker/aufs/mnt/06400b526ec18b66639c96efc41a84f4ae0b117cb28dafd56be420651b4084a0 rw,relatime - aufs none rw,si=caafa54f840b525 -76 20 0:69 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785-init rw,relatime - aufs none rw,si=caafa54fdddf525 -77 20 0:70 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785 rw,relatime - aufs none rw,si=caafa54f854b525 -78 20 0:71 / /var/lib/docker/aufs/mnt/1ff414fa93fd61ec81b0ab7b365a841ff6545accae03cceac702833aaeaf718f rw,relatime - aufs none rw,si=caafa54f8d85525 -79 20 0:72 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8-init rw,relatime - aufs none rw,si=caafa54f8da3525 -80 20 0:73 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8 rw,relatime - aufs none rw,si=caafa54f8da2525 -81 20 0:74 / /var/lib/docker/aufs/mnt/b68b1d4fe4d30016c552398e78b379a39f651661d8e1fa5f2460c24a5e723420 rw,relatime - aufs none rw,si=caafa54f8d81525 -82 20 0:75 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739-init rw,relatime - aufs none rw,si=caafa54f8da1525 -83 20 0:76 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739 rw,relatime - aufs none rw,si=caafa54f8da0525 -84 20 0:77 / /var/lib/docker/aufs/mnt/53e10b0329afc0e0d3322d31efaed4064139dc7027fe6ae445cffd7104bcc94f rw,relatime - aufs none rw,si=caafa54f8c35525 -85 20 0:78 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494-init rw,relatime - aufs none rw,si=caafa54f8db8525 -86 20 0:79 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494 rw,relatime - aufs none rw,si=caafa54f8dba525 -87 20 0:80 / /var/lib/docker/aufs/mnt/90fdd2c03eeaf65311f88f4200e18aef6d2772482712d9aea01cd793c64781b5 rw,relatime - aufs none rw,si=caafa54f8315525 -88 20 0:81 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f-init rw,relatime - aufs none rw,si=caafa54f8fc6525 -89 20 0:82 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f rw,relatime - aufs none rw,si=caafa54f8468525 -90 20 0:83 / /var/lib/docker/aufs/mnt/8cf9a993f50f3305abad3da268c0fc44ff78a1e7bba595ef9de963497496c3f9 rw,relatime - aufs none rw,si=caafa54f8c59525 -91 20 0:84 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173-init rw,relatime - aufs none rw,si=caafa54f846a525 -92 20 0:85 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173 rw,relatime - aufs none rw,si=caafa54f846b525 -93 20 0:86 / /var/lib/docker/aufs/mnt/d8c8288ec920439a48b5796bab5883ee47a019240da65e8d8f33400c31bac5df rw,relatime - aufs none rw,si=caafa54f8dbf525 -94 20 0:87 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6-init rw,relatime - aufs none rw,si=caafa54f810f525 -95 20 0:88 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6 rw,relatime - aufs none rw,si=caafa54fbae9525 -96 20 0:89 / /var/lib/docker/aufs/mnt/befc1c67600df449dddbe796c0d06da7caff1d2bbff64cde1f0ba82d224996b5 rw,relatime - aufs none rw,si=caafa54f8dab525 -97 20 0:90 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562-init rw,relatime - aufs none rw,si=caafa54fdc02525 -98 20 0:91 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562 rw,relatime - aufs none rw,si=caafa54f9eb0525 -99 20 0:92 / /var/lib/docker/aufs/mnt/2a31f10029f04ff9d4381167a9b739609853d7220d55a56cb654779a700ee246 rw,relatime - aufs none rw,si=caafa54f8c37525 -100 20 0:93 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927-init rw,relatime - aufs none rw,si=caafa54fd173525 -101 20 0:94 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927 rw,relatime - aufs none rw,si=caafa54f8108525 -102 20 0:95 / /var/lib/docker/aufs/mnt/eaa0f57403a3dc685268f91df3fbcd7a8423cee50e1a9ee5c3e1688d9d676bb4 rw,relatime - aufs none rw,si=caafa54f852d525 -103 20 0:96 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b-init rw,relatime - aufs none rw,si=caafa54f8d80525 -104 20 0:97 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b rw,relatime - aufs none rw,si=caafa54f8fc3525 -105 20 0:98 / /var/lib/docker/aufs/mnt/d1b322ae17613c6adee84e709641a9244ac56675244a89a64dc0075075fcbb83 rw,relatime - aufs none rw,si=caafa54f8c58525 -106 20 0:99 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd-init rw,relatime - aufs none rw,si=caafa54f8c63525 -107 20 0:100 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd rw,relatime - aufs none rw,si=caafa54f8c67525 -108 20 0:101 / /var/lib/docker/aufs/mnt/bc9d2a264158f83a617a069bf17cbbf2a2ba453db7d3951d9dc63cc1558b1c2b rw,relatime - aufs none rw,si=caafa54f8dbe525 -109 20 0:102 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99-init rw,relatime - aufs none rw,si=caafa54f9e0d525 -110 20 0:103 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99 rw,relatime - aufs none rw,si=caafa54f9e1b525 -111 20 0:104 / /var/lib/docker/aufs/mnt/d4dca7b02569c732e740071e1c654d4ad282de5c41edb619af1f0aafa618be26 rw,relatime - aufs none rw,si=caafa54f8dae525 -112 20 0:105 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7-init rw,relatime - aufs none rw,si=caafa54f8c5c525 -113 20 0:106 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7 rw,relatime - aufs none rw,si=caafa54fd172525 -114 20 0:107 / /var/lib/docker/aufs/mnt/e60c57499c0b198a6734f77f660cdbbd950a5b78aa23f470ca4f0cfcc376abef rw,relatime - aufs none rw,si=caafa54909c4525 -115 20 0:108 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35-init rw,relatime - aufs none rw,si=caafa54909c3525 -116 20 0:109 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35 rw,relatime - aufs none rw,si=caafa54909c7525 -117 20 0:110 / /var/lib/docker/aufs/mnt/2997be666d58b9e71469759bcb8bd9608dad0e533a1a7570a896919ba3388825 rw,relatime - aufs none rw,si=caafa54f8557525 -118 20 0:111 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93-init rw,relatime - aufs none rw,si=caafa54c6e88525 -119 20 0:112 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93 rw,relatime - aufs none rw,si=caafa54c6e8e525 -120 20 0:113 / /var/lib/docker/aufs/mnt/a672a1e2f2f051f6e19ed1dfbe80860a2d774174c49f7c476695f5dd1d5b2f67 rw,relatime - aufs none rw,si=caafa54c6e15525 -121 20 0:114 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420-init rw,relatime - aufs none rw,si=caafa54f8dad525 -122 20 0:115 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420 rw,relatime - aufs none rw,si=caafa54f8d84525 -123 20 0:116 / /var/lib/docker/aufs/mnt/2abc86007aca46fb4a817a033e2a05ccacae40b78ea4b03f8ea616b9ada40e2e rw,relatime - aufs none rw,si=caafa54c6e8b525 -124 20 0:117 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374-init rw,relatime - aufs none rw,si=caafa54c6e8d525 -125 20 0:118 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374 rw,relatime - aufs none rw,si=caafa54f8c34525 -126 20 0:119 / /var/lib/docker/aufs/mnt/2f95ca1a629cea8363b829faa727dd52896d5561f2c96ddee4f697ea2fc872c2 rw,relatime - aufs none rw,si=caafa54c6e8a525 -127 20 0:120 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2-init rw,relatime - aufs none rw,si=caafa54f8e19525 -128 20 0:121 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2 rw,relatime - aufs none rw,si=caafa54fa8c6525 -129 20 0:122 / /var/lib/docker/aufs/mnt/c1d04dfdf8cccb3676d5a91e84e9b0781ce40623d127d038bcfbe4c761b27401 rw,relatime - aufs none rw,si=caafa54f8c30525 -130 20 0:123 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a-init rw,relatime - aufs none rw,si=caafa54c6e1a525 -131 20 0:124 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a rw,relatime - aufs none rw,si=caafa54c6e1c525 -132 20 0:125 / /var/lib/docker/aufs/mnt/5ae3b6fccb1539fc02d420e86f3e9637bef5b711fed2ca31a2f426c8f5deddbf rw,relatime - aufs none rw,si=caafa54c4fea525 -133 20 0:126 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0-init rw,relatime - aufs none rw,si=caafa54c6e1e525 -134 20 0:127 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0 rw,relatime - aufs none rw,si=caafa54fa8c0525 -135 20 0:128 / /var/lib/docker/aufs/mnt/f382bd5aaccaf2d04a59089ac7cb12ec87efd769fd0c14d623358fbfd2a3f896 rw,relatime - aufs none rw,si=caafa54c4fec525 -136 20 0:129 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735-init rw,relatime - aufs none rw,si=caafa54c4fef525 -137 20 0:130 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735 rw,relatime - aufs none rw,si=caafa54c4feb525 -138 20 0:131 / /var/lib/docker/aufs/mnt/a9c5ee0854dc083b6bf62b7eb1e5291aefbb10702289a446471ce73aba0d5d7d rw,relatime - aufs none rw,si=caafa54909c6525 -139 20 0:134 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0-init rw,relatime - aufs none rw,si=caafa54804fe525 -140 20 0:135 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0 rw,relatime - aufs none rw,si=caafa54804fa525 -141 20 0:136 / /var/lib/docker/aufs/mnt/7ec3277e5c04c907051caf9c9c35889f5fcd6463e5485971b25404566830bb70 rw,relatime - aufs none rw,si=caafa54804f9525 -142 20 0:139 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8-init rw,relatime - aufs none rw,si=caafa54c6ef6525 -143 20 0:140 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8 rw,relatime - aufs none rw,si=caafa54c6ef5525 -144 20 0:356 / /var/lib/docker/aufs/mnt/e6ecde9e2c18cd3c75f424c67b6d89685cfee0fc67abf2cb6bdc0867eb998026 rw,relatime - aufs none rw,si=caafa548068e525` - - gentooMountinfo = `15 1 8:6 / / rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -16 15 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw -17 15 0:14 / /run rw,nosuid,nodev,relatime - tmpfs tmpfs rw,size=3292172k,mode=755 -18 15 0:5 / /dev rw,nosuid,relatime - devtmpfs udev rw,size=10240k,nr_inodes=4106451,mode=755 -19 18 0:12 / /dev/mqueue rw,nosuid,nodev,noexec,relatime - mqueue mqueue rw -20 18 0:10 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 -21 18 0:15 / /dev/shm rw,nosuid,nodev,noexec,relatime - tmpfs shm rw -22 15 0:16 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw -23 22 0:7 / /sys/kernel/debug rw,nosuid,nodev,noexec,relatime - debugfs debugfs rw -24 22 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs cgroup_root rw,size=10240k,mode=755 -25 24 0:18 / /sys/fs/cgroup/openrc rw,nosuid,nodev,noexec,relatime - cgroup openrc rw,release_agent=/lib64/rc/sh/cgroup-release-agent.sh,name=openrc -26 24 0:19 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cpuset rw,cpuset,clone_children -27 24 0:20 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cpu rw,cpu,clone_children -28 24 0:21 / /sys/fs/cgroup/cpuacct rw,nosuid,nodev,noexec,relatime - cgroup cpuacct rw,cpuacct,clone_children -29 24 0:22 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup memory rw,memory,clone_children -30 24 0:23 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime - cgroup devices rw,devices,clone_children -31 24 0:24 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime - cgroup freezer rw,freezer,clone_children -32 24 0:25 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime - cgroup blkio rw,blkio,clone_children -33 15 8:1 / /boot rw,noatime,nodiratime - vfat /dev/sda1 rw,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro -34 15 8:18 / /mnt/xfs rw,noatime,nodiratime - xfs /dev/sdb2 rw,attr2,inode64,noquota -35 15 0:26 / /tmp rw,relatime - tmpfs tmpfs rw -36 16 0:27 / /proc/sys/fs/binfmt_misc rw,nosuid,nodev,noexec,relatime - binfmt_misc binfmt_misc rw -42 15 0:33 / /var/lib/nfs/rpc_pipefs rw,relatime - rpc_pipefs rpc_pipefs rw -43 16 0:34 / /proc/fs/nfsd rw,nosuid,nodev,noexec,relatime - nfsd nfsd rw -44 15 0:35 / /home/tianon/.gvfs rw,nosuid,nodev,relatime - fuse.gvfs-fuse-daemon gvfs-fuse-daemon rw,user_id=1000,group_id=1000 -68 15 0:3336 / /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd rw,relatime - aufs none rw,si=9b4a7640128db39c -85 68 8:6 /var/lib/docker/init/dockerinit-0.7.2-dev//deleted /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerinit rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -86 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/config.env /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerenv rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -87 68 8:6 /etc/resolv.conf /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/resolv.conf rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -88 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hostname /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hostname rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -89 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hosts /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hosts rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered -38 15 0:3384 / /var/lib/docker/aufs/mnt/0292005a9292401bb5197657f2b682d97d8edcb3b72b5e390d2a680139985b55 rw,relatime - aufs none rw,si=9b4a7642b584939c -39 15 0:3385 / /var/lib/docker/aufs/mnt/59db98c889de5f71b70cfb82c40cbe47b64332f0f56042a2987a9e5df6e5e3aa rw,relatime - aufs none rw,si=9b4a7642b584e39c -40 15 0:3386 / /var/lib/docker/aufs/mnt/0545f0f2b6548eb9601d08f35a08f5a0a385407d36027a28f58e06e9f61e0278 rw,relatime - aufs none rw,si=9b4a7642b584b39c -41 15 0:3387 / /var/lib/docker/aufs/mnt/d882cfa16d1aa8fe0331a36e79be3d80b151e49f24fc39a39c3fed1735d5feb5 rw,relatime - aufs none rw,si=9b4a76453040039c -45 15 0:3388 / /var/lib/docker/aufs/mnt/055ca3befcb1626e74f5344b3398724ff05c0de0e20021683d04305c9e70a3f6 rw,relatime - aufs none rw,si=9b4a76453040739c -46 15 0:3389 / /var/lib/docker/aufs/mnt/b899e4567a351745d4285e7f1c18fdece75d877deb3041981cd290be348b7aa6 rw,relatime - aufs none rw,si=9b4a7647def4039c -47 15 0:3390 / /var/lib/docker/aufs/mnt/067ca040292c58954c5129f953219accfae0d40faca26b4d05e76ca76a998f16 rw,relatime - aufs none rw,si=9b4a7647def4239c -48 15 0:3391 / /var/lib/docker/aufs/mnt/8c995e7cb6e5082742daeea720e340b021d288d25d92e0412c03d200df308a11 rw,relatime - aufs none rw,si=9b4a764479c1639c -49 15 0:3392 / /var/lib/docker/aufs/mnt/07cc54dfae5b45300efdacdd53cc72c01b9044956a86ce7bff42d087e426096d rw,relatime - aufs none rw,si=9b4a764479c1739c -50 15 0:3393 / /var/lib/docker/aufs/mnt/0a9c95cf4c589c05b06baa79150b0cc1d8e7102759fe3ce4afaabb8247ca4f85 rw,relatime - aufs none rw,si=9b4a7644059c839c -51 15 0:3394 / /var/lib/docker/aufs/mnt/468fa98cececcf4e226e8370f18f4f848d63faf287fb8321a07f73086441a3a0 rw,relatime - aufs none rw,si=9b4a7644059ca39c -52 15 0:3395 / /var/lib/docker/aufs/mnt/0b826192231c5ce066fffb5beff4397337b5fc19a377aa7c6282c7c0ce7f111f rw,relatime - aufs none rw,si=9b4a764479c1339c -53 15 0:3396 / /var/lib/docker/aufs/mnt/93b8ba1b772fbe79709b909c43ea4b2c30d712e53548f467db1ffdc7a384f196 rw,relatime - aufs none rw,si=9b4a7640798a739c -54 15 0:3397 / /var/lib/docker/aufs/mnt/0c0d0acfb506859b12ef18cdfef9ebed0b43a611482403564224bde9149d373c rw,relatime - aufs none rw,si=9b4a7640798a039c -55 15 0:3398 / /var/lib/docker/aufs/mnt/33648c39ab6c7c74af0243d6d6a81b052e9e25ad1e04b19892eb2dde013e358b rw,relatime - aufs none rw,si=9b4a7644b439b39c -56 15 0:3399 / /var/lib/docker/aufs/mnt/0c12bea97a1c958a3c739fb148536c1c89351d48e885ecda8f0499b5cc44407e rw,relatime - aufs none rw,si=9b4a7640798a239c -57 15 0:3400 / /var/lib/docker/aufs/mnt/ed443988ce125f172d7512e84a4de2627405990fd767a16adefa8ce700c19ce8 rw,relatime - aufs none rw,si=9b4a7644c8ed339c -59 15 0:3402 / /var/lib/docker/aufs/mnt/f61612c324ff3c924d3f7a82fb00a0f8d8f73c248c41897061949e9f5ab7e3b1 rw,relatime - aufs none rw,si=9b4a76442810c39c -60 15 0:3403 / /var/lib/docker/aufs/mnt/0f1ee55c6c4e25027b80de8e64b8b6fb542b3b41aa0caab9261da75752e22bfd rw,relatime - aufs none rw,si=9b4a76442810e39c -61 15 0:3404 / /var/lib/docker/aufs/mnt/956f6cc4af5785cb3ee6963dcbca668219437d9b28f513290b1453ac64a34f97 rw,relatime - aufs none rw,si=9b4a7644303ec39c -62 15 0:3405 / /var/lib/docker/aufs/mnt/1099769158c4b4773e2569e38024e8717e400f87a002c41d8cf47cb81b051ba6 rw,relatime - aufs none rw,si=9b4a7644303ee39c -63 15 0:3406 / /var/lib/docker/aufs/mnt/11890ceb98d4442595b676085cd7b21550ab85c5df841e0fba997ff54e3d522d rw,relatime - aufs none rw,si=9b4a7644303ed39c -64 15 0:3407 / /var/lib/docker/aufs/mnt/acdb90dc378e8ed2420b43a6d291f1c789a081cd1904018780cc038fcd7aae53 rw,relatime - aufs none rw,si=9b4a76434be2139c -65 15 0:3408 / /var/lib/docker/aufs/mnt/120e716f19d4714fbe63cc1ed246204f2c1106eefebc6537ba2587d7e7711959 rw,relatime - aufs none rw,si=9b4a76434be2339c -66 15 0:3409 / /var/lib/docker/aufs/mnt/b197b7fffb61d89e0ba1c40de9a9fc0d912e778b3c1bd828cf981ff37c1963bc rw,relatime - aufs none rw,si=9b4a76434be2039c -70 15 0:3412 / /var/lib/docker/aufs/mnt/1434b69d2e1bb18a9f0b96b9cdac30132b2688f5d1379f68a39a5e120c2f93eb rw,relatime - aufs none rw,si=9b4a76434be2639c -71 15 0:3413 / /var/lib/docker/aufs/mnt/16006e83caf33ab5eb0cd6afc92ea2ee8edeff897496b0bb3ec3a75b767374b3 rw,relatime - aufs none rw,si=9b4a7644d790439c -72 15 0:3414 / /var/lib/docker/aufs/mnt/55bfa5f44e94d27f91f79ba901b118b15098449165c87abf1b53ffff147ff164 rw,relatime - aufs none rw,si=9b4a7644d790239c -73 15 0:3415 / /var/lib/docker/aufs/mnt/1912b97a07ab21ccd98a2a27bc779bf3cf364a3138afa3c3e6f7f169a3c3eab5 rw,relatime - aufs none rw,si=9b4a76441822739c -76 15 0:3418 / /var/lib/docker/aufs/mnt/1a7c3292e8879bd91ffd9282e954f643b1db5683093574c248ff14a9609f2f56 rw,relatime - aufs none rw,si=9b4a76438cb7239c -77 15 0:3419 / /var/lib/docker/aufs/mnt/bb1faaf0d076ddba82c2318305a85f490dafa4e8a8640a8db8ed657c439120cc rw,relatime - aufs none rw,si=9b4a76438cb7339c -78 15 0:3420 / /var/lib/docker/aufs/mnt/1ab869f21d2241a73ac840c7f988490313f909ac642eba71d092204fec66dd7c rw,relatime - aufs none rw,si=9b4a76438cb7639c -79 15 0:3421 / /var/lib/docker/aufs/mnt/fd7245b2cfe3890fa5f5b452260e4edf9e7fb7746532ed9d83f7a0d7dbaa610e rw,relatime - aufs none rw,si=9b4a7644bdc0139c -80 15 0:3422 / /var/lib/docker/aufs/mnt/1e5686c5301f26b9b3cd24e322c608913465cc6c5d0dcd7c5e498d1314747d61 rw,relatime - aufs none rw,si=9b4a7644bdc0639c -81 15 0:3423 / /var/lib/docker/aufs/mnt/52edf6ee6e40bfec1e9301a4d4a92ab83d144e2ae4ce5099e99df6138cb844bf rw,relatime - aufs none rw,si=9b4a7644bdc0239c -82 15 0:3424 / /var/lib/docker/aufs/mnt/1ea10fb7085d28cda4904657dff0454e52598d28e1d77e4f2965bbc3666e808f rw,relatime - aufs none rw,si=9b4a76438cb7139c -83 15 0:3425 / /var/lib/docker/aufs/mnt/9c03e98c3593946dbd4087f8d83f9ca262f4a2efdc952ce60690838b9ba6c526 rw,relatime - aufs none rw,si=9b4a76443020639c -84 15 0:3426 / /var/lib/docker/aufs/mnt/220a2344d67437602c6d2cee9a98c46be13f82c2a8063919dd2fad52bf2fb7dd rw,relatime - aufs none rw,si=9b4a76434bff339c -94 15 0:3427 / /var/lib/docker/aufs/mnt/3b32876c5b200312c50baa476ff342248e88c8ea96e6a1032cd53a88738a1cf2 rw,relatime - aufs none rw,si=9b4a76434bff139c -95 15 0:3428 / /var/lib/docker/aufs/mnt/23ee2b8b0d4ae8db6f6d1e168e2c6f79f8a18f953b09f65e0d22cc1e67a3a6fa rw,relatime - aufs none rw,si=9b4a7646c305c39c -96 15 0:3429 / /var/lib/docker/aufs/mnt/e86e6daa70b61b57945fa178222615f3c3d6bcef12c9f28e9f8623d44dc2d429 rw,relatime - aufs none rw,si=9b4a7646c305f39c -97 15 0:3430 / /var/lib/docker/aufs/mnt/2413d07623e80860bb2e9e306fbdee699afd07525785c025c591231e864aa162 rw,relatime - aufs none rw,si=9b4a76434bff039c -98 15 0:3431 / /var/lib/docker/aufs/mnt/adfd622eb22340fc80b429e5564b125668e260bf9068096c46dd59f1386a4b7d rw,relatime - aufs none rw,si=9b4a7646a7a1039c -102 15 0:3435 / /var/lib/docker/aufs/mnt/27cd92e7a91d02e2d6b44d16679a00fb6d169b19b88822891084e7fd1a84882d rw,relatime - aufs none rw,si=9b4a7646f25ec39c -103 15 0:3436 / /var/lib/docker/aufs/mnt/27dfdaf94cfbf45055c748293c37dd68d9140240bff4c646cb09216015914a88 rw,relatime - aufs none rw,si=9b4a7646732f939c -104 15 0:3437 / /var/lib/docker/aufs/mnt/5ed7524aff68dfbf0fc601cbaeac01bab14391850a973dabf3653282a627920f rw,relatime - aufs none rw,si=9b4a7646732f839c -105 15 0:3438 / /var/lib/docker/aufs/mnt/2a0d4767e536beb5785b60e071e3ac8e5e812613ab143a9627bee77d0c9ab062 rw,relatime - aufs none rw,si=9b4a7646732fe39c -106 15 0:3439 / /var/lib/docker/aufs/mnt/dea3fc045d9f4ae51ba952450b948a822cf85c39411489ca5224f6d9a8d02bad rw,relatime - aufs none rw,si=9b4a764012ad839c -107 15 0:3440 / /var/lib/docker/aufs/mnt/2d140a787160798da60cb67c21b1210054ad4dafecdcf832f015995b9aa99cfd rw,relatime - aufs none rw,si=9b4a764012add39c -108 15 0:3441 / /var/lib/docker/aufs/mnt/cb190b2a8e984475914430fbad2382e0d20b9b659f8ef83ae8d170cc672e519c rw,relatime - aufs none rw,si=9b4a76454d9c239c -109 15 0:3442 / /var/lib/docker/aufs/mnt/2f4a012d5a7ffd90256a6e9aa479054b3dddbc3c6a343f26dafbf3196890223b rw,relatime - aufs none rw,si=9b4a76454d9c439c -110 15 0:3443 / /var/lib/docker/aufs/mnt/63cc77904b80c4ffbf49cb974c5d8733dc52ad7640d3ae87554b325d7312d87f rw,relatime - aufs none rw,si=9b4a76454d9c339c -111 15 0:3444 / /var/lib/docker/aufs/mnt/30333e872c451482ea2d235ff2192e875bd234006b238ae2bdde3b91a86d7522 rw,relatime - aufs none rw,si=9b4a76422cebf39c -112 15 0:3445 / /var/lib/docker/aufs/mnt/6c54fc1125da3925cae65b5c9a98f3be55b0a2c2666082e5094a4ba71beb5bff rw,relatime - aufs none rw,si=9b4a7646dd5a439c -113 15 0:3446 / /var/lib/docker/aufs/mnt/3087d48cb01cda9d0a83a9ca301e6ea40e8593d18c4921be4794c91a420ab9a3 rw,relatime - aufs none rw,si=9b4a7646dd5a739c -114 15 0:3447 / /var/lib/docker/aufs/mnt/cc2607462a8f55b179a749b144c3fdbb50678e1a4f3065ea04e283e9b1f1d8e2 rw,relatime - aufs none rw,si=9b4a7646dd5a239c -117 15 0:3450 / /var/lib/docker/aufs/mnt/310c5e8392b29e8658a22e08d96d63936633b7e2c38e8d220047928b00a03d24 rw,relatime - aufs none rw,si=9b4a7647932d739c -118 15 0:3451 / /var/lib/docker/aufs/mnt/38a1f0029406ba9c3b6058f2f406d8a1d23c855046cf355c91d87d446fcc1460 rw,relatime - aufs none rw,si=9b4a76445abc939c -119 15 0:3452 / /var/lib/docker/aufs/mnt/42e109ab7914ae997a11ccd860fd18e4d488c50c044c3240423ce15774b8b62e rw,relatime - aufs none rw,si=9b4a76445abca39c -120 15 0:3453 / /var/lib/docker/aufs/mnt/365d832af0402d052b389c1e9c0d353b48487533d20cd4351df8e24ec4e4f9d8 rw,relatime - aufs none rw,si=9b4a7644066aa39c -121 15 0:3454 / /var/lib/docker/aufs/mnt/d3fa8a24d695b6cda9b64f96188f701963d28bef0473343f8b212df1a2cf1d2b rw,relatime - aufs none rw,si=9b4a7644066af39c -122 15 0:3455 / /var/lib/docker/aufs/mnt/37d4f491919abc49a15d0c7a7cc8383f087573525d7d288accd14f0b4af9eae0 rw,relatime - aufs none rw,si=9b4a7644066ad39c -123 15 0:3456 / /var/lib/docker/aufs/mnt/93902707fe12cbdd0068ce73f2baad4b3a299189b1b19cb5f8a2025e106ae3f5 rw,relatime - aufs none rw,si=9b4a76444445f39c -126 15 0:3459 / /var/lib/docker/aufs/mnt/3b49291670a625b9bbb329ffba99bf7fa7abff80cefef040f8b89e2b3aad4f9f rw,relatime - aufs none rw,si=9b4a7640798a339c -127 15 0:3460 / /var/lib/docker/aufs/mnt/8d9c7b943cc8f854f4d0d4ec19f7c16c13b0cc4f67a41472a072648610cecb59 rw,relatime - aufs none rw,si=9b4a76427383039c -128 15 0:3461 / /var/lib/docker/aufs/mnt/3b6c90036526c376307df71d49c9f5fce334c01b926faa6a78186842de74beac rw,relatime - aufs none rw,si=9b4a7644badd439c -130 15 0:3463 / /var/lib/docker/aufs/mnt/7b24158eeddfb5d31b7e932e406ea4899fd728344335ff8e0765e89ddeb351dd rw,relatime - aufs none rw,si=9b4a7644badd539c -131 15 0:3464 / /var/lib/docker/aufs/mnt/3ead6dd5773765c74850cf6c769f21fe65c29d622ffa712664f9f5b80364ce27 rw,relatime - aufs none rw,si=9b4a7642f469939c -132 15 0:3465 / /var/lib/docker/aufs/mnt/3f825573b29547744a37b65597a9d6d15a8350be4429b7038d126a4c9a8e178f rw,relatime - aufs none rw,si=9b4a7642f469c39c -133 15 0:3466 / /var/lib/docker/aufs/mnt/f67aaaeb3681e5dcb99a41f847087370bd1c206680cb8c7b6a9819fd6c97a331 rw,relatime - aufs none rw,si=9b4a7647cc25939c -134 15 0:3467 / /var/lib/docker/aufs/mnt/41afe6cfb3c1fc2280b869db07699da88552786e28793f0bc048a265c01bd942 rw,relatime - aufs none rw,si=9b4a7647cc25c39c -135 15 0:3468 / /var/lib/docker/aufs/mnt/b8092ea59da34a40b120e8718c3ae9fa8436996edc4fc50e4b99c72dfd81e1af rw,relatime - aufs none rw,si=9b4a76445abc439c -136 15 0:3469 / /var/lib/docker/aufs/mnt/42c69d2cc179e2684458bb8596a9da6dad182c08eae9b74d5f0e615b399f75a5 rw,relatime - aufs none rw,si=9b4a76455ddbe39c -137 15 0:3470 / /var/lib/docker/aufs/mnt/ea0871954acd2d62a211ac60e05969622044d4c74597870c4f818fbb0c56b09b rw,relatime - aufs none rw,si=9b4a76455ddbf39c -138 15 0:3471 / /var/lib/docker/aufs/mnt/4307906b275ab3fc971786b3841ae3217ac85b6756ddeb7ad4ba09cd044c2597 rw,relatime - aufs none rw,si=9b4a76455ddb839c -139 15 0:3472 / /var/lib/docker/aufs/mnt/4390b872928c53500a5035634f3421622ed6299dc1472b631fc45de9f56dc180 rw,relatime - aufs none rw,si=9b4a76402f2fd39c -140 15 0:3473 / /var/lib/docker/aufs/mnt/6bb41e78863b85e4aa7da89455314855c8c3bda64e52a583bab15dc1fa2e80c2 rw,relatime - aufs none rw,si=9b4a76402f2fa39c -141 15 0:3474 / /var/lib/docker/aufs/mnt/4444f583c2a79c66608f4673a32c9c812154f027045fbd558c2d69920c53f835 rw,relatime - aufs none rw,si=9b4a764479dbd39c -142 15 0:3475 / /var/lib/docker/aufs/mnt/6f11883af4a05ea362e0c54df89058da4859f977efd07b6f539e1f55c1d2a668 rw,relatime - aufs none rw,si=9b4a76402f30b39c -143 15 0:3476 / /var/lib/docker/aufs/mnt/453490dd32e7c2e9ef906f995d8fb3c2753923d1a5e0ba3fd3296e2e4dc238e7 rw,relatime - aufs none rw,si=9b4a76402f30c39c -144 15 0:3477 / /var/lib/docker/aufs/mnt/45e5945735ee102b5e891c91650c57ec4b52bb53017d68f02d50ea8a6e230610 rw,relatime - aufs none rw,si=9b4a76423260739c -147 15 0:3480 / /var/lib/docker/aufs/mnt/4727a64a5553a1125f315b96bed10d3073d6988225a292cce732617c925b56ab rw,relatime - aufs none rw,si=9b4a76443030339c -150 15 0:3483 / /var/lib/docker/aufs/mnt/4e348b5187b9a567059306afc72d42e0ec5c893b0d4abd547526d5f9b6fb4590 rw,relatime - aufs none rw,si=9b4a7644f5d8c39c -151 15 0:3484 / /var/lib/docker/aufs/mnt/4efc616bfbc3f906718b052da22e4335f8e9f91ee9b15866ed3a8029645189ef rw,relatime - aufs none rw,si=9b4a7644f5d8939c -152 15 0:3485 / /var/lib/docker/aufs/mnt/83e730ae9754d5adb853b64735472d98dfa17136b8812ac9cfcd1eba7f4e7d2d rw,relatime - aufs none rw,si=9b4a76469aa7139c -153 15 0:3486 / /var/lib/docker/aufs/mnt/4fc5ba8a5b333be2b7eefacccb626772eeec0ae8a6975112b56c9fb36c0d342f rw,relatime - aufs none rw,si=9b4a7640128dc39c -154 15 0:3487 / /var/lib/docker/aufs/mnt/50200d5edff5dfe8d1ef3c78b0bbd709793ac6e936aa16d74ff66f7ea577b6f9 rw,relatime - aufs none rw,si=9b4a7640128da39c -155 15 0:3488 / /var/lib/docker/aufs/mnt/51e5e51604361448f0b9777f38329f414bc5ba9cf238f26d465ff479bd574b61 rw,relatime - aufs none rw,si=9b4a76444f68939c -156 15 0:3489 / /var/lib/docker/aufs/mnt/52a142149aa98bba83df8766bbb1c629a97b9799944ead90dd206c4bdf0b8385 rw,relatime - aufs none rw,si=9b4a76444f68b39c -157 15 0:3490 / /var/lib/docker/aufs/mnt/52dd21a94a00f58a1ed489312fcfffb91578089c76c5650364476f1d5de031bc rw,relatime - aufs none rw,si=9b4a76444f68f39c -158 15 0:3491 / /var/lib/docker/aufs/mnt/ee562415ddaad353ed22c88d0ca768a0c74bfba6333b6e25c46849ee22d990da rw,relatime - aufs none rw,si=9b4a7640128d839c -159 15 0:3492 / /var/lib/docker/aufs/mnt/db47a9e87173f7554f550c8a01891de79cf12acdd32e01f95c1a527a08bdfb2c rw,relatime - aufs none rw,si=9b4a764405a1d39c -160 15 0:3493 / /var/lib/docker/aufs/mnt/55e827bf6d44d930ec0b827c98356eb8b68c3301e2d60d1429aa72e05b4c17df rw,relatime - aufs none rw,si=9b4a764405a1a39c -162 15 0:3495 / /var/lib/docker/aufs/mnt/578dc4e0a87fc37ec081ca098430499a59639c09f6f12a8f48de29828a091aa6 rw,relatime - aufs none rw,si=9b4a76406d7d439c -163 15 0:3496 / /var/lib/docker/aufs/mnt/728cc1cb04fa4bc6f7bf7a90980beda6d8fc0beb71630874c0747b994efb0798 rw,relatime - aufs none rw,si=9b4a76444f20e39c -164 15 0:3497 / /var/lib/docker/aufs/mnt/5850cc4bd9b55aea46c7ad598f1785117607974084ea643580f58ce3222e683a rw,relatime - aufs none rw,si=9b4a7644a824239c -165 15 0:3498 / /var/lib/docker/aufs/mnt/89443b3f766d5a37bc8b84e29da8b84e6a3ea8486d3cf154e2aae1816516e4a8 rw,relatime - aufs none rw,si=9b4a7644a824139c -166 15 0:3499 / /var/lib/docker/aufs/mnt/f5ae8fd5a41a337907d16515bc3162525154b59c32314c695ecd092c3b47943d rw,relatime - aufs none rw,si=9b4a7644a824439c -167 15 0:3500 / /var/lib/docker/aufs/mnt/5a430854f2a03a9e5f7cbc9f3fb46a8ebca526a5b3f435236d8295e5998798f5 rw,relatime - aufs none rw,si=9b4a7647fc82439c -168 15 0:3501 / /var/lib/docker/aufs/mnt/eda16901ae4cead35070c39845cbf1e10bd6b8cb0ffa7879ae2d8a186e460f91 rw,relatime - aufs none rw,si=9b4a76441e0df39c -169 15 0:3502 / /var/lib/docker/aufs/mnt/5a593721430c2a51b119ff86a7e06ea2b37e3b4131f8f1344d402b61b0c8d868 rw,relatime - aufs none rw,si=9b4a764248bad39c -170 15 0:3503 / /var/lib/docker/aufs/mnt/d662ad0a30fbfa902e0962108685b9330597e1ee2abb16dc9462eb5a67fdd23f rw,relatime - aufs none rw,si=9b4a764248bae39c -171 15 0:3504 / /var/lib/docker/aufs/mnt/5bc9de5c79812843fb36eee96bef1ddba812407861f572e33242f4ee10da2c15 rw,relatime - aufs none rw,si=9b4a764248ba839c -172 15 0:3505 / /var/lib/docker/aufs/mnt/5e763de8e9b0f7d58d2e12a341e029ab4efb3b99788b175090d8209e971156c1 rw,relatime - aufs none rw,si=9b4a764248baa39c -173 15 0:3506 / /var/lib/docker/aufs/mnt/b4431dc2739936f1df6387e337f5a0c99cf051900c896bd7fd46a870ce61c873 rw,relatime - aufs none rw,si=9b4a76401263539c -174 15 0:3507 / /var/lib/docker/aufs/mnt/5f37830e5a02561ab8c67ea3113137ba69f67a60e41c05cb0e7a0edaa1925b24 rw,relatime - aufs none rw,si=9b4a76401263639c -184 15 0:3508 / /var/lib/docker/aufs/mnt/62ea10b957e6533538a4633a1e1d678502f50ddcdd354b2ca275c54dd7a7793a rw,relatime - aufs none rw,si=9b4a76401263039c -187 15 0:3509 / /var/lib/docker/aufs/mnt/d56ee9d44195fe390e042fda75ec15af5132adb6d5c69468fa8792f4e54a6953 rw,relatime - aufs none rw,si=9b4a76401263239c -188 15 0:3510 / /var/lib/docker/aufs/mnt/6a300930673174549c2b62f36c933f0332a20735978c007c805a301f897146c5 rw,relatime - aufs none rw,si=9b4a76455d4c539c -189 15 0:3511 / /var/lib/docker/aufs/mnt/64496c45c84d348c24d410015456d101601c30cab4d1998c395591caf7e57a70 rw,relatime - aufs none rw,si=9b4a76455d4c639c -190 15 0:3512 / /var/lib/docker/aufs/mnt/65a6a645883fe97a7422cd5e71ebe0bc17c8e6302a5361edf52e89747387e908 rw,relatime - aufs none rw,si=9b4a76455d4c039c -191 15 0:3513 / /var/lib/docker/aufs/mnt/672be40695f7b6e13b0a3ed9fc996c73727dede3481f58155950fcfad57ed616 rw,relatime - aufs none rw,si=9b4a76455d4c239c -192 15 0:3514 / /var/lib/docker/aufs/mnt/d42438acb2bfb2169e1c0d8e917fc824f7c85d336dadb0b0af36dfe0f001b3ba rw,relatime - aufs none rw,si=9b4a7642bfded39c -193 15 0:3515 / /var/lib/docker/aufs/mnt/b48a54abf26d01cb2ddd908b1ed6034d17397c1341bf0eb2b251a3e5b79be854 rw,relatime - aufs none rw,si=9b4a7642bfdee39c -194 15 0:3516 / /var/lib/docker/aufs/mnt/76f27134491f052bfb87f59092126e53ef875d6851990e59195a9da16a9412f8 rw,relatime - aufs none rw,si=9b4a7642bfde839c -195 15 0:3517 / /var/lib/docker/aufs/mnt/6bd626a5462b4f8a8e1cc7d10351326dca97a59b2758e5ea549a4f6350ce8a90 rw,relatime - aufs none rw,si=9b4a7642bfdea39c -196 15 0:3518 / /var/lib/docker/aufs/mnt/f1fe3549dbd6f5ca615e9139d9b53f0c83a3b825565df37628eacc13e70cbd6d rw,relatime - aufs none rw,si=9b4a7642bfdf539c -197 15 0:3519 / /var/lib/docker/aufs/mnt/6d0458c8426a9e93d58d0625737e6122e725c9408488ed9e3e649a9984e15c34 rw,relatime - aufs none rw,si=9b4a7642bfdf639c -198 15 0:3520 / /var/lib/docker/aufs/mnt/6e4c97db83aa82145c9cf2bafc20d500c0b5389643b689e3ae84188c270a48c5 rw,relatime - aufs none rw,si=9b4a7642bfdf039c -199 15 0:3521 / /var/lib/docker/aufs/mnt/eb94d6498f2c5969eaa9fa11ac2934f1ab90ef88e2d002258dca08e5ba74ea27 rw,relatime - aufs none rw,si=9b4a7642bfdf239c -200 15 0:3522 / /var/lib/docker/aufs/mnt/fe3f88f0c511608a2eec5f13a98703aa16e55dbf930309723d8a37101f539fe1 rw,relatime - aufs none rw,si=9b4a7642bfc3539c -201 15 0:3523 / /var/lib/docker/aufs/mnt/6f40c229fb9cad85fabf4b64a2640a5403ec03fe5ac1a57d0609fb8b606b9c83 rw,relatime - aufs none rw,si=9b4a7642bfc3639c -202 15 0:3524 / /var/lib/docker/aufs/mnt/7513e9131f7a8acf58ff15248237feb767c78732ca46e159f4d791e6ef031dbc rw,relatime - aufs none rw,si=9b4a7642bfc3039c -203 15 0:3525 / /var/lib/docker/aufs/mnt/79f48b00aa713cdf809c6bb7c7cb911b66e9a8076c81d6c9d2504139984ea2da rw,relatime - aufs none rw,si=9b4a7642bfc3239c -204 15 0:3526 / /var/lib/docker/aufs/mnt/c3680418350d11358f0a96c676bc5aa74fa00a7c89e629ef5909d3557b060300 rw,relatime - aufs none rw,si=9b4a7642f47cd39c -205 15 0:3527 / /var/lib/docker/aufs/mnt/7a1744dd350d7fcc0cccb6f1757ca4cbe5453f203a5888b0f1014d96ad5a5ef9 rw,relatime - aufs none rw,si=9b4a7642f47ce39c -206 15 0:3528 / /var/lib/docker/aufs/mnt/7fa99662db046be9f03c33c35251afda9ccdc0085636bbba1d90592cec3ff68d rw,relatime - aufs none rw,si=9b4a7642f47c839c -207 15 0:3529 / /var/lib/docker/aufs/mnt/f815021ef20da9c9b056bd1d52d8aaf6e2c0c19f11122fc793eb2b04eb995e35 rw,relatime - aufs none rw,si=9b4a7642f47ca39c -208 15 0:3530 / /var/lib/docker/aufs/mnt/801086ae3110192d601dfcebdba2db92e86ce6b6a9dba6678ea04488e4513669 rw,relatime - aufs none rw,si=9b4a7642dc6dd39c -209 15 0:3531 / /var/lib/docker/aufs/mnt/822ba7db69f21daddda87c01cfbfbf73013fc03a879daf96d16cdde6f9b1fbd6 rw,relatime - aufs none rw,si=9b4a7642dc6de39c -210 15 0:3532 / /var/lib/docker/aufs/mnt/834227c1a950fef8cae3827489129d0dd220541e60c6b731caaa765bf2e6a199 rw,relatime - aufs none rw,si=9b4a7642dc6d839c -211 15 0:3533 / /var/lib/docker/aufs/mnt/83dccbc385299bd1c7cf19326e791b33a544eea7b4cdfb6db70ea94eed4389fb rw,relatime - aufs none rw,si=9b4a7642dc6da39c -212 15 0:3534 / /var/lib/docker/aufs/mnt/f1b8e6f0e7c8928b5dcdab944db89306ebcae3e0b32f9ff40d2daa8329f21600 rw,relatime - aufs none rw,si=9b4a7645a126039c -213 15 0:3535 / /var/lib/docker/aufs/mnt/970efb262c7a020c2404cbcc5b3259efba0d110a786079faeef05bc2952abf3a rw,relatime - aufs none rw,si=9b4a7644c8ed139c -214 15 0:3536 / /var/lib/docker/aufs/mnt/84b6d73af7450f3117a77e15a5ca1255871fea6182cd8e8a7be6bc744be18c2c rw,relatime - aufs none rw,si=9b4a76406559139c -215 15 0:3537 / /var/lib/docker/aufs/mnt/88be2716e026bc681b5e63fe7942068773efbd0b6e901ca7ba441412006a96b6 rw,relatime - aufs none rw,si=9b4a76406559339c -216 15 0:3538 / /var/lib/docker/aufs/mnt/c81939aa166ce50cd8bca5cfbbcc420a78e0318dd5cd7c755209b9166a00a752 rw,relatime - aufs none rw,si=9b4a76406559239c -217 15 0:3539 / /var/lib/docker/aufs/mnt/e0f241645d64b7dc5ff6a8414087cca226be08fb54ce987d1d1f6350c57083aa rw,relatime - aufs none rw,si=9b4a7647cfc0f39c -218 15 0:3540 / /var/lib/docker/aufs/mnt/e10e2bf75234ed51d8a6a4bb39e465404fecbe318e54400d3879cdb2b0679c78 rw,relatime - aufs none rw,si=9b4a7647cfc0939c -219 15 0:3541 / /var/lib/docker/aufs/mnt/8f71d74c8cfc3228b82564aa9f09b2e576cff0083ddfb6aa5cb350346063f080 rw,relatime - aufs none rw,si=9b4a7647cfc0a39c -220 15 0:3542 / /var/lib/docker/aufs/mnt/9159f1eba2aef7f5205cc18d015cda7f5933cd29bba3b1b8aed5ccb5824c69ee rw,relatime - aufs none rw,si=9b4a76468cedd39c -221 15 0:3543 / /var/lib/docker/aufs/mnt/932cad71e652e048e500d9fbb5b8ea4fc9a269d42a3134ce527ceef42a2be56b rw,relatime - aufs none rw,si=9b4a76468cede39c -222 15 0:3544 / /var/lib/docker/aufs/mnt/bf1e1b5f529e8943cc0144ee86dbaaa37885c1ddffcef29537e0078ee7dd316a rw,relatime - aufs none rw,si=9b4a76468ced839c -223 15 0:3545 / /var/lib/docker/aufs/mnt/949d93ecf3322e09f858ce81d5f4b434068ec44ff84c375de03104f7b45ee955 rw,relatime - aufs none rw,si=9b4a76468ceda39c -224 15 0:3546 / /var/lib/docker/aufs/mnt/d65c6087f92dc2a3841b5251d2fe9ca07d4c6e5b021597692479740816e4e2a1 rw,relatime - aufs none rw,si=9b4a7645a126239c -225 15 0:3547 / /var/lib/docker/aufs/mnt/98a0153119d0651c193d053d254f6e16a68345a141baa80c87ae487e9d33f290 rw,relatime - aufs none rw,si=9b4a7640787cf39c -226 15 0:3548 / /var/lib/docker/aufs/mnt/99daf7fe5847c017392f6e59aa9706b3dfdd9e6d1ba11dae0f7fffde0a60b5e5 rw,relatime - aufs none rw,si=9b4a7640787c839c -227 15 0:3549 / /var/lib/docker/aufs/mnt/9ad1f2fe8a5599d4e10c5a6effa7f03d932d4e92ee13149031a372087a359079 rw,relatime - aufs none rw,si=9b4a7640787ca39c -228 15 0:3550 / /var/lib/docker/aufs/mnt/c26d64494da782ddac26f8370d86ac93e7c1666d88a7b99110fc86b35ea6a85d rw,relatime - aufs none rw,si=9b4a7642fc6b539c -229 15 0:3551 / /var/lib/docker/aufs/mnt/a49e4a8275133c230ec640997f35f172312eb0ea5bd2bbe10abf34aae98f30eb rw,relatime - aufs none rw,si=9b4a7642fc6b639c -230 15 0:3552 / /var/lib/docker/aufs/mnt/b5e2740c867ed843025f49d84e8d769de9e8e6039b3c8cb0735b5bf358994bc7 rw,relatime - aufs none rw,si=9b4a7642fc6b039c -231 15 0:3553 / /var/lib/docker/aufs/mnt/a826fdcf3a7039b30570054579b65763db605a314275d7aef31b872c13311b4b rw,relatime - aufs none rw,si=9b4a7642fc6b239c -232 15 0:3554 / /var/lib/docker/aufs/mnt/addf3025babf5e43b5a3f4a0da7ad863dda3c01fb8365c58fd8d28bb61dc11bc rw,relatime - aufs none rw,si=9b4a76407871d39c -233 15 0:3555 / /var/lib/docker/aufs/mnt/c5b6c6813ab3e5ebdc6d22cb2a3d3106a62095f2c298be52b07a3b0fa20ff690 rw,relatime - aufs none rw,si=9b4a76407871e39c -234 15 0:3556 / /var/lib/docker/aufs/mnt/af0609eaaf64e2392060cb46f5a9f3d681a219bb4c651d4f015bf573fbe6c4cf rw,relatime - aufs none rw,si=9b4a76407871839c -235 15 0:3557 / /var/lib/docker/aufs/mnt/e7f20e3c37ecad39cd90a97cd3549466d0d106ce4f0a930b8495442634fa4a1f rw,relatime - aufs none rw,si=9b4a76407871a39c -237 15 0:3559 / /var/lib/docker/aufs/mnt/b57a53d440ffd0c1295804fa68cdde35d2fed5409484627e71b9c37e4249fd5c rw,relatime - aufs none rw,si=9b4a76444445a39c -238 15 0:3560 / /var/lib/docker/aufs/mnt/b5e7d7b8f35e47efbba3d80c5d722f5e7bd43e54c824e54b4a4b351714d36d42 rw,relatime - aufs none rw,si=9b4a7647932d439c -239 15 0:3561 / /var/lib/docker/aufs/mnt/f1b136def157e9465640658f277f3347de593c6ae76412a2e79f7002f091cae2 rw,relatime - aufs none rw,si=9b4a76445abcd39c -240 15 0:3562 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=9b4a7644403b339c -241 15 0:3563 / /var/lib/docker/aufs/mnt/b89b140cdbc95063761864e0a23346207fa27ee4c5c63a1ae85c9069a9d9cf1d rw,relatime - aufs none rw,si=9b4a7644aa19739c -242 15 0:3564 / /var/lib/docker/aufs/mnt/bc6a69ed51c07f5228f6b4f161c892e6a949c0e7e86a9c3432049d4c0e5cd298 rw,relatime - aufs none rw,si=9b4a7644aa19139c -243 15 0:3565 / /var/lib/docker/aufs/mnt/be4e2ba3f136933e239f7cf3d136f484fb9004f1fbdfee24a62a2c7b0ab30670 rw,relatime - aufs none rw,si=9b4a7644aa19339c -244 15 0:3566 / /var/lib/docker/aufs/mnt/e04ca1a4a5171e30d20f0c92f90a50b8b6f8600af5459c4b4fb25e42e864dfe1 rw,relatime - aufs none rw,si=9b4a7647932d139c -245 15 0:3567 / /var/lib/docker/aufs/mnt/be61576b31db893129aaffcd3dcb5ce35e49c4b71b30c392a78609a45c7323d8 rw,relatime - aufs none rw,si=9b4a7642d85f739c -246 15 0:3568 / /var/lib/docker/aufs/mnt/dda42c191e56becf672327658ab84fcb563322db3764b91c2fefe4aaef04c624 rw,relatime - aufs none rw,si=9b4a7642d85f139c -247 15 0:3569 / /var/lib/docker/aufs/mnt/c0a7995053330f3d88969247a2e72b07e2dd692133f5668a4a35ea3905561072 rw,relatime - aufs none rw,si=9b4a7642d85f339c -249 15 0:3571 / /var/lib/docker/aufs/mnt/c3594b2e5f08c59ff5ed338a1ba1eceeeb1f7fc5d180068338110c00b1eb8502 rw,relatime - aufs none rw,si=9b4a7642738c739c -250 15 0:3572 / /var/lib/docker/aufs/mnt/c58dce03a0ab0a7588393880379dc3bce9f96ec08ed3f99cf1555260ff0031e8 rw,relatime - aufs none rw,si=9b4a7642738c139c -251 15 0:3573 / /var/lib/docker/aufs/mnt/c73e9f1d109c9d14cb36e1c7489df85649be3911116d76c2fd3648ec8fd94e23 rw,relatime - aufs none rw,si=9b4a7642738c339c -252 15 0:3574 / /var/lib/docker/aufs/mnt/c9eef28c344877cd68aa09e543c0710ab2b305a0ff96dbb859bfa7808c3e8d01 rw,relatime - aufs none rw,si=9b4a7642d85f439c -253 15 0:3575 / /var/lib/docker/aufs/mnt/feb67148f548d70cb7484f2aaad2a86051cd6867a561741a2f13b552457d666e rw,relatime - aufs none rw,si=9b4a76468c55739c -254 15 0:3576 / /var/lib/docker/aufs/mnt/cdf1f96c36d35a96041a896bf398ec0f7dc3b0fb0643612a0f4b6ff96e04e1bb rw,relatime - aufs none rw,si=9b4a76468c55139c -255 15 0:3577 / /var/lib/docker/aufs/mnt/ec6e505872353268451ac4bc034c1df00f3bae4a3ea2261c6e48f7bd5417c1b3 rw,relatime - aufs none rw,si=9b4a76468c55339c -256 15 0:3578 / /var/lib/docker/aufs/mnt/d6dc8aca64efd90e0bc10274001882d0efb310d42ccbf5712b99b169053b8b1a rw,relatime - aufs none rw,si=9b4a7642738c439c -257 15 0:3579 / /var/lib/docker/aufs/mnt/d712594e2ff6eaeb895bfd150d694bd1305fb927e7a186b2dab7df2ea95f8f81 rw,relatime - aufs none rw,si=9b4a76401268f39c -259 15 0:3581 / /var/lib/docker/aufs/mnt/dbfa1174cd78cde2d7410eae442af0b416c4a0e6f87ed4ff1e9f169a0029abc0 rw,relatime - aufs none rw,si=9b4a76401268b39c -260 15 0:3582 / /var/lib/docker/aufs/mnt/e883f5a82316d7856fbe93ee8c0af5a920b7079619dd95c4ffd88bbd309d28dd rw,relatime - aufs none rw,si=9b4a76468c55439c -261 15 0:3583 / /var/lib/docker/aufs/mnt/fdec3eff581c4fc2b09f87befa2fa021f3f2d373bea636a87f1fb5b367d6347a rw,relatime - aufs none rw,si=9b4a7644aa1af39c -262 15 0:3584 / /var/lib/docker/aufs/mnt/ef764e26712184653067ecf7afea18a80854c41331ca0f0ef03e1bacf90a6ffc rw,relatime - aufs none rw,si=9b4a7644aa1a939c -263 15 0:3585 / /var/lib/docker/aufs/mnt/f3176b40c41fce8ce6942936359a2001a6f1b5c1bb40ee224186db0789ec2f76 rw,relatime - aufs none rw,si=9b4a7644aa1ab39c -264 15 0:3586 / /var/lib/docker/aufs/mnt/f5daf06785d3565c6dd18ea7d953d9a8b9606107781e63270fe0514508736e6a rw,relatime - aufs none rw,si=9b4a76401268c39c -58 15 0:3587 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8-init rw,relatime - aufs none rw,si=9b4a76444445839c -67 15 0:3588 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8 rw,relatime - aufs none rw,si=9b4a7644badd339c -265 15 0:3610 / /var/lib/docker/aufs/mnt/e812472cd2c8c4748d1ef71fac4e77e50d661b9349abe66ce3e23511ed44f414 rw,relatime - aufs none rw,si=9b4a76427937d39c -270 15 0:3615 / /var/lib/docker/aufs/mnt/997636e7c5c9d0d1376a217e295c14c205350b62bc12052804fb5f90abe6f183 rw,relatime - aufs none rw,si=9b4a76406540739c -273 15 0:3618 / /var/lib/docker/aufs/mnt/d5794d080417b6e52e69227c3873e0e4c1ff0d5a845ebe3860ec2f89a47a2a1e rw,relatime - aufs none rw,si=9b4a76454814039c -278 15 0:3623 / /var/lib/docker/aufs/mnt/586bdd48baced671bb19bc4d294ec325f26c55545ae267db426424f157d59c48 rw,relatime - aufs none rw,si=9b4a7644b439f39c -281 15 0:3626 / /var/lib/docker/aufs/mnt/69739d022f89f8586908bbd5edbbdd95ea5256356f177f9ffcc6ef9c0ea752d2 rw,relatime - aufs none rw,si=9b4a7644a0f1b39c -286 15 0:3631 / /var/lib/docker/aufs/mnt/ff28c27d5f894363993622de26d5dd352dba072f219e4691d6498c19bbbc15a9 rw,relatime - aufs none rw,si=9b4a7642265b339c -289 15 0:3634 / /var/lib/docker/aufs/mnt/aa128fe0e64fdede333aa48fd9de39530c91a9244a0f0649a3c411c61e372daa rw,relatime - aufs none rw,si=9b4a764012ada39c -99 15 8:33 / /media/REMOVE\040ME rw,nosuid,nodev,relatime - fuseblk /dev/sdc1 rw,user_id=0,group_id=0,allow_other,blksize=4096` -) - -func TestParseFedoraMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(fedoraMountinfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseUbuntuMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(ubuntuMountInfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseGentooMountinfo(t *testing.T) { - r := bytes.NewBuffer([]byte(gentooMountinfo)) - _, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } -} - -func TestParseFedoraMountinfoFields(t *testing.T) { - r := bytes.NewBuffer([]byte(fedoraMountinfo)) - infos, err := parseInfoFile(r) - if err != nil { - t.Fatal(err) - } - expectedLength := 58 - if len(infos) != expectedLength { - t.Fatalf("Expected %d entries, got %d", expectedLength, len(infos)) - } - mi := MountInfo{ - Id: 15, - Parent: 35, - Major: 0, - Minor: 3, - Root: "/", - Mountpoint: "/proc", - Opts: "rw,nosuid,nodev,noexec,relatime", - Optional: "shared:5", - Fstype: "proc", - Source: "proc", - VfsOpts: "rw", - } - - if *infos[0] != mi { - t.Fatalf("expected %#v, got %#v", mi, infos[0]) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go deleted file mode 100644 index da9aa15015a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go +++ /dev/null @@ -1,331 +0,0 @@ -// +build linux - -package mount - -import ( - "os" - "path" - "syscall" - "testing" -) - -// nothing is propagated in or out -func TestSubtreePrivate(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outside1Dir = path.Join(tmp, "outside1") - outside2Dir = path.Join(tmp, "outside2") - - outside1Path = path.Join(outside1Dir, "file.txt") - outside2Path = path.Join(outside2Dir, "file.txt") - outside1CheckPath = path.Join(targetDir, "a", "file.txt") - outside2CheckPath = path.Join(sourceDir, "b", "file.txt") - ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside1Dir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside2Dir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outside1Path); err != nil { - t.Fatal(err) - } - if err := createFile(outside2Path); err != nil { - t.Fatal(err) - } - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // next, make the target private - if err := MakePrivate(targetDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the _source_ - if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(sourceDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _target_ - if _, err := os.Stat(outside1CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside1CheckPath) - } - - // next mount outside2Dir into the _target_ - if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "b")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _source_ - if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside2CheckPath) - } -} - -// Testing that when a target is a shared mount, -// then child mounts propogate to the source -func TestSubtreeShared(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outsideDir = path.Join(tmp, "outside") - - outsidePath = path.Join(outsideDir, "file.txt") - sourceCheckPath = path.Join(sourceDir, "a", "file.txt") - ) - - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outsideDir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outsidePath); err != nil { - t.Fatal(err) - } - - // mount the source as shared - if err := MakeShared(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the target - if err := Mount(outsideDir, path.Join(targetDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // NOW, check that the file from the outside directory is avaible in the source directory - if _, err := os.Stat(sourceCheckPath); err != nil { - t.Fatal(err) - } -} - -// testing that mounts to a shared source show up in the slave target, -// and that mounts into a slave target do _not_ show up in the shared source -func TestSubtreeSharedSlave(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - outside1Dir = path.Join(tmp, "outside1") - outside2Dir = path.Join(tmp, "outside2") - - outside1Path = path.Join(outside1Dir, "file.txt") - outside2Path = path.Join(outside2Dir, "file.txt") - outside1CheckPath = path.Join(targetDir, "a", "file.txt") - outside2CheckPath = path.Join(sourceDir, "b", "file.txt") - ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(targetDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside1Dir, 0777); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(outside2Dir, 0777); err != nil { - t.Fatal(err) - } - - if err := createFile(outside1Path); err != nil { - t.Fatal(err) - } - if err := createFile(outside2Path); err != nil { - t.Fatal(err) - } - - // mount the source as shared - if err := MakeShared(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // mount the shared directory to a target - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // next, make the target slave - if err := MakeSlave(targetDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() - - // mount in an outside path to a mounted path inside the _source_ - if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(sourceDir, "a")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_ show in the _target_ - if _, err := os.Stat(outside1CheckPath); err != nil { - t.Fatal(err) - } - - // next mount outside2Dir into the _target_ - if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(path.Join(targetDir, "b")); err != nil { - t.Fatal(err) - } - }() - - // check that this file _does_not_ show in the _source_ - if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not be visible, but is", outside2CheckPath) - } -} - -func TestSubtreeUnbindable(t *testing.T) { - tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmp) - - var ( - sourceDir = path.Join(tmp, "source") - targetDir = path.Join(tmp, "target") - ) - if err := os.MkdirAll(sourceDir, 0777); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(targetDir, 0777); err != nil { - t.Fatal(err) - } - - // next, make the source unbindable - if err := MakeUnbindable(sourceDir); err != nil { - t.Fatal(err) - } - defer func() { - if err := Unmount(sourceDir); err != nil { - t.Fatal(err) - } - }() - - // then attempt to mount it to target. It should fail - if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil && err != syscall.EINVAL { - t.Fatal(err) - } else if err == nil { - t.Fatalf("%q should not have been bindable", sourceDir) - } - defer func() { - if err := Unmount(targetDir); err != nil { - t.Fatal(err) - } - }() -} - -func createFile(path string) error { - f, err := os.Create(path) - if err != nil { - return err - } - f.WriteString("hello world!") - return f.Close() -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go deleted file mode 100644 index a248350223a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/filters/parse_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package filters - -import ( - "sort" - "testing" -) - -func TestParseArgs(t *testing.T) { - // equivalent of `docker ps -f 'created=today' -f 'image.name=ubuntu*' -f 'image.name=*untu'` - flagArgs := []string{ - "created=today", - "image.name=ubuntu*", - "image.name=*untu", - } - var ( - args = Args{} - err error - ) - for i := range flagArgs { - args, err = ParseFlag(flagArgs[i], args) - if err != nil { - t.Errorf("failed to parse %s: %s", flagArgs[i], err) - } - } - if len(args["created"]) != 1 { - t.Errorf("failed to set this arg") - } - if len(args["image.name"]) != 2 { - t.Errorf("the args should have collapsed") - } -} - -func TestParam(t *testing.T) { - a := Args{ - "created": []string{"today"}, - "image.name": []string{"ubuntu*", "*untu"}, - } - - v, err := ToParam(a) - if err != nil { - t.Errorf("failed to marshal the filters: %s", err) - } - v1, err := FromParam(v) - if err != nil { - t.Errorf("%s", err) - } - for key, vals := range v1 { - if _, ok := a[key]; !ok { - t.Errorf("could not find key %s in original set", key) - } - sort.Strings(vals) - sort.Strings(a[key]) - if len(vals) != len(a[key]) { - t.Errorf("value lengths ought to match") - continue - } - for i := range vals { - if vals[i] != a[key][i] { - t.Errorf("expected %s, but got %s", a[key][i], vals[i]) - } - } - } -} - -func TestEmpty(t *testing.T) { - a := Args{} - v, err := ToParam(a) - if err != nil { - t.Errorf("failed to marshal the filters: %s", err) - } - v1, err := FromParam(v) - if err != nil { - t.Errorf("%s", err) - } - if len(a) != len(v1) { - t.Errorf("these should both be empty sets") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go deleted file mode 100644 index e211a63b7d5..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package kernel - -import ( - "testing" -) - -func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) { - var ( - a *KernelVersionInfo - ) - a, _ = ParseRelease(release) - - if r := CompareKernelVersion(a, b); r != result { - t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result) - } - if a.Flavor != b.Flavor { - t.Fatalf("Unexpected parsed kernel flavor. Found %s, expected %s", a.Flavor, b.Flavor) - } -} - -func TestParseRelease(t *testing.T) { - assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0) - assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) - assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) - assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "-19-generic"}, 0) - assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8, Flavor: "tag"}, 0) - assertParseRelease(t, "3.12-1-amd64", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 0, Flavor: "-1-amd64"}, 0) -} - -func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) { - if r := CompareKernelVersion(a, b); r != result { - t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result) - } -} - -func TestCompareKernelVersion(t *testing.T) { - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 0) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - -1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 0) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - 1) - assertKernelVersion(t, - &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20}, - &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, - -1) -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go deleted file mode 100644 index b7d54cbb1c1..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package operatingsystem - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" -) - -func TestGetOperatingSystem(t *testing.T) { - var ( - backup = etcOsRelease - ubuntuTrusty = []byte(`NAME="Ubuntu" -VERSION="14.04, Trusty Tahr" -ID=ubuntu -ID_LIKE=debian -PRETTY_NAME="Ubuntu 14.04 LTS" -VERSION_ID="14.04" -HOME_URL="http://www.ubuntu.com/" -SUPPORT_URL="http://help.ubuntu.com/" -BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) - gentoo = []byte(`NAME=Gentoo -ID=gentoo -PRETTY_NAME="Gentoo/Linux" -ANSI_COLOR="1;32" -HOME_URL="http://www.gentoo.org/" -SUPPORT_URL="http://www.gentoo.org/main/en/support.xml" -BUG_REPORT_URL="https://bugs.gentoo.org/" -`) - noPrettyName = []byte(`NAME="Ubuntu" -VERSION="14.04, Trusty Tahr" -ID=ubuntu -ID_LIKE=debian -VERSION_ID="14.04" -HOME_URL="http://www.ubuntu.com/" -SUPPORT_URL="http://help.ubuntu.com/" -BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) - ) - - dir := os.TempDir() - etcOsRelease = filepath.Join(dir, "etcOsRelease") - - defer func() { - os.Remove(etcOsRelease) - etcOsRelease = backup - }() - - for expect, osRelease := range map[string][]byte{ - "Ubuntu 14.04 LTS": ubuntuTrusty, - "Gentoo/Linux": gentoo, - "": noPrettyName, - } { - if err := ioutil.WriteFile(etcOsRelease, osRelease, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", etcOsRelease, err) - } - s, err := GetOperatingSystem() - if s != expect { - if expect == "" { - t.Fatalf("Expected error 'PRETTY_NAME not found', but got %v", err) - } else { - t.Fatalf("Expected '%s', but got '%s'. Err=%v", expect, s, err) - } - } - } -} - -func TestIsContainerized(t *testing.T) { - var ( - backup = proc1Cgroup - nonContainerizedProc1Cgroup = []byte(`14:name=systemd:/ -13:hugetlb:/ -12:net_prio:/ -11:perf_event:/ -10:bfqio:/ -9:blkio:/ -8:net_cls:/ -7:freezer:/ -6:devices:/ -5:memory:/ -4:cpuacct:/ -3:cpu:/ -2:cpuset:/ -`) - containerizedProc1Cgroup = []byte(`9:perf_event:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -8:blkio:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -7:net_cls:/ -6:freezer:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -5:devices:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -4:memory:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -3:cpuacct:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -2:cpu:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d -1:cpuset:/`) - ) - - dir := os.TempDir() - proc1Cgroup = filepath.Join(dir, "proc1Cgroup") - - defer func() { - os.Remove(proc1Cgroup) - proc1Cgroup = backup - }() - - if err := ioutil.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroup, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) - } - inContainer, err := IsContainerized() - if err != nil { - t.Fatal(err) - } - if inContainer { - t.Fatal("Wrongly assuming containerized") - } - - if err := ioutil.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0600); err != nil { - t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) - } - inContainer, err = IsContainerized() - if err != nil { - t.Fatal(err) - } - if !inContainer { - t.Fatal("Wrongly assuming non-containerized") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go deleted file mode 100644 index 89f4ae023ae..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/parsers/parsers_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package parsers - -import ( - "strings" - "testing" -) - -func TestParseHost(t *testing.T) { - var ( - defaultHttpHost = "127.0.0.1" - defaultUnix = "/var/run/docker.sock" - ) - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.0"); err == nil { - t.Errorf("tcp 0.0.0.0 address expected error return, but err == nil, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://"); err == nil { - t.Errorf("default tcp:// address expected error return, but err == nil, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.1:5555"); err != nil || addr != "tcp://0.0.0.1:5555" { - t.Errorf("0.0.0.1:5555 -> expected tcp://0.0.0.1:5555, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, ":6666"); err != nil || addr != "tcp://127.0.0.1:6666" { - t.Errorf(":6666 -> expected tcp://127.0.0.1:6666, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" { - t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" { - t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" { - t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix://"); err != nil || addr != "unix:///var/run/docker.sock" { - t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1"); err == nil { - t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr) - } - if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1:2375"); err == nil { - t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr) - } -} - -func TestParseRepositoryTag(t *testing.T) { - if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "root" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "root", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("user/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "user/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "user/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("url:5000/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "url:5000/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "url:5000/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } -} - -func TestParsePortMapping(t *testing.T) { - data, err := PartParser("ip:public:private", "192.168.1.1:80:8080") - if err != nil { - t.Fatal(err) - } - - if len(data) != 3 { - t.FailNow() - } - if data["ip"] != "192.168.1.1" { - t.Fail() - } - if data["public"] != "80" { - t.Fail() - } - if data["private"] != "8080" { - t.Fail() - } -} - -func TestParsePortRange(t *testing.T) { - if start, end, err := ParsePortRange("8000-8080"); err != nil || start != 8000 || end != 8080 { - t.Fatalf("Error: %s or Expecting {start,end} values {8000,8080} but found {%d,%d}.", err, start, end) - } -} - -func TestParsePortRangeIncorrectRange(t *testing.T) { - if _, _, err := ParsePortRange("9000-8080"); err == nil || !strings.Contains(err.Error(), "Invalid range specified for the Port") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectEndRange(t *testing.T) { - if _, _, err := ParsePortRange("8000-a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("8000-30a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectStartRange(t *testing.T) { - if _, _, err := ParsePortRange("a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("30a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParseLink(t *testing.T) { - name, alias, err := ParseLink("name:alias") - if err != nil { - t.Fatalf("Expected not to error out on a valid name:alias format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "alias" { - t.Fatalf("Link alias should have been alias, got %s instead", alias) - } - // short format definition - name, alias, err = ParseLink("name") - if err != nil { - t.Fatalf("Expected not to error out on a valid name only format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "name" { - t.Fatalf("Link alias should have been name, got %s instead", alias) - } - // empty string link definition is not allowed - if _, _, err := ParseLink(""); err == nil || !strings.Contains(err.Error(), "empty string specified for links") { - t.Fatalf("Expected error 'empty string specified for links' but got: %v", err) - } - // more than two colons are not allowed - if _, _, err := ParseLink("link:alias:wrong"); err == nil || !strings.Contains(err.Error(), "bad format for links: link:alias:wrong") { - t.Fatalf("Expected error 'bad format for links: link:alias:wrong' but got: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows_test.go deleted file mode 100644 index edb5d6f6612..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/console_windows_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// +build windows - -package winconsole - -import ( - "fmt" - "testing" -) - -func helpsTestParseInt16OrDefault(t *testing.T, expectedValue int16, shouldFail bool, input string, defaultValue int16, format string, args ...string) { - value, err := parseInt16OrDefault(input, defaultValue) - if nil != err && !shouldFail { - t.Errorf("Unexpected error returned %v", err) - t.Errorf(format, args) - } - if nil == err && shouldFail { - t.Errorf("Should have failed as expected\n\tReturned value = %d", value) - t.Errorf(format, args) - } - if expectedValue != value { - t.Errorf("The value returned does not match expected\n\tExpected:%v\n\t:Actual%v", expectedValue, value) - t.Errorf(format, args) - } -} - -func TestParseInt16OrDefault(t *testing.T) { - // empty string - helpsTestParseInt16OrDefault(t, 0, false, "", 0, "Empty string returns default") - helpsTestParseInt16OrDefault(t, 2, false, "", 2, "Empty string returns default") - - // normal case - helpsTestParseInt16OrDefault(t, 0, false, "0", 0, "0 handled correctly") - helpsTestParseInt16OrDefault(t, 111, false, "111", 2, "Normal") - helpsTestParseInt16OrDefault(t, 111, false, "+111", 2, "+N") - helpsTestParseInt16OrDefault(t, -111, false, "-111", 2, "-N") - helpsTestParseInt16OrDefault(t, 0, false, "+0", 11, "+0") - helpsTestParseInt16OrDefault(t, 0, false, "-0", 12, "-0") - - // ill formed strings - helpsTestParseInt16OrDefault(t, 0, true, "abc", 0, "Invalid string") - helpsTestParseInt16OrDefault(t, 42, true, "+= 23", 42, "Invalid string") - helpsTestParseInt16OrDefault(t, 42, true, "123.45", 42, "float like") - -} - -func helpsTestGetNumberOfChars(t *testing.T, expected uint32, fromCoord COORD, toCoord COORD, screenSize COORD, format string, args ...interface{}) { - actual := getNumberOfChars(fromCoord, toCoord, screenSize) - mesg := fmt.Sprintf(format, args) - assertTrue(t, expected == actual, fmt.Sprintf("%s Expected=%d, Actual=%d, Parameters = { fromCoord=%+v, toCoord=%+v, screenSize=%+v", mesg, expected, actual, fromCoord, toCoord, screenSize)) -} - -func TestGetNumberOfChars(t *testing.T) { - // Note: The columns and lines are 0 based - // Also that interval is "inclusive" means will have both start and end chars - // This test only tests the number opf characters being written - - // all four corners - maxWindow := COORD{X: 80, Y: 50} - leftTop := COORD{X: 0, Y: 0} - rightTop := COORD{X: 79, Y: 0} - leftBottom := COORD{X: 0, Y: 49} - rightBottom := COORD{X: 79, Y: 49} - - // same position - helpsTestGetNumberOfChars(t, 1, COORD{X: 1, Y: 14}, COORD{X: 1, Y: 14}, COORD{X: 80, Y: 50}, "Same position random line") - - // four corners - helpsTestGetNumberOfChars(t, 1, leftTop, leftTop, maxWindow, "Same position- leftTop") - helpsTestGetNumberOfChars(t, 1, rightTop, rightTop, maxWindow, "Same position- rightTop") - helpsTestGetNumberOfChars(t, 1, leftBottom, leftBottom, maxWindow, "Same position- leftBottom") - helpsTestGetNumberOfChars(t, 1, rightBottom, rightBottom, maxWindow, "Same position- rightBottom") - - // from this char to next char on same line - helpsTestGetNumberOfChars(t, 2, COORD{X: 0, Y: 0}, COORD{X: 1, Y: 0}, maxWindow, "Next position on same line") - helpsTestGetNumberOfChars(t, 2, COORD{X: 1, Y: 14}, COORD{X: 2, Y: 14}, maxWindow, "Next position on same line") - - // from this char to next 10 chars on same line - helpsTestGetNumberOfChars(t, 11, COORD{X: 0, Y: 0}, COORD{X: 10, Y: 0}, maxWindow, "Next position on same line") - helpsTestGetNumberOfChars(t, 11, COORD{X: 1, Y: 14}, COORD{X: 11, Y: 14}, maxWindow, "Next position on same line") - - helpsTestGetNumberOfChars(t, 5, COORD{X: 3, Y: 11}, COORD{X: 7, Y: 11}, maxWindow, "To and from on same line") - - helpsTestGetNumberOfChars(t, 8, COORD{X: 0, Y: 34}, COORD{X: 7, Y: 34}, maxWindow, "Start of line to middle") - helpsTestGetNumberOfChars(t, 4, COORD{X: 76, Y: 34}, COORD{X: 79, Y: 34}, maxWindow, "Middle to end of line") - - // multiple lines - 1 - helpsTestGetNumberOfChars(t, 81, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 1}, maxWindow, "one line below same X") - helpsTestGetNumberOfChars(t, 81, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 11}, maxWindow, "one line below same X") - - // multiple lines - 2 - helpsTestGetNumberOfChars(t, 161, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 2}, maxWindow, "one line below same X") - helpsTestGetNumberOfChars(t, 161, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 12}, maxWindow, "one line below same X") - - // multiple lines - 3 - helpsTestGetNumberOfChars(t, 241, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 3}, maxWindow, "one line below same X") - helpsTestGetNumberOfChars(t, 241, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 13}, maxWindow, "one line below same X") - - // full line - helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 0}, COORD{X: 79, Y: 0}, maxWindow, "Full line - first") - helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 23}, COORD{X: 79, Y: 23}, maxWindow, "Full line - random") - helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 49}, COORD{X: 79, Y: 49}, maxWindow, "Full line - last") - - // full screen - helpsTestGetNumberOfChars(t, 80*50, leftTop, rightBottom, maxWindow, "full screen") - - helpsTestGetNumberOfChars(t, 80*50-1, COORD{X: 1, Y: 0}, rightBottom, maxWindow, "dropping first char to, end of screen") - helpsTestGetNumberOfChars(t, 80*50-2, COORD{X: 2, Y: 0}, rightBottom, maxWindow, "dropping first two char to, end of screen") - - helpsTestGetNumberOfChars(t, 80*50-1, leftTop, COORD{X: 78, Y: 49}, maxWindow, "from start of screen, till last char-1") - helpsTestGetNumberOfChars(t, 80*50-2, leftTop, COORD{X: 77, Y: 49}, maxWindow, "from start of screen, till last char-2") - - helpsTestGetNumberOfChars(t, 80*50-5, COORD{X: 4, Y: 0}, COORD{X: 78, Y: 49}, COORD{X: 80, Y: 50}, "from start of screen+4, till last char-1") - helpsTestGetNumberOfChars(t, 80*50-6, COORD{X: 4, Y: 0}, COORD{X: 77, Y: 49}, COORD{X: 80, Y: 50}, "from start of screen+4, till last char-2") -} - -var allForeground = []int16{ - ANSI_FOREGROUND_BLACK, - ANSI_FOREGROUND_RED, - ANSI_FOREGROUND_GREEN, - ANSI_FOREGROUND_YELLOW, - ANSI_FOREGROUND_BLUE, - ANSI_FOREGROUND_MAGENTA, - ANSI_FOREGROUND_CYAN, - ANSI_FOREGROUND_WHITE, - ANSI_FOREGROUND_DEFAULT, -} -var allBackground = []int16{ - ANSI_BACKGROUND_BLACK, - ANSI_BACKGROUND_RED, - ANSI_BACKGROUND_GREEN, - ANSI_BACKGROUND_YELLOW, - ANSI_BACKGROUND_BLUE, - ANSI_BACKGROUND_MAGENTA, - ANSI_BACKGROUND_CYAN, - ANSI_BACKGROUND_WHITE, - ANSI_BACKGROUND_DEFAULT, -} - -func maskForeground(flag WORD) WORD { - return flag & FOREGROUND_MASK_UNSET -} - -func onlyForeground(flag WORD) WORD { - return flag & FOREGROUND_MASK_SET -} - -func maskBackground(flag WORD) WORD { - return flag & BACKGROUND_MASK_UNSET -} - -func onlyBackground(flag WORD) WORD { - return flag & BACKGROUND_MASK_SET -} - -func helpsTestGetWindowsTextAttributeForAnsiValue(t *testing.T, oldValue WORD /*, expected WORD*/, ansi int16, onlyMask WORD, restMask WORD) WORD { - actual, err := getWindowsTextAttributeForAnsiValue(oldValue, FOREGROUND_MASK_SET, ansi) - assertTrue(t, nil == err, "Should be no error") - // assert that other bits are not affected - if 0 != oldValue { - assertTrue(t, (actual&restMask) == (oldValue&restMask), "The operation should not have affected other bits actual=%X oldValue=%X ansi=%d", actual, oldValue, ansi) - } - return actual -} - -func TestBackgroundForAnsiValue(t *testing.T) { - // Check that nothing else changes - // background changes - for _, state1 := range allBackground { - for _, state2 := range allBackground { - flag := WORD(0) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - } - } - // cummulative bcakground changes - for _, state1 := range allBackground { - flag := WORD(0) - for _, state2 := range allBackground { - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - } - } - // change background after foreground - for _, state1 := range allForeground { - for _, state2 := range allBackground { - flag := WORD(0) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - } - } - // change background after change cumulative - for _, state1 := range allForeground { - flag := WORD(0) - for _, state2 := range allBackground { - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - } - } -} - -func TestForegroundForAnsiValue(t *testing.T) { - // Check that nothing else changes - for _, state1 := range allForeground { - for _, state2 := range allForeground { - flag := WORD(0) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - } - } - - for _, state1 := range allForeground { - flag := WORD(0) - for _, state2 := range allForeground { - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - } - } - for _, state1 := range allBackground { - for _, state2 := range allForeground { - flag := WORD(0) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - } - } - for _, state1 := range allBackground { - flag := WORD(0) - for _, state2 := range allForeground { - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) - flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator_test.go deleted file mode 100644 index 94104ff51f2..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/term/winconsole/term_emulator_test.go +++ /dev/null @@ -1,388 +0,0 @@ -package winconsole - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "testing" -) - -const ( - WRITE_OPERATION = iota - COMMAND_OPERATION = iota -) - -var languages = []string{ - "Български", - "Català", - "Čeština", - "Ελληνικά", - "Español", - "Esperanto", - "Euskara", - "Français", - "Galego", - "한국어", - "ქართული", - "Latviešu", - "Lietuvių", - "Magyar", - "Nederlands", - "日本語", - "Norsk bokmål", - "Norsk nynorsk", - "Polski", - "Português", - "Română", - "Русский", - "Slovenčina", - "Slovenščina", - "Српски", - "српскохрватски", - "Suomi", - "Svenska", - "ไทย", - "Tiếng Việt", - "Türkçe", - "Українська", - "中文", -} - -// Mock terminal handler object -type mockTerminal struct { - OutputCommandSequence []terminalOperation -} - -// Used for recording the callback data -type terminalOperation struct { - Operation int - Data []byte - Str string -} - -func (mt *mockTerminal) record(operation int, data []byte) { - op := terminalOperation{ - Operation: operation, - Data: make([]byte, len(data)), - } - copy(op.Data, data) - op.Str = string(op.Data) - mt.OutputCommandSequence = append(mt.OutputCommandSequence, op) -} - -func (mt *mockTerminal) HandleOutputCommand(fd uintptr, command []byte) (n int, err error) { - mt.record(COMMAND_OPERATION, command) - return len(command), nil -} - -func (mt *mockTerminal) HandleInputSequence(fd uintptr, command []byte) (n int, err error) { - return 0, nil -} - -func (mt *mockTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) { - mt.record(WRITE_OPERATION, p) - return len(p), nil -} - -func (mt *mockTerminal) ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) { - return len(p), nil -} - -func assertTrue(t *testing.T, cond bool, format string, args ...interface{}) { - if !cond { - t.Errorf(format, args...) - } -} - -// reflect.DeepEqual does not provide detailed information as to what excatly failed. -func assertBytesEqual(t *testing.T, expected, actual []byte, format string, args ...interface{}) { - match := true - mismatchIndex := 0 - if len(expected) == len(actual) { - for i := 0; i < len(expected); i++ { - if expected[i] != actual[i] { - match = false - mismatchIndex = i - break - } - } - } else { - match = false - t.Errorf("Lengths don't match Expected=%d Actual=%d", len(expected), len(actual)) - } - if !match { - t.Errorf("Mismatch at index %d ", mismatchIndex) - t.Errorf("\tActual String = %s", string(actual)) - t.Errorf("\tExpected String = %s", string(expected)) - t.Errorf("\tActual = %v", actual) - t.Errorf("\tExpected = %v", expected) - t.Errorf(format, args) - } -} - -// Just to make sure :) -func TestAssertEqualBytes(t *testing.T) { - data := []byte{9, 9, 1, 1, 1, 9, 9} - assertBytesEqual(t, data, data, "Self") - assertBytesEqual(t, data[1:4], data[1:4], "Self") - assertBytesEqual(t, []byte{1, 1}, []byte{1, 1}, "Simple match") - assertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 2, 3}, "content mismatch") - assertBytesEqual(t, []byte{1, 1, 1}, data[2:5], "slice match") -} - -/* -func TestAssertEqualBytesNegative(t *testing.T) { - AssertBytesEqual(t, []byte{1, 1}, []byte{1}, "Length mismatch") - AssertBytesEqual(t, []byte{1, 1}, []byte{1}, "Length mismatch") - AssertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 1, 1}, "content mismatch") -}*/ - -// Checks that the calls received -func assertHandlerOutput(t *testing.T, mock *mockTerminal, plainText string, commands ...string) { - text := make([]byte, 0, 3*len(plainText)) - cmdIndex := 0 - for opIndex := 0; opIndex < len(mock.OutputCommandSequence); opIndex++ { - op := mock.OutputCommandSequence[opIndex] - if op.Operation == WRITE_OPERATION { - t.Logf("\nThe data is[%d] == %s", opIndex, string(op.Data)) - text = append(text[:], op.Data...) - } else { - assertTrue(t, mock.OutputCommandSequence[opIndex].Operation == COMMAND_OPERATION, "Operation should be command : %s", fmt.Sprintf("%+v", mock)) - assertBytesEqual(t, StringToBytes(commands[cmdIndex]), mock.OutputCommandSequence[opIndex].Data, "Command data should match") - cmdIndex++ - } - } - assertBytesEqual(t, StringToBytes(plainText), text, "Command data should match %#v", mock) -} - -func StringToBytes(str string) []byte { - bytes := make([]byte, len(str)) - copy(bytes[:], str) - return bytes -} - -func TestParseAnsiCommand(t *testing.T) { - // Note: if the parameter does not exist then the empty value is returned - - c := parseAnsiCommand(StringToBytes("\x1Bm")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "" == c.getParam(0), "should return empty string") - assertTrue(t, "" == c.getParam(1), "should return empty string") - - // Escape sequence - ESC[ - c = parseAnsiCommand(StringToBytes("\x1B[m")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "" == c.getParam(0), "should return empty string") - assertTrue(t, "" == c.getParam(1), "should return empty string") - - // Escape sequence With empty parameters- ESC[ - c = parseAnsiCommand(StringToBytes("\x1B[;m")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "" == c.getParam(0), "should return empty string") - assertTrue(t, "" == c.getParam(1), "should return empty string") - assertTrue(t, "" == c.getParam(2), "should return empty string") - - // Escape sequence With empty muliple parameters- ESC[ - c = parseAnsiCommand(StringToBytes("\x1B[;;m")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "" == c.getParam(0), "") - assertTrue(t, "" == c.getParam(1), "") - assertTrue(t, "" == c.getParam(2), "") - - // Escape sequence With muliple parameters- ESC[ - c = parseAnsiCommand(StringToBytes("\x1B[1;2;3m")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "1" == c.getParam(0), "") - assertTrue(t, "2" == c.getParam(1), "") - assertTrue(t, "3" == c.getParam(2), "") - - // Escape sequence With muliple parameters- some missing - c = parseAnsiCommand(StringToBytes("\x1B[1;;3;;;6m")) - assertTrue(t, c.Command == "m", "Command should be m") - assertTrue(t, "1" == c.getParam(0), "") - assertTrue(t, "" == c.getParam(1), "") - assertTrue(t, "3" == c.getParam(2), "") - assertTrue(t, "" == c.getParam(3), "") - assertTrue(t, "" == c.getParam(4), "") - assertTrue(t, "6" == c.getParam(5), "") -} - -func newBufferedMockTerm() (stdOut io.Writer, stdErr io.Writer, stdIn io.ReadCloser, mock *mockTerminal) { - var input bytes.Buffer - var output bytes.Buffer - var err bytes.Buffer - - mock = &mockTerminal{ - OutputCommandSequence: make([]terminalOperation, 0, 256), - } - - stdOut = &terminalWriter{ - wrappedWriter: &output, - emulator: mock, - command: make([]byte, 0, 256), - } - stdErr = &terminalWriter{ - wrappedWriter: &err, - emulator: mock, - command: make([]byte, 0, 256), - } - stdIn = &terminalReader{ - wrappedReader: ioutil.NopCloser(&input), - emulator: mock, - command: make([]byte, 0, 256), - } - - return -} - -func TestOutputSimple(t *testing.T) { - stdOut, _, _, mock := newBufferedMockTerm() - - stdOut.Write(StringToBytes("Hello world")) - stdOut.Write(StringToBytes("\x1BmHello again")) - - assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) - assertBytesEqual(t, StringToBytes("\x1Bm"), mock.OutputCommandSequence[1].Data, "Command data should match") - - assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[2].Data, "Write data should match") -} - -func TestOutputSplitCommand(t *testing.T) { - stdOut, _, _, mock := newBufferedMockTerm() - - stdOut.Write(StringToBytes("Hello world\x1B[1;2;3")) - stdOut.Write(StringToBytes("mHello again")) - - assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) - assertBytesEqual(t, StringToBytes("\x1B[1;2;3m"), mock.OutputCommandSequence[1].Data, "Command data should match") - - assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[2].Data, "Write data should match") -} - -func TestOutputMultipleCommands(t *testing.T) { - stdOut, _, _, mock := newBufferedMockTerm() - - stdOut.Write(StringToBytes("Hello world")) - stdOut.Write(StringToBytes("\x1B[1;2;3m")) - stdOut.Write(StringToBytes("\x1B[J")) - stdOut.Write(StringToBytes("Hello again")) - - assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) - assertBytesEqual(t, StringToBytes("\x1B[1;2;3m"), mock.OutputCommandSequence[1].Data, "Command data should match") - - assertTrue(t, mock.OutputCommandSequence[2].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) - assertBytesEqual(t, StringToBytes("\x1B[J"), mock.OutputCommandSequence[2].Data, "Command data should match") - - assertTrue(t, mock.OutputCommandSequence[3].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[3].Data, "Write data should match") -} - -// Splits the given data in two chunks , makes two writes and checks the split data is parsed correctly -// checks output write/command is passed to handler correctly -func helpsTestOutputSplitChunksAtIndex(t *testing.T, i int, data []byte) { - t.Logf("\ni=%d", i) - stdOut, _, _, mock := newBufferedMockTerm() - - t.Logf("\nWriting chunk[0] == %s", string(data[:i])) - t.Logf("\nWriting chunk[1] == %s", string(data[i:])) - stdOut.Write(data[:i]) - stdOut.Write(data[i:]) - - assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, data[:i], mock.OutputCommandSequence[0].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[1].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, data[i:], mock.OutputCommandSequence[1].Data, "Write data should match") -} - -// Splits the given data in three chunks , makes three writes and checks the split data is parsed correctly -// checks output write/command is passed to handler correctly -func helpsTestOutputSplitThreeChunksAtIndex(t *testing.T, data []byte, i int, j int) { - stdOut, _, _, mock := newBufferedMockTerm() - - t.Logf("\nWriting chunk[0] == %s", string(data[:i])) - t.Logf("\nWriting chunk[1] == %s", string(data[i:j])) - t.Logf("\nWriting chunk[2] == %s", string(data[j:])) - stdOut.Write(data[:i]) - stdOut.Write(data[i:j]) - stdOut.Write(data[j:]) - - assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, data[:i], mock.OutputCommandSequence[0].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[1].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, data[i:j], mock.OutputCommandSequence[1].Data, "Write data should match") - - assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) - assertBytesEqual(t, data[j:], mock.OutputCommandSequence[2].Data, "Write data should match") -} - -// Splits the output into two parts and tests all such possible pairs -func helpsTestOutputSplitChunks(t *testing.T, data []byte) { - for i := 1; i < len(data)-1; i++ { - helpsTestOutputSplitChunksAtIndex(t, i, data) - } -} - -// Splits the output in three parts and tests all such possible triples -func helpsTestOutputSplitThreeChunks(t *testing.T, data []byte) { - for i := 1; i < len(data)-2; i++ { - for j := i + 1; j < len(data)-1; j++ { - helpsTestOutputSplitThreeChunksAtIndex(t, data, i, j) - } - } -} - -func helpsTestOutputSplitCommandsAtIndex(t *testing.T, data []byte, i int, plainText string, commands ...string) { - t.Logf("\ni=%d", i) - stdOut, _, _, mock := newBufferedMockTerm() - - stdOut.Write(data[:i]) - stdOut.Write(data[i:]) - assertHandlerOutput(t, mock, plainText, commands...) -} - -func helpsTestOutputSplitCommands(t *testing.T, data []byte, plainText string, commands ...string) { - for i := 1; i < len(data)-1; i++ { - helpsTestOutputSplitCommandsAtIndex(t, data, i, plainText, commands...) - } -} - -func injectCommandAt(data string, i int, command string) string { - retValue := make([]byte, len(data)+len(command)+4) - retValue = append(retValue, data[:i]...) - retValue = append(retValue, data[i:]...) - return string(retValue) -} - -func TestOutputSplitChunks(t *testing.T) { - data := StringToBytes("qwertyuiopasdfghjklzxcvbnm") - helpsTestOutputSplitChunks(t, data) - helpsTestOutputSplitChunks(t, StringToBytes("BBBBB")) - helpsTestOutputSplitThreeChunks(t, StringToBytes("ABCDE")) -} - -func TestOutputSplitChunksIncludingCommands(t *testing.T) { - helpsTestOutputSplitCommands(t, StringToBytes("Hello world.\x1B[mHello again."), "Hello world.Hello again.", "\x1B[m") - helpsTestOutputSplitCommandsAtIndex(t, StringToBytes("Hello world.\x1B[mHello again."), 2, "Hello world.Hello again.", "\x1B[m") -} - -func TestSplitChunkUnicode(t *testing.T) { - for _, l := range languages { - data := StringToBytes(l) - helpsTestOutputSplitChunks(t, data) - helpsTestOutputSplitThreeChunks(t, data) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/json_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/json_test.go deleted file mode 100644 index 1ff33317975..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/json_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package timeutils - -import ( - "testing" - "time" -) - -// Testing to ensure 'year' fields is between 0 and 9999 -func TestFastMarshalJSONWithInvalidDate(t *testing.T) { - aTime := time.Date(-1, 1, 1, 0, 0, 0, 0, time.Local) - json, err := FastMarshalJSON(aTime) - if err == nil { - t.Fatalf("FastMarshalJSON should throw an error, but was '%v'", json) - } - anotherTime := time.Date(10000, 1, 1, 0, 0, 0, 0, time.Local) - json, err = FastMarshalJSON(anotherTime) - if err == nil { - t.Fatalf("FastMarshalJSON should throw an error, but was '%v'", json) - } - -} - -func TestFastMarshalJSON(t *testing.T) { - aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC) - json, err := FastMarshalJSON(aTime) - if err != nil { - t.Fatal(err) - } - expected := "\"2015-05-29T11:01:02.000000003Z\"" - if json != expected { - t.Fatalf("Expected %v, got %v", expected, json) - } - - location, err := time.LoadLocation("Europe/Paris") - if err != nil { - t.Fatal(err) - } - aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location) - json, err = FastMarshalJSON(aTime) - if err != nil { - t.Fatal(err) - } - expected = "\"2015-05-29T11:01:02.000000003+02:00\"" - if json != expected { - t.Fatalf("Expected %v, got %v", expected, json) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/utils_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/utils_test.go deleted file mode 100644 index f71dcb5310f..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/timeutils/utils_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package timeutils - -import ( - "fmt" - "testing" - "time" -) - -func TestGetTimestamp(t *testing.T) { - now := time.Now() - cases := []struct{ in, expected string }{ - {"0", "-62167305600"}, // 0 gets parsed year 0 - - // Partial RFC3339 strings get parsed with second precision - {"2006-01-02T15:04:05.999999999+07:00", "1136189045"}, - {"2006-01-02T15:04:05.999999999Z", "1136214245"}, - {"2006-01-02T15:04:05.999999999", "1136214245"}, - {"2006-01-02T15:04:05", "1136214245"}, - {"2006-01-02T15:04", "1136214240"}, - {"2006-01-02T15", "1136214000"}, - {"2006-01-02T", "1136160000"}, - {"2006-01-02", "1136160000"}, - {"2006", "1136073600"}, - {"2015-05-13T20:39:09Z", "1431549549"}, - - // unix timestamps returned as is - {"1136073600", "1136073600"}, - - // Durations - {"1m", fmt.Sprintf("%d", now.Add(-1*time.Minute).Unix())}, - {"1.5h", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())}, - {"1h30m", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())}, - - // String fallback - {"invalid", "invalid"}, - } - - for _, c := range cases { - o := GetTimestamp(c.in, now) - if o != c.expected { - t.Fatalf("wrong value for '%s'. expected:'%s' got:'%s'", c.in, c.expected, o) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/units/duration_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/units/duration_test.go deleted file mode 100644 index fcfb6b7bbd7..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/units/duration_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package units - -import ( - "testing" - "time" -) - -func TestHumanDuration(t *testing.T) { - // Useful duration abstractions - day := 24 * time.Hour - week := 7 * day - month := 30 * day - year := 365 * day - - assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) - assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) - assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) - assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) - assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) - assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) - assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) - assertEquals(t, "2 days", HumanDuration(2*day)) - assertEquals(t, "7 days", HumanDuration(7*day)) - assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) - assertEquals(t, "2 weeks", HumanDuration(2*week)) - assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) - assertEquals(t, "3 weeks", HumanDuration(3*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) - assertEquals(t, "4 weeks", HumanDuration(1*month)) - assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) - assertEquals(t, "8 weeks", HumanDuration(2*month)) - assertEquals(t, "3 months", HumanDuration(3*month+1*week)) - assertEquals(t, "5 months", HumanDuration(5*month+2*week)) - assertEquals(t, "13 months", HumanDuration(13*month)) - assertEquals(t, "23 months", HumanDuration(23*month)) - assertEquals(t, "24 months", HumanDuration(24*month)) - assertEquals(t, "2 years", HumanDuration(24*month+2*week)) - assertEquals(t, "3 years", HumanDuration(3*year+2*month)) -} diff --git a/Godeps/_workspace/src/github.com/docker/docker/pkg/units/size_test.go b/Godeps/_workspace/src/github.com/docker/docker/pkg/units/size_test.go deleted file mode 100644 index 67c3b81e6b4..00000000000 --- a/Godeps/_workspace/src/github.com/docker/docker/pkg/units/size_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package units - -import ( - "reflect" - "runtime" - "strings" - "testing" -) - -func TestBytesSize(t *testing.T) { - assertEquals(t, "1 KiB", BytesSize(1024)) - assertEquals(t, "1 MiB", BytesSize(1024*1024)) - assertEquals(t, "1 MiB", BytesSize(1048576)) - assertEquals(t, "2 MiB", BytesSize(2*MiB)) - assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) - assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) - assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) -} - -func TestHumanSize(t *testing.T) { - assertEquals(t, "1 kB", HumanSize(1000)) - assertEquals(t, "1.024 kB", HumanSize(1024)) - assertEquals(t, "1 MB", HumanSize(1000000)) - assertEquals(t, "1.049 MB", HumanSize(1048576)) - assertEquals(t, "2 MB", HumanSize(2*MB)) - assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) - assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) - assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) -} - -func TestFromHumanSize(t *testing.T) { - assertSuccessEquals(t, 32, FromHumanSize, "32") - assertSuccessEquals(t, 32, FromHumanSize, "32b") - assertSuccessEquals(t, 32, FromHumanSize, "32B") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") - assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") - assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") - assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") - assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") - - assertError(t, FromHumanSize, "") - assertError(t, FromHumanSize, "hello") - assertError(t, FromHumanSize, "-32") - assertError(t, FromHumanSize, "32.3") - assertError(t, FromHumanSize, " 32 ") - assertError(t, FromHumanSize, "32.3Kb") - assertError(t, FromHumanSize, "32 mb") - assertError(t, FromHumanSize, "32m b") - assertError(t, FromHumanSize, "32bm") -} - -func TestRAMInBytes(t *testing.T) { - assertSuccessEquals(t, 32, RAMInBytes, "32") - assertSuccessEquals(t, 32, RAMInBytes, "32b") - assertSuccessEquals(t, 32, RAMInBytes, "32B") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") - assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") - assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") - assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") - - assertError(t, RAMInBytes, "") - assertError(t, RAMInBytes, "hello") - assertError(t, RAMInBytes, "-32") - assertError(t, RAMInBytes, "32.3") - assertError(t, RAMInBytes, " 32 ") - assertError(t, RAMInBytes, "32.3Kb") - assertError(t, RAMInBytes, "32 mb") - assertError(t, RAMInBytes, "32m b") - assertError(t, RAMInBytes, "32bm") -} - -func assertEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - t.Errorf("Expected '%v' but got '%v'", expected, actual) - } -} - -// func that maps to the parse function signatures as testing abstraction -type parseFn func(string) (int64, error) - -// Define 'String()' for pretty-print -func (fn parseFn) String() string { - fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() - return fnName[strings.LastIndex(fnName, ".")+1:] -} - -func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { - res, err := fn(arg) - if err != nil || res != expected { - t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) - } -} - -func assertError(t *testing.T, fn parseFn, arg string) { - res, err := fn(arg) - if err == nil && res != -1 { - t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/cgroups_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/cgroups_test.go deleted file mode 100644 index e8c52938ce9..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/cgroups_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package cgroups - -import ( - "bytes" - "testing" -) - -const ( - cgroupsContents = `11:hugetlb:/ -10:perf_event:/ -9:blkio:/ -8:net_cls:/ -7:freezer:/ -6:devices:/ -5:memory:/ -4:cpuacct,cpu:/ -3:cpuset:/ -2:name=systemd:/user.slice/user-1000.slice/session-16.scope` -) - -func TestParseCgroups(t *testing.T) { - r := bytes.NewBuffer([]byte(cgroupsContents)) - _, err := ParseCgroupFile("blkio", r) - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/blkio_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/blkio_test.go deleted file mode 100644 index 38e8ede9f27..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/blkio_test.go +++ /dev/null @@ -1,473 +0,0 @@ -package fs - -import ( - "strconv" - "testing" - - "github.com/docker/libcontainer/cgroups" -) - -const ( - sectorsRecursiveContents = `8:0 1024` - serviceBytesRecursiveContents = `8:0 Read 100 -8:0 Write 200 -8:0 Sync 300 -8:0 Async 500 -8:0 Total 500 -Total 500` - servicedRecursiveContents = `8:0 Read 10 -8:0 Write 40 -8:0 Sync 20 -8:0 Async 30 -8:0 Total 50 -Total 50` - queuedRecursiveContents = `8:0 Read 1 -8:0 Write 4 -8:0 Sync 2 -8:0 Async 3 -8:0 Total 5 -Total 5` - serviceTimeRecursiveContents = `8:0 Read 173959 -8:0 Write 0 -8:0 Sync 0 -8:0 Async 173959 -8:0 Total 17395 -Total 17395` - waitTimeRecursiveContents = `8:0 Read 15571 -8:0 Write 0 -8:0 Sync 0 -8:0 Async 15571 -8:0 Total 15571` - mergedRecursiveContents = `8:0 Read 5 -8:0 Write 10 -8:0 Sync 0 -8:0 Async 0 -8:0 Total 15 -Total 15` - timeRecursiveContents = `8:0 8` - throttleServiceBytes = `8:0 Read 11030528 -8:0 Write 23 -8:0 Sync 42 -8:0 Async 11030528 -8:0 Total 11030528 -252:0 Read 11030528 -252:0 Write 23 -252:0 Sync 42 -252:0 Async 11030528 -252:0 Total 11030528 -Total 22061056` - throttleServiced = `8:0 Read 164 -8:0 Write 23 -8:0 Sync 42 -8:0 Async 164 -8:0 Total 164 -252:0 Read 164 -252:0 Write 23 -252:0 Sync 42 -252:0 Async 164 -252:0 Total 164 -Total 328` -) - -func appendBlkioStatEntry(blkioStatEntries *[]cgroups.BlkioStatEntry, major, minor, value uint64, op string) { - *blkioStatEntries = append(*blkioStatEntries, cgroups.BlkioStatEntry{Major: major, Minor: minor, Value: value, Op: op}) -} - -func TestBlkioSetWeight(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - weightBefore = 100 - weightAfter = 200 - ) - - helper.writeFileContents(map[string]string{ - "blkio.weight": strconv.Itoa(weightBefore), - }) - - helper.CgroupData.c.BlkioWeight = weightAfter - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "blkio.weight") - if err != nil { - t.Fatalf("Failed to parse blkio.weight - %s", err) - } - - if value != weightAfter { - t.Fatal("Got the wrong value, set blkio.weight failed.") - } -} - -func TestBlkioSetWeightDevice(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - - const ( - weightDeviceBefore = "8:0 400" - weightDeviceAfter = "8:0 500" - ) - - helper.writeFileContents(map[string]string{ - "blkio.weight_device": weightDeviceBefore, - }) - - helper.CgroupData.c.BlkioWeightDevice = weightDeviceAfter - blkio := &BlkioGroup{} - if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "blkio.weight_device") - if err != nil { - t.Fatalf("Failed to parse blkio.weight_device - %s", err) - } - - if value != weightDeviceAfter { - t.Fatal("Got the wrong value, set blkio.weight_device failed.") - } -} - -func TestBlkioStats(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - // Verify expected stats. - expectedStats := cgroups.BlkioStats{} - appendBlkioStatEntry(&expectedStats.SectorsRecursive, 8, 0, 1024, "") - - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 100, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 200, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 300, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Total") - - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 10, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 40, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 20, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 30, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 50, "Total") - - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 1, "Read") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 4, "Write") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 2, "Sync") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 3, "Async") - appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 5, "Total") - - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 17395, "Total") - - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Read") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Write") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Async") - appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Total") - - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 5, "Read") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 10, "Write") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Sync") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Async") - appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 15, "Total") - - appendBlkioStatEntry(&expectedStats.IoTimeRecursive, 8, 0, 8, "") - - expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) -} - -func TestBlkioStatsNoSectorsFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServiceBytesFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServicedFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoQueuedFile(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoServiceTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoWaitTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoMergedFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsNoTimeFile(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatalf("Failed unexpectedly: %s", err) - } -} - -func TestBlkioStatsUnexpectedNumberOfFields(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "8:0 Read 100 100", - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected to fail, but did not") - } -} - -func TestBlkioStatsUnexpectedFieldType(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "8:0 Read Write", - "blkio.io_serviced_recursive": servicedRecursiveContents, - "blkio.io_queued_recursive": queuedRecursiveContents, - "blkio.sectors_recursive": sectorsRecursiveContents, - "blkio.io_service_time_recursive": serviceTimeRecursiveContents, - "blkio.io_wait_time_recursive": waitTimeRecursiveContents, - "blkio.io_merged_recursive": mergedRecursiveContents, - "blkio.time_recursive": timeRecursiveContents, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected to fail, but did not") - } -} - -func TestNonCFQBlkioStats(t *testing.T) { - helper := NewCgroupTestUtil("blkio", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "blkio.io_service_bytes_recursive": "", - "blkio.io_serviced_recursive": "", - "blkio.io_queued_recursive": "", - "blkio.sectors_recursive": "", - "blkio.io_service_time_recursive": "", - "blkio.io_wait_time_recursive": "", - "blkio.io_merged_recursive": "", - "blkio.time_recursive": "", - "blkio.throttle.io_service_bytes": throttleServiceBytes, - "blkio.throttle.io_serviced": throttleServiced, - }) - - blkio := &BlkioGroup{} - actualStats := *cgroups.NewStats() - err := blkio.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - // Verify expected stats. - expectedStats := cgroups.BlkioStats{} - - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Total") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Read") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Async") - appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Total") - - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Total") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Read") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 23, "Write") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 42, "Sync") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Async") - appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Total") - - expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpu_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpu_test.go deleted file mode 100644 index bcf4ac4e8a8..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpu_test.go +++ /dev/null @@ -1,139 +0,0 @@ -package fs - -import ( - "fmt" - "strconv" - "testing" - - "github.com/docker/libcontainer/cgroups" -) - -func TestCpuSetShares(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - sharesBefore = 1024 - sharesAfter = 512 - ) - - helper.writeFileContents(map[string]string{ - "cpu.shares": strconv.Itoa(sharesBefore), - }) - - helper.CgroupData.c.CpuShares = sharesAfter - cpu := &CpuGroup{} - if err := cpu.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "cpu.shares") - if err != nil { - t.Fatalf("Failed to parse cpu.shares - %s", err) - } - - if value != sharesAfter { - t.Fatal("Got the wrong value, set cpu.shares failed.") - } -} - -func TestCpuSetBandWidth(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - quotaBefore = 8000 - quotaAfter = 5000 - periodBefore = 10000 - periodAfter = 7000 - ) - - helper.writeFileContents(map[string]string{ - "cpu.cfs_quota_us": strconv.Itoa(quotaBefore), - "cpu.cfs_period_us": strconv.Itoa(periodBefore), - }) - - helper.CgroupData.c.CpuQuota = quotaAfter - helper.CgroupData.c.CpuPeriod = periodAfter - cpu := &CpuGroup{} - if err := cpu.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - quota, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_quota_us") - if err != nil { - t.Fatalf("Failed to parse cpu.cfs_quota_us - %s", err) - } - if quota != quotaAfter { - t.Fatal("Got the wrong value, set cpu.cfs_quota_us failed.") - } - - period, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_period_us") - if err != nil { - t.Fatalf("Failed to parse cpu.cfs_period_us - %s", err) - } - if period != periodAfter { - t.Fatal("Got the wrong value, set cpu.cfs_period_us failed.") - } -} - -func TestCpuStats(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - const ( - kNrPeriods = 2000 - kNrThrottled = 200 - kThrottledTime = uint64(18446744073709551615) - ) - - cpuStatContent := fmt.Sprintf("nr_periods %d\n nr_throttled %d\n throttled_time %d\n", - kNrPeriods, kNrThrottled, kThrottledTime) - helper.writeFileContents(map[string]string{ - "cpu.stat": cpuStatContent, - }) - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - - expectedStats := cgroups.ThrottlingData{ - Periods: kNrPeriods, - ThrottledPeriods: kNrThrottled, - ThrottledTime: kThrottledTime} - - expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData) -} - -func TestNoCpuStatFile(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal("Expected not to fail, but did") - } -} - -func TestInvalidCpuStat(t *testing.T) { - helper := NewCgroupTestUtil("cpu", t) - defer helper.cleanup() - cpuStatContent := `nr_periods 2000 - nr_throttled 200 - throttled_time fortytwo` - helper.writeFileContents(map[string]string{ - "cpu.stat": cpuStatContent, - }) - - cpu := &CpuGroup{} - actualStats := *cgroups.NewStats() - err := cpu.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failed stat parsing.") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpuset_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpuset_test.go deleted file mode 100644 index 7449cdca17b..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/cpuset_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package fs - -import ( - "testing" -) - -func TestCpusetSetCpus(t *testing.T) { - helper := NewCgroupTestUtil("cpuset", t) - defer helper.cleanup() - - const ( - cpusBefore = "0" - cpusAfter = "1-3" - ) - - helper.writeFileContents(map[string]string{ - "cpuset.cpus": cpusBefore, - }) - - helper.CgroupData.c.CpusetCpus = cpusAfter - cpuset := &CpusetGroup{} - if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "cpuset.cpus") - if err != nil { - t.Fatalf("Failed to parse cpuset.cpus - %s", err) - } - - if value != cpusAfter { - t.Fatal("Got the wrong value, set cpuset.cpus failed.") - } -} - -func TestCpusetSetMems(t *testing.T) { - helper := NewCgroupTestUtil("cpuset", t) - defer helper.cleanup() - - const ( - memsBefore = "0" - memsAfter = "1" - ) - - helper.writeFileContents(map[string]string{ - "cpuset.mems": memsBefore, - }) - - helper.CgroupData.c.CpusetMems = memsAfter - cpuset := &CpusetGroup{} - if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "cpuset.mems") - if err != nil { - t.Fatalf("Failed to parse cpuset.mems - %s", err) - } - - if value != memsAfter { - t.Fatal("Got the wrong value, set cpuset.mems failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/devices_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/devices_test.go deleted file mode 100644 index 18bb1274624..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/devices_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package fs - -import ( - "testing" - - "github.com/docker/libcontainer/configs" -) - -var ( - allowedDevices = []*configs.Device{ - { - Path: "/dev/zero", - Type: 'c', - Major: 1, - Minor: 5, - Permissions: "rwm", - FileMode: 0666, - }, - } - allowedList = "c 1:5 rwm" -) - -func TestDevicesSetAllow(t *testing.T) { - helper := NewCgroupTestUtil("devices", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "devices.deny": "a", - }) - - helper.CgroupData.c.AllowAllDevices = false - helper.CgroupData.c.AllowedDevices = allowedDevices - devices := &DevicesGroup{} - if err := devices.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "devices.allow") - if err != nil { - t.Fatalf("Failed to parse devices.allow - %s", err) - } - - if value != allowedList { - t.Fatal("Got the wrong value, set devices.allow failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/freezer_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/freezer_test.go deleted file mode 100644 index 9ff1886d26f..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/freezer_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package fs - -import ( - "testing" - - "github.com/docker/libcontainer/configs" -) - -func TestFreezerSetState(t *testing.T) { - helper := NewCgroupTestUtil("freezer", t) - defer helper.cleanup() - - helper.writeFileContents(map[string]string{ - "freezer.state": string(configs.Frozen), - }) - - helper.CgroupData.c.Freezer = configs.Thawed - freezer := &FreezerGroup{} - if err := freezer.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamString(helper.CgroupPath, "freezer.state") - if err != nil { - t.Fatalf("Failed to parse freezer.state - %s", err) - } - if value != string(configs.Thawed) { - t.Fatal("Got the wrong value, set freezer.state failed.") - } -} - -func TestFreezerSetInvalidState(t *testing.T) { - helper := NewCgroupTestUtil("freezer", t) - defer helper.cleanup() - - const ( - invalidArg configs.FreezerState = "Invalid" - ) - - helper.CgroupData.c.Freezer = invalidArg - freezer := &FreezerGroup{} - if err := freezer.Set(helper.CgroupPath, helper.CgroupData.c); err == nil { - t.Fatal("Failed to return invalid argument error") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/memory_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/memory_test.go deleted file mode 100644 index 60edc67a524..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/memory_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package fs - -import ( - "strconv" - "testing" - - "github.com/docker/libcontainer/cgroups" -) - -const ( - memoryStatContents = `cache 512 -rss 1024` - memoryUsageContents = "2048\n" - memoryMaxUsageContents = "4096\n" - memoryFailcnt = "100\n" -) - -func TestMemorySetMemory(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - memoryBefore = 314572800 // 300M - memoryAfter = 524288000 // 500M - reservationBefore = 209715200 // 200M - reservationAfter = 314572800 // 300M - ) - - helper.writeFileContents(map[string]string{ - "memory.limit_in_bytes": strconv.Itoa(memoryBefore), - "memory.soft_limit_in_bytes": strconv.Itoa(reservationBefore), - }) - - helper.CgroupData.c.Memory = memoryAfter - helper.CgroupData.c.MemoryReservation = reservationAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.limit_in_bytes - %s", err) - } - if value != memoryAfter { - t.Fatal("Got the wrong value, set memory.limit_in_bytes failed.") - } - - value, err = getCgroupParamUint(helper.CgroupPath, "memory.soft_limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.soft_limit_in_bytes - %s", err) - } - if value != reservationAfter { - t.Fatal("Got the wrong value, set memory.soft_limit_in_bytes failed.") - } -} - -func TestMemorySetMemoryswap(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - memoryswapBefore = 314572800 // 300M - memoryswapAfter = 524288000 // 500M - ) - - helper.writeFileContents(map[string]string{ - "memory.memsw.limit_in_bytes": strconv.Itoa(memoryswapBefore), - }) - - helper.CgroupData.c.MemorySwap = memoryswapAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.memsw.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.memsw.limit_in_bytes - %s", err) - } - if value != memoryswapAfter { - t.Fatal("Got the wrong value, set memory.memsw.limit_in_bytes failed.") - } -} - -func TestMemorySetMemoryswapDefault(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - memoryBefore = 209715200 // 200M - memoryAfter = 314572800 // 300M - memoryswapAfter = 629145600 // 300M*2 - ) - - helper.writeFileContents(map[string]string{ - "memory.limit_in_bytes": strconv.Itoa(memoryBefore), - }) - - helper.CgroupData.c.Memory = memoryAfter - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.memsw.limit_in_bytes") - if err != nil { - t.Fatalf("Failed to parse memory.memsw.limit_in_bytes - %s", err) - } - if value != memoryswapAfter { - t.Fatal("Got the wrong value, set memory.memsw.limit_in_bytes failed.") - } -} - -func TestMemoryStats(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - "memory.failcnt": memoryFailcnt, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } - expectedStats := cgroups.MemoryStats{Usage: 2048, Cache: 512, MaxUsage: 4096, Failcnt: 100, Stats: map[string]uint64{"cache": 512, "rss": 1024}} - expectMemoryStatEquals(t, expectedStats, actualStats.MemoryStats) -} - -func TestMemoryStatsNoStatFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err != nil { - t.Fatal(err) - } -} - -func TestMemoryStatsNoUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsNoMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadStatFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": "rss rss", - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": "bad", - "memory.max_usage_in_bytes": memoryMaxUsageContents, - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemoryStatsBadMaxUsageFile(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - helper.writeFileContents(map[string]string{ - "memory.stat": memoryStatContents, - "memory.usage_in_bytes": memoryUsageContents, - "memory.max_usage_in_bytes": "bad", - }) - - memory := &MemoryGroup{} - actualStats := *cgroups.NewStats() - err := memory.GetStats(helper.CgroupPath, &actualStats) - if err == nil { - t.Fatal("Expected failure") - } -} - -func TestMemorySetOomControl(t *testing.T) { - helper := NewCgroupTestUtil("memory", t) - defer helper.cleanup() - - const ( - oom_kill_disable = 1 // disable oom killer, default is 0 - ) - - helper.writeFileContents(map[string]string{ - "memory.oom_control": strconv.Itoa(oom_kill_disable), - }) - - memory := &MemoryGroup{} - if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { - t.Fatal(err) - } - - value, err := getCgroupParamUint(helper.CgroupPath, "memory.oom_control") - if err != nil { - t.Fatalf("Failed to parse memory.oom_control - %s", err) - } - - if value != oom_kill_disable { - t.Fatalf("Got the wrong value, set memory.oom_control failed.") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/stats_util_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/stats_util_test.go deleted file mode 100644 index c55ba938cbc..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/stats_util_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package fs - -import ( - "fmt" - "log" - "testing" - - "github.com/docker/libcontainer/cgroups" -) - -func blkioStatEntryEquals(expected, actual []cgroups.BlkioStatEntry) error { - if len(expected) != len(actual) { - return fmt.Errorf("blkioStatEntries length do not match") - } - for i, expValue := range expected { - actValue := actual[i] - if expValue != actValue { - return fmt.Errorf("Expected blkio stat entry %v but found %v", expValue, actValue) - } - } - return nil -} - -func expectBlkioStatsEquals(t *testing.T, expected, actual cgroups.BlkioStats) { - if err := blkioStatEntryEquals(expected.IoServiceBytesRecursive, actual.IoServiceBytesRecursive); err != nil { - log.Printf("blkio IoServiceBytesRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoServicedRecursive, actual.IoServicedRecursive); err != nil { - log.Printf("blkio IoServicedRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoQueuedRecursive, actual.IoQueuedRecursive); err != nil { - log.Printf("blkio IoQueuedRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.SectorsRecursive, actual.SectorsRecursive); err != nil { - log.Printf("blkio SectorsRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoServiceTimeRecursive, actual.IoServiceTimeRecursive); err != nil { - log.Printf("blkio IoServiceTimeRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoWaitTimeRecursive, actual.IoWaitTimeRecursive); err != nil { - log.Printf("blkio IoWaitTimeRecursive do not match - %s\n", err) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoMergedRecursive, actual.IoMergedRecursive); err != nil { - log.Printf("blkio IoMergedRecursive do not match - %v vs %v\n", expected.IoMergedRecursive, actual.IoMergedRecursive) - t.Fail() - } - - if err := blkioStatEntryEquals(expected.IoTimeRecursive, actual.IoTimeRecursive); err != nil { - log.Printf("blkio IoTimeRecursive do not match - %s\n", err) - t.Fail() - } -} - -func expectThrottlingDataEquals(t *testing.T, expected, actual cgroups.ThrottlingData) { - if expected != actual { - log.Printf("Expected throttling data %v but found %v\n", expected, actual) - t.Fail() - } -} - -func expectMemoryStatEquals(t *testing.T, expected, actual cgroups.MemoryStats) { - if expected.Usage != actual.Usage { - log.Printf("Expected memory usage %d but found %d\n", expected.Usage, actual.Usage) - t.Fail() - } - if expected.MaxUsage != actual.MaxUsage { - log.Printf("Expected memory max usage %d but found %d\n", expected.MaxUsage, actual.MaxUsage) - t.Fail() - } - for key, expValue := range expected.Stats { - actValue, ok := actual.Stats[key] - if !ok { - log.Printf("Expected memory stat key %s not found\n", key) - t.Fail() - } - if expValue != actValue { - log.Printf("Expected memory stat value %d but found %d\n", expValue, actValue) - t.Fail() - } - } - if expected.Failcnt != actual.Failcnt { - log.Printf("Expected memory failcnt %d but found %d\n", expected.Failcnt, actual.Failcnt) - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/util_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/util_test.go deleted file mode 100644 index 37bf5157818..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/util_test.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Utility for testing cgroup operations. - -Creates a mock of the cgroup filesystem for the duration of the test. -*/ -package fs - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/docker/libcontainer/configs" -) - -type cgroupTestUtil struct { - // data to use in tests. - CgroupData *data - - // Path to the mock cgroup directory. - CgroupPath string - - // Temporary directory to store mock cgroup filesystem. - tempDir string - t *testing.T -} - -// Creates a new test util for the specified subsystem -func NewCgroupTestUtil(subsystem string, t *testing.T) *cgroupTestUtil { - d := &data{ - c: &configs.Cgroup{}, - } - tempDir, err := ioutil.TempDir("", "cgroup_test") - if err != nil { - t.Fatal(err) - } - d.root = tempDir - testCgroupPath := filepath.Join(d.root, subsystem) - if err != nil { - t.Fatal(err) - } - - // Ensure the full mock cgroup path exists. - err = os.MkdirAll(testCgroupPath, 0755) - if err != nil { - t.Fatal(err) - } - return &cgroupTestUtil{CgroupData: d, CgroupPath: testCgroupPath, tempDir: tempDir, t: t} -} - -func (c *cgroupTestUtil) cleanup() { - os.RemoveAll(c.tempDir) -} - -// Write the specified contents on the mock of the specified cgroup files. -func (c *cgroupTestUtil) writeFileContents(fileContents map[string]string) { - for file, contents := range fileContents { - err := writeFile(c.CgroupPath, file, contents) - if err != nil { - c.t.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/utils_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/utils_test.go deleted file mode 100644 index 8b19a84b279..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/cgroups/fs/utils_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package fs - -import ( - "io/ioutil" - "math" - "os" - "path/filepath" - "strconv" - "testing" -) - -const ( - cgroupFile = "cgroup.file" - floatValue = 2048.0 - floatString = "2048" -) - -func TestGetCgroupParamsInt(t *testing.T) { - // Setup tempdir. - tempDir, err := ioutil.TempDir("", "cgroup_utils_test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - tempFile := filepath.Join(tempDir, cgroupFile) - - // Success. - err = ioutil.WriteFile(tempFile, []byte(floatString), 0755) - if err != nil { - t.Fatal(err) - } - value, err := getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != floatValue { - t.Fatalf("Expected %d to equal %f", value, floatValue) - } - - // Success with new line. - err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != floatValue { - t.Fatalf("Expected %d to equal %f", value, floatValue) - } - - // Success with negative values - err = ioutil.WriteFile(tempFile, []byte("-12345"), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != 0 { - t.Fatalf("Expected %d to equal %d", value, 0) - } - - // Success with negative values lesser than min int64 - s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64) - err = ioutil.WriteFile(tempFile, []byte(s), 0755) - if err != nil { - t.Fatal(err) - } - value, err = getCgroupParamUint(tempDir, cgroupFile) - if err != nil { - t.Fatal(err) - } else if value != 0 { - t.Fatalf("Expected %d to equal %d", value, 0) - } - - // Not a float. - err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0755) - if err != nil { - t.Fatal(err) - } - _, err = getCgroupParamUint(tempDir, cgroupFile) - if err == nil { - t.Fatal("Expecting error, got none") - } - - // Unknown file. - err = os.Remove(tempFile) - if err != nil { - t.Fatal(err) - } - _, err = getCgroupParamUint(tempDir, cgroupFile) - if err == nil { - t.Fatal("Expecting error, got none") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/configs/config_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/configs/config_test.go deleted file mode 100644 index 765d5e50dbb..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/configs/config_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package configs - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "testing" -) - -// Checks whether the expected capability is specified in the capabilities. -func contains(expected string, values []string) bool { - for _, v := range values { - if v == expected { - return true - } - } - return false -} - -func containsDevice(expected *Device, values []*Device) bool { - for _, d := range values { - if d.Path == expected.Path && - d.Permissions == expected.Permissions && - d.FileMode == expected.FileMode && - d.Major == expected.Major && - d.Minor == expected.Minor && - d.Type == expected.Type { - return true - } - } - return false -} - -func loadConfig(name string) (*Config, error) { - f, err := os.Open(filepath.Join("../sample_configs", name)) - if err != nil { - return nil, err - } - defer f.Close() - - var container *Config - if err := json.NewDecoder(f).Decode(&container); err != nil { - return nil, err - } - - // Check that a config doesn't contain extra fields - var configMap, abstractMap map[string]interface{} - - if _, err := f.Seek(0, 0); err != nil { - return nil, err - } - - if err := json.NewDecoder(f).Decode(&abstractMap); err != nil { - return nil, err - } - - configData, err := json.Marshal(&container) - if err != nil { - return nil, err - } - - if err := json.Unmarshal(configData, &configMap); err != nil { - return nil, err - } - - for k := range configMap { - delete(abstractMap, k) - } - - if len(abstractMap) != 0 { - return nil, fmt.Errorf("unknown fields: %s", abstractMap) - } - - return container, nil -} - -func TestConfigJsonFormat(t *testing.T) { - container, err := loadConfig("attach_to_bridge.json") - if err != nil { - t.Fatal(err) - } - - if container.Hostname != "koye" { - t.Log("hostname is not set") - t.Fail() - } - - if !container.Namespaces.Contains(NEWNET) { - t.Log("namespaces should contain NEWNET") - t.Fail() - } - - if container.Namespaces.Contains(NEWUSER) { - t.Log("namespaces should not contain NEWUSER") - t.Fail() - } - - if contains("SYS_ADMIN", container.Capabilities) { - t.Log("SYS_ADMIN should not be enabled in capabilities mask") - t.Fail() - } - - if !contains("MKNOD", container.Capabilities) { - t.Log("MKNOD should be enabled in capabilities mask") - t.Fail() - } - - if !contains("SYS_CHROOT", container.Capabilities) { - t.Log("capabilities mask should contain SYS_CHROOT") - t.Fail() - } - - for _, n := range container.Networks { - if n.Type == "veth" { - if n.Bridge != "docker0" { - t.Logf("veth bridge should be docker0 but received %q", n.Bridge) - t.Fail() - } - - if n.Address != "172.17.0.101/16" { - t.Logf("veth address should be 172.17.0.101/61 but received %q", n.Address) - t.Fail() - } - - if n.Gateway != "172.17.42.1" { - t.Logf("veth gateway should be 172.17.42.1 but received %q", n.Gateway) - t.Fail() - } - - if n.Mtu != 1500 { - t.Logf("veth mtu should be 1500 but received %d", n.Mtu) - t.Fail() - } - - break - } - } - for _, d := range DefaultSimpleDevices { - if !containsDevice(d, container.Devices) { - t.Logf("expected device configuration for %s", d.Path) - t.Fail() - } - } -} - -func TestApparmorProfile(t *testing.T) { - container, err := loadConfig("apparmor.json") - if err != nil { - t.Fatal(err) - } - - if container.AppArmorProfile != "docker-default" { - t.Fatalf("expected apparmor profile to be docker-default but received %q", container.AppArmorProfile) - } -} - -func TestSelinuxLabels(t *testing.T) { - container, err := loadConfig("selinux.json") - if err != nil { - t.Fatal(err) - } - label := "system_u:system_r:svirt_lxc_net_t:s0:c164,c475" - - if container.ProcessLabel != label { - t.Fatalf("expected process label %q but received %q", label, container.ProcessLabel) - } - if container.MountLabel != label { - t.Fatalf("expected mount label %q but received %q", label, container.MountLabel) - } -} - -func TestRemoveNamespace(t *testing.T) { - ns := Namespaces{ - {Type: NEWNET}, - } - if !ns.Remove(NEWNET) { - t.Fatal("NEWNET was not removed") - } - if len(ns) != 0 { - t.Fatalf("namespaces should have 0 items but reports %d", len(ns)) - } -} - -func TestHostUIDNoUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{}, - } - uid, err := config.HostUID() - if err != nil { - t.Fatal(err) - } - if uid != 0 { - t.Fatalf("expected uid 0 with no USERNS but received %d", uid) - } -} - -func TestHostUIDWithUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{{Type: NEWUSER}}, - UidMappings: []IDMap{ - { - ContainerID: 0, - HostID: 1000, - Size: 1, - }, - }, - } - uid, err := config.HostUID() - if err != nil { - t.Fatal(err) - } - if uid != 1000 { - t.Fatalf("expected uid 1000 with no USERNS but received %d", uid) - } -} - -func TestHostGIDNoUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{}, - } - uid, err := config.HostGID() - if err != nil { - t.Fatal(err) - } - if uid != 0 { - t.Fatalf("expected gid 0 with no USERNS but received %d", uid) - } -} - -func TestHostGIDWithUSERNS(t *testing.T) { - config := &Config{ - Namespaces: Namespaces{{Type: NEWUSER}}, - GidMappings: []IDMap{ - { - ContainerID: 0, - HostID: 1000, - Size: 1, - }, - }, - } - uid, err := config.HostGID() - if err != nil { - t.Fatal(err) - } - if uid != 1000 { - t.Fatalf("expected gid 1000 with no USERNS but received %d", uid) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/container_linux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/container_linux_test.go deleted file mode 100644 index b05733e585a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/container_linux_test.go +++ /dev/null @@ -1,201 +0,0 @@ -// +build linux - -package libcontainer - -import ( - "fmt" - "os" - "testing" - - "github.com/docker/libcontainer/cgroups" - "github.com/docker/libcontainer/configs" -) - -type mockCgroupManager struct { - pids []int - stats *cgroups.Stats - paths map[string]string -} - -func (m *mockCgroupManager) GetPids() ([]int, error) { - return m.pids, nil -} - -func (m *mockCgroupManager) GetStats() (*cgroups.Stats, error) { - return m.stats, nil -} - -func (m *mockCgroupManager) Apply(pid int) error { - return nil -} - -func (m *mockCgroupManager) Set(container *configs.Config) error { - return nil -} - -func (m *mockCgroupManager) Destroy() error { - return nil -} - -func (m *mockCgroupManager) GetPaths() map[string]string { - return m.paths -} - -func (m *mockCgroupManager) Freeze(state configs.FreezerState) error { - return nil -} - -type mockProcess struct { - _pid int - started string -} - -func (m *mockProcess) terminate() error { - return nil -} - -func (m *mockProcess) pid() int { - return m._pid -} - -func (m *mockProcess) startTime() (string, error) { - return m.started, nil -} - -func (m *mockProcess) start() error { - return nil -} - -func (m *mockProcess) wait() (*os.ProcessState, error) { - return nil, nil -} - -func (m *mockProcess) signal(_ os.Signal) error { - return nil -} - -func TestGetContainerPids(t *testing.T) { - container := &linuxContainer{ - id: "myid", - config: &configs.Config{}, - cgroupManager: &mockCgroupManager{pids: []int{1, 2, 3}}, - } - pids, err := container.Processes() - if err != nil { - t.Fatal(err) - } - for i, expected := range []int{1, 2, 3} { - if pids[i] != expected { - t.Fatalf("expected pid %d but received %d", expected, pids[i]) - } - } -} - -func TestGetContainerStats(t *testing.T) { - container := &linuxContainer{ - id: "myid", - config: &configs.Config{}, - cgroupManager: &mockCgroupManager{ - pids: []int{1, 2, 3}, - stats: &cgroups.Stats{ - MemoryStats: cgroups.MemoryStats{ - Usage: 1024, - }, - }, - }, - } - stats, err := container.Stats() - if err != nil { - t.Fatal(err) - } - if stats.CgroupStats == nil { - t.Fatal("cgroup stats are nil") - } - if stats.CgroupStats.MemoryStats.Usage != 1024 { - t.Fatalf("expected memory usage 1024 but recevied %d", stats.CgroupStats.MemoryStats.Usage) - } -} - -func TestGetContainerState(t *testing.T) { - var ( - pid = os.Getpid() - expectedMemoryPath = "/sys/fs/cgroup/memory/myid" - expectedNetworkPath = "/networks/fd" - ) - container := &linuxContainer{ - id: "myid", - config: &configs.Config{ - Namespaces: []configs.Namespace{ - {Type: configs.NEWPID}, - {Type: configs.NEWNS}, - {Type: configs.NEWNET, Path: expectedNetworkPath}, - {Type: configs.NEWUTS}, - // emulate host for IPC - //{Type: configs.NEWIPC}, - }, - }, - initProcess: &mockProcess{ - _pid: pid, - started: "010", - }, - cgroupManager: &mockCgroupManager{ - pids: []int{1, 2, 3}, - stats: &cgroups.Stats{ - MemoryStats: cgroups.MemoryStats{ - Usage: 1024, - }, - }, - paths: map[string]string{ - "memory": expectedMemoryPath, - }, - }, - } - state, err := container.State() - if err != nil { - t.Fatal(err) - } - if state.InitProcessPid != pid { - t.Fatalf("expected pid %d but received %d", pid, state.InitProcessPid) - } - if state.InitProcessStartTime != "010" { - t.Fatalf("expected process start time 010 but received %s", state.InitProcessStartTime) - } - paths := state.CgroupPaths - if paths == nil { - t.Fatal("cgroup paths should not be nil") - } - if memPath := paths["memory"]; memPath != expectedMemoryPath { - t.Fatalf("expected memory path %q but received %q", expectedMemoryPath, memPath) - } - for _, ns := range container.config.Namespaces { - path := state.NamespacePaths[ns.Type] - if path == "" { - t.Fatalf("expected non nil namespace path for %s", ns.Type) - } - if ns.Type == configs.NEWNET { - if path != expectedNetworkPath { - t.Fatalf("expected path %q but received %q", expectedNetworkPath, path) - } - } else { - file := "" - switch ns.Type { - case configs.NEWNET: - file = "net" - case configs.NEWNS: - file = "mnt" - case configs.NEWPID: - file = "pid" - case configs.NEWIPC: - file = "ipc" - case configs.NEWUSER: - file = "user" - case configs.NEWUTS: - file = "uts" - } - expected := fmt.Sprintf("/proc/%d/ns/%s", pid, file) - if expected != path { - t.Fatalf("expected path %q but received %q", expected, path) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/devices/devices_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/devices/devices_test.go deleted file mode 100644 index 9e52fc4e258..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/devices/devices_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package devices - -import ( - "errors" - "os" - "testing" -) - -func TestDeviceFromPathLstatFailure(t *testing.T) { - testError := errors.New("test error") - - // Override os.Lstat to inject error. - osLstat = func(path string) (os.FileInfo, error) { - return nil, testError - } - - _, err := DeviceFromPath("", "") - if err != testError { - t.Fatalf("Unexpected error %v, expected %v", err, testError) - } -} - -func TestHostDevicesIoutilReadDirFailure(t *testing.T) { - testError := errors.New("test error") - - // Override ioutil.ReadDir to inject error. - ioutilReadDir = func(dirname string) ([]os.FileInfo, error) { - return nil, testError - } - - _, err := HostDevices() - if err != testError { - t.Fatalf("Unexpected error %v, expected %v", err, testError) - } -} - -func TestHostDevicesIoutilReadDirDeepFailure(t *testing.T) { - testError := errors.New("test error") - called := false - - // Override ioutil.ReadDir to inject error after the first call. - ioutilReadDir = func(dirname string) ([]os.FileInfo, error) { - if called { - return nil, testError - } - called = true - - // Provoke a second call. - fi, err := os.Lstat("/tmp") - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - - return []os.FileInfo{fi}, nil - } - - _, err := HostDevices() - if err != testError { - t.Fatalf("Unexpected error %v, expected %v", err, testError) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/error_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/error_test.go deleted file mode 100644 index 4bf4c9f5d49..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/error_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package libcontainer - -import "testing" - -func TestErrorCode(t *testing.T) { - codes := map[ErrorCode]string{ - IdInUse: "Id already in use", - InvalidIdFormat: "Invalid format", - ContainerPaused: "Container paused", - ConfigInvalid: "Invalid configuration", - SystemError: "System error", - ContainerNotExists: "Container does not exist", - } - - for code, expected := range codes { - if actual := code.String(); actual != expected { - t.Fatalf("expected string %q but received %q", expected, actual) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/factory_linux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/factory_linux_test.go deleted file mode 100644 index 00e39739439..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/factory_linux_test.go +++ /dev/null @@ -1,179 +0,0 @@ -// +build linux - -package libcontainer - -import ( - "encoding/json" - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/docker/docker/pkg/mount" - "github.com/docker/libcontainer/configs" -) - -func newTestRoot() (string, error) { - dir, err := ioutil.TempDir("", "libcontainer") - if err != nil { - return "", err - } - return dir, nil -} - -func TestFactoryNew(t *testing.T) { - root, rerr := newTestRoot() - if rerr != nil { - t.Fatal(rerr) - } - defer os.RemoveAll(root) - factory, err := New(root, Cgroupfs) - if err != nil { - t.Fatal(err) - } - if factory == nil { - t.Fatal("factory should not be nil") - } - lfactory, ok := factory.(*LinuxFactory) - if !ok { - t.Fatal("expected linux factory returned on linux based systems") - } - if lfactory.Root != root { - t.Fatalf("expected factory root to be %q but received %q", root, lfactory.Root) - } - - if factory.Type() != "libcontainer" { - t.Fatalf("unexpected factory type: %q, expected %q", factory.Type(), "libcontainer") - } -} - -func TestFactoryNewTmpfs(t *testing.T) { - root, rerr := newTestRoot() - if rerr != nil { - t.Fatal(rerr) - } - defer os.RemoveAll(root) - factory, err := New(root, Cgroupfs, TmpfsRoot) - if err != nil { - t.Fatal(err) - } - if factory == nil { - t.Fatal("factory should not be nil") - } - lfactory, ok := factory.(*LinuxFactory) - if !ok { - t.Fatal("expected linux factory returned on linux based systems") - } - if lfactory.Root != root { - t.Fatalf("expected factory root to be %q but received %q", root, lfactory.Root) - } - - if factory.Type() != "libcontainer" { - t.Fatalf("unexpected factory type: %q, expected %q", factory.Type(), "libcontainer") - } - mounted, err := mount.Mounted(lfactory.Root) - if err != nil { - t.Fatal(err) - } - if !mounted { - t.Fatalf("Factory Root is not mounted") - } - mounts, err := mount.GetMounts() - if err != nil { - t.Fatal(err) - } - var found bool - for _, m := range mounts { - if m.Mountpoint == lfactory.Root { - if m.Fstype != "tmpfs" { - t.Fatalf("Fstype of root: %s, expected %s", m.Fstype, "tmpfs") - } - if m.Source != "tmpfs" { - t.Fatalf("Source of root: %s, expected %s", m.Source, "tmpfs") - } - found = true - } - } - if !found { - t.Fatalf("Factory Root is not listed in mounts list") - } -} - -func TestFactoryLoadNotExists(t *testing.T) { - root, rerr := newTestRoot() - if rerr != nil { - t.Fatal(rerr) - } - defer os.RemoveAll(root) - factory, err := New(root, Cgroupfs) - if err != nil { - t.Fatal(err) - } - _, err = factory.Load("nocontainer") - if err == nil { - t.Fatal("expected nil error loading non-existing container") - } - lerr, ok := err.(Error) - if !ok { - t.Fatal("expected libcontainer error type") - } - if lerr.Code() != ContainerNotExists { - t.Fatalf("expected error code %s but received %s", ContainerNotExists, lerr.Code()) - } -} - -func TestFactoryLoadContainer(t *testing.T) { - root, err := newTestRoot() - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(root) - // setup default container config and state for mocking - var ( - id = "1" - expectedConfig = &configs.Config{ - Rootfs: "/mycontainer/root", - } - expectedState = &State{ - InitProcessPid: 1024, - Config: *expectedConfig, - } - ) - if err := os.Mkdir(filepath.Join(root, id), 0700); err != nil { - t.Fatal(err) - } - if err := marshal(filepath.Join(root, id, stateFilename), expectedState); err != nil { - t.Fatal(err) - } - factory, err := New(root, Cgroupfs) - if err != nil { - t.Fatal(err) - } - container, err := factory.Load(id) - if err != nil { - t.Fatal(err) - } - if container.ID() != id { - t.Fatalf("expected container id %q but received %q", id, container.ID()) - } - config := container.Config() - if config.Rootfs != expectedConfig.Rootfs { - t.Fatalf("expected rootfs %q but received %q", expectedConfig.Rootfs, config.Rootfs) - } - lcontainer, ok := container.(*linuxContainer) - if !ok { - t.Fatal("expected linux container on linux based systems") - } - if lcontainer.initProcess.pid() != expectedState.InitProcessPid { - t.Fatalf("expected init pid %d but received %d", expectedState.InitProcessPid, lcontainer.initProcess.pid()) - } -} - -func marshal(path string, v interface{}) error { - f, err := os.Create(path) - if err != nil { - return err - } - defer f.Close() - return json.NewEncoder(f).Encode(v) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/generic_error_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/generic_error_test.go deleted file mode 100644 index 292d2a36bdc..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/generic_error_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package libcontainer - -import ( - "fmt" - "io/ioutil" - "testing" -) - -func TestErrorDetail(t *testing.T) { - err := newGenericError(fmt.Errorf("test error"), SystemError) - if derr := err.Detail(ioutil.Discard); derr != nil { - t.Fatal(derr) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/exec_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/integration/exec_test.go deleted file mode 100644 index 8f6719d0a6a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/exec_test.go +++ /dev/null @@ -1,615 +0,0 @@ -package integration - -import ( - "bytes" - "io/ioutil" - "os" - "strconv" - "strings" - "testing" - - "github.com/docker/libcontainer" - "github.com/docker/libcontainer/cgroups/systemd" - "github.com/docker/libcontainer/configs" -) - -func TestExecPS(t *testing.T) { - testExecPS(t, false) -} - -func TestUsernsExecPS(t *testing.T) { - if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) { - t.Skip("userns is unsupported") - } - testExecPS(t, true) -} - -func testExecPS(t *testing.T, userns bool) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - if userns { - config.UidMappings = []configs.IDMap{{0, 0, 1000}} - config.GidMappings = []configs.IDMap{{0, 0, 1000}} - config.Namespaces = append(config.Namespaces, configs.Namespace{Type: configs.NEWUSER}) - } - - buffers, exitCode, err := runContainer(config, "", "ps") - if err != nil { - t.Fatalf("%s: %s", buffers, err) - } - if exitCode != 0 { - t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) - } - lines := strings.Split(buffers.Stdout.String(), "\n") - if len(lines) < 2 { - t.Fatalf("more than one process running for output %q", buffers.Stdout.String()) - } - expected := `1 root ps` - actual := strings.Trim(lines[1], "\n ") - if actual != expected { - t.Fatalf("expected output %q but received %q", expected, actual) - } -} - -func TestIPCPrivate(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - l, err := os.Readlink("/proc/1/ns/ipc") - ok(t, err) - - config := newTemplateConfig(rootfs) - buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") - ok(t, err) - - if exitCode != 0 { - t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) - } - - if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual == l { - t.Fatalf("ipc link should be private to the container but equals host %q %q", actual, l) - } -} - -func TestIPCHost(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - l, err := os.Readlink("/proc/1/ns/ipc") - ok(t, err) - - config := newTemplateConfig(rootfs) - config.Namespaces.Remove(configs.NEWIPC) - buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") - ok(t, err) - - if exitCode != 0 { - t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) - } - - if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l { - t.Fatalf("ipc link not equal to host link %q %q", actual, l) - } -} - -func TestIPCJoinPath(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - l, err := os.Readlink("/proc/1/ns/ipc") - ok(t, err) - - config := newTemplateConfig(rootfs) - config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipc") - - buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") - ok(t, err) - - if exitCode != 0 { - t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) - } - - if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l { - t.Fatalf("ipc link not equal to host link %q %q", actual, l) - } -} - -func TestIPCBadPath(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipcc") - - _, _, err = runContainer(config, "", "true") - if err == nil { - t.Fatal("container succeeded with bad ipc path") - } -} - -func TestRlimit(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - out, _, err := runContainer(config, "", "/bin/sh", "-c", "ulimit -n") - ok(t, err) - if limit := strings.TrimSpace(out.Stdout.String()); limit != "1025" { - t.Fatalf("expected rlimit to be 1025, got %s", limit) - } -} - -func newTestRoot() (string, error) { - dir, err := ioutil.TempDir("", "libcontainer") - if err != nil { - return "", err - } - if err := os.MkdirAll(dir, 0700); err != nil { - return "", err - } - return dir, nil -} - -func waitProcess(p *libcontainer.Process, t *testing.T) { - status, err := p.Wait() - ok(t, err) - if !status.Success() { - t.Fatal(status) - } -} - -func TestEnter(t *testing.T) { - if testing.Short() { - return - } - root, err := newTestRoot() - ok(t, err) - defer os.RemoveAll(root) - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - - factory, err := libcontainer.New(root, libcontainer.Cgroupfs) - ok(t, err) - - container, err := factory.Create("test", config) - ok(t, err) - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - ok(t, err) - - var stdout, stdout2 bytes.Buffer - - pconfig := libcontainer.Process{ - Args: []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"}, - Env: standardEnvironment, - Stdin: stdinR, - Stdout: &stdout, - } - err = container.Start(&pconfig) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - pid, err := pconfig.Pid() - ok(t, err) - - // Execute another process in the container - stdinR2, stdinW2, err := os.Pipe() - ok(t, err) - pconfig2 := libcontainer.Process{ - Env: standardEnvironment, - } - pconfig2.Args = []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"} - pconfig2.Stdin = stdinR2 - pconfig2.Stdout = &stdout2 - - err = container.Start(&pconfig2) - stdinR2.Close() - defer stdinW2.Close() - ok(t, err) - - pid2, err := pconfig2.Pid() - ok(t, err) - - processes, err := container.Processes() - ok(t, err) - - n := 0 - for i := range processes { - if processes[i] == pid || processes[i] == pid2 { - n++ - } - } - if n != 2 { - t.Fatal("unexpected number of processes", processes, pid, pid2) - } - - // Wait processes - stdinW2.Close() - waitProcess(&pconfig2, t) - - stdinW.Close() - waitProcess(&pconfig, t) - - // Check that both processes live in the same pidns - pidns := string(stdout.Bytes()) - ok(t, err) - - pidns2 := string(stdout2.Bytes()) - ok(t, err) - - if pidns != pidns2 { - t.Fatal("The second process isn't in the required pid namespace", pidns, pidns2) - } -} - -func TestProcessEnv(t *testing.T) { - if testing.Short() { - return - } - root, err := newTestRoot() - ok(t, err) - defer os.RemoveAll(root) - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - - factory, err := libcontainer.New(root, libcontainer.Cgroupfs) - ok(t, err) - - container, err := factory.Create("test", config) - ok(t, err) - defer container.Destroy() - - var stdout bytes.Buffer - pconfig := libcontainer.Process{ - Args: []string{"sh", "-c", "env"}, - Env: []string{ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "HOSTNAME=integration", - "TERM=xterm", - "FOO=BAR", - }, - Stdin: nil, - Stdout: &stdout, - } - err = container.Start(&pconfig) - ok(t, err) - - // Wait for process - waitProcess(&pconfig, t) - - outputEnv := string(stdout.Bytes()) - - // Check that the environment has the key/value pair we added - if !strings.Contains(outputEnv, "FOO=BAR") { - t.Fatal("Environment doesn't have the expected FOO=BAR key/value pair: ", outputEnv) - } - - // Make sure that HOME is set - if !strings.Contains(outputEnv, "HOME=/root") { - t.Fatal("Environment doesn't have HOME set: ", outputEnv) - } -} - -func TestProcessCaps(t *testing.T) { - if testing.Short() { - return - } - root, err := newTestRoot() - ok(t, err) - defer os.RemoveAll(root) - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - - factory, err := libcontainer.New(root, libcontainer.Cgroupfs) - ok(t, err) - - container, err := factory.Create("test", config) - ok(t, err) - defer container.Destroy() - - processCaps := append(config.Capabilities, "NET_ADMIN") - - var stdout bytes.Buffer - pconfig := libcontainer.Process{ - Args: []string{"sh", "-c", "cat /proc/self/status"}, - Env: standardEnvironment, - Capabilities: processCaps, - Stdin: nil, - Stdout: &stdout, - } - err = container.Start(&pconfig) - ok(t, err) - - // Wait for process - waitProcess(&pconfig, t) - - outputStatus := string(stdout.Bytes()) - - lines := strings.Split(outputStatus, "\n") - - effectiveCapsLine := "" - for _, l := range lines { - line := strings.TrimSpace(l) - if strings.Contains(line, "CapEff:") { - effectiveCapsLine = line - break - } - } - - if effectiveCapsLine == "" { - t.Fatal("Couldn't find effective caps: ", outputStatus) - } - - parts := strings.Split(effectiveCapsLine, ":") - effectiveCapsStr := strings.TrimSpace(parts[1]) - - effectiveCaps, err := strconv.ParseUint(effectiveCapsStr, 16, 64) - if err != nil { - t.Fatal("Could not parse effective caps", err) - } - - var netAdminMask uint64 - var netAdminBit uint - netAdminBit = 12 // from capability.h - netAdminMask = 1 << netAdminBit - if effectiveCaps&netAdminMask != netAdminMask { - t.Fatal("CAP_NET_ADMIN is not set as expected") - } -} - -func TestFreeze(t *testing.T) { - testFreeze(t, false) -} - -func TestSystemdFreeze(t *testing.T) { - if !systemd.UseSystemd() { - t.Skip("Systemd is unsupported") - } - testFreeze(t, true) -} - -func testFreeze(t *testing.T, systemd bool) { - if testing.Short() { - return - } - root, err := newTestRoot() - ok(t, err) - defer os.RemoveAll(root) - - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - if systemd { - config.Cgroups.Slice = "system.slice" - } - - factory, err := libcontainer.New(root, libcontainer.Cgroupfs) - ok(t, err) - - container, err := factory.Create("test", config) - ok(t, err) - defer container.Destroy() - - stdinR, stdinW, err := os.Pipe() - ok(t, err) - - pconfig := libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(&pconfig) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - - pid, err := pconfig.Pid() - ok(t, err) - - process, err := os.FindProcess(pid) - ok(t, err) - - err = container.Pause() - ok(t, err) - state, err := container.Status() - ok(t, err) - err = container.Resume() - ok(t, err) - if state != libcontainer.Paused { - t.Fatal("Unexpected state: ", state) - } - - stdinW.Close() - s, err := process.Wait() - ok(t, err) - - if !s.Success() { - t.Fatal(s.String()) - } -} - -func TestContainerState(t *testing.T) { - if testing.Short() { - return - } - root, err := newTestRoot() - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(root) - - rootfs, err := newRootfs() - if err != nil { - t.Fatal(err) - } - defer remove(rootfs) - - l, err := os.Readlink("/proc/1/ns/ipc") - if err != nil { - t.Fatal(err) - } - - config := newTemplateConfig(rootfs) - config.Namespaces = configs.Namespaces([]configs.Namespace{ - {Type: configs.NEWNS}, - {Type: configs.NEWUTS}, - // host for IPC - //{Type: configs.NEWIPC}, - {Type: configs.NEWPID}, - {Type: configs.NEWNET}, - }) - - factory, err := libcontainer.New(root, libcontainer.Cgroupfs) - if err != nil { - t.Fatal(err) - } - - container, err := factory.Create("test", config) - if err != nil { - t.Fatal(err) - } - defer container.Destroy() - - stdinR, stdinW, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - p := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(p) - if err != nil { - t.Fatal(err) - } - stdinR.Close() - defer p.Signal(os.Kill) - - st, err := container.State() - if err != nil { - t.Fatal(err) - } - - l1, err := os.Readlink(st.NamespacePaths[configs.NEWIPC]) - if err != nil { - t.Fatal(err) - } - if l1 != l { - t.Fatal("Container using non-host ipc namespace") - } - stdinW.Close() - p.Wait() -} - -func TestPassExtraFiles(t *testing.T) { - if testing.Short() { - return - } - - rootfs, err := newRootfs() - if err != nil { - t.Fatal(err) - } - defer remove(rootfs) - - config := newTemplateConfig(rootfs) - - factory, err := libcontainer.New(rootfs, libcontainer.Cgroupfs) - if err != nil { - t.Fatal(err) - } - - container, err := factory.Create("test", config) - if err != nil { - t.Fatal(err) - } - defer container.Destroy() - - var stdout bytes.Buffer - pipeout1, pipein1, err := os.Pipe() - pipeout2, pipein2, err := os.Pipe() - process := libcontainer.Process{ - Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"}, - Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, - ExtraFiles: []*os.File{pipein1, pipein2}, - Stdin: nil, - Stdout: &stdout, - } - err = container.Start(&process) - if err != nil { - t.Fatal(err) - } - - waitProcess(&process, t) - - out := string(stdout.Bytes()) - // fd 5 is the directory handle for /proc/$$/fd - if out != "0 1 2 3 4 5" { - t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out) - } - var buf = []byte{0} - _, err = pipeout1.Read(buf) - if err != nil { - t.Fatal(err) - } - out1 := string(buf) - if out1 != "1" { - t.Fatalf("expected first pipe to receive '1', got '%s'", out1) - } - - _, err = pipeout2.Read(buf) - if err != nil { - t.Fatal(err) - } - out2 := string(buf) - if out2 != "2" { - t.Fatalf("expected second pipe to receive '2', got '%s'", out2) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/execin_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/integration/execin_test.go deleted file mode 100644 index 7c8a19da838..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/execin_test.go +++ /dev/null @@ -1,338 +0,0 @@ -package integration - -import ( - "bytes" - "io" - "os" - "strings" - "testing" - "time" - - "github.com/docker/libcontainer" -) - -func TestExecIn(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - ok(t, err) - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - ok(t, err) - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - - buffers := newStdBuffers() - ps := &libcontainer.Process{ - Args: []string{"ps"}, - Env: standardEnvironment, - Stdin: buffers.Stdin, - Stdout: buffers.Stdout, - Stderr: buffers.Stderr, - } - err = container.Start(ps) - ok(t, err) - _, err = ps.Wait() - ok(t, err) - stdinW.Close() - if _, err := process.Wait(); err != nil { - t.Log(err) - } - out := buffers.Stdout.String() - if !strings.Contains(out, "cat") || !strings.Contains(out, "ps") { - t.Fatalf("unexpected running process, output %q", out) - } -} - -func TestExecInRlimit(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - ok(t, err) - defer container.Destroy() - - stdinR, stdinW, err := os.Pipe() - ok(t, err) - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - - buffers := newStdBuffers() - ps := &libcontainer.Process{ - Args: []string{"/bin/sh", "-c", "ulimit -n"}, - Env: standardEnvironment, - Stdin: buffers.Stdin, - Stdout: buffers.Stdout, - Stderr: buffers.Stderr, - } - err = container.Start(ps) - ok(t, err) - _, err = ps.Wait() - ok(t, err) - stdinW.Close() - if _, err := process.Wait(); err != nil { - t.Log(err) - } - out := buffers.Stdout.String() - if limit := strings.TrimSpace(out); limit != "1025" { - t.Fatalf("expected rlimit to be 1025, got %s", limit) - } -} - -func TestExecInError(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - ok(t, err) - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - ok(t, err) - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer func() { - stdinW.Close() - if _, err := process.Wait(); err != nil { - t.Log(err) - } - }() - ok(t, err) - - unexistent := &libcontainer.Process{ - Args: []string{"unexistent"}, - Env: standardEnvironment, - } - err = container.Start(unexistent) - if err == nil { - t.Fatal("Should be an error") - } - if !strings.Contains(err.Error(), "executable file not found") { - t.Fatalf("Should be error about not found executable, got %s", err) - } -} - -func TestExecInTTY(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - ok(t, err) - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - ok(t, err) - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - - var stdout bytes.Buffer - ps := &libcontainer.Process{ - Args: []string{"ps"}, - Env: standardEnvironment, - } - console, err := ps.NewConsole(0) - copy := make(chan struct{}) - go func() { - io.Copy(&stdout, console) - close(copy) - }() - ok(t, err) - err = container.Start(ps) - ok(t, err) - select { - case <-time.After(5 * time.Second): - t.Fatal("Waiting for copy timed out") - case <-copy: - } - _, err = ps.Wait() - ok(t, err) - stdinW.Close() - if _, err := process.Wait(); err != nil { - t.Log(err) - } - out := stdout.String() - if !strings.Contains(out, "cat") || !strings.Contains(string(out), "ps") { - t.Fatalf("unexpected running process, output %q", out) - } -} - -func TestExecInEnvironment(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - ok(t, err) - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - ok(t, err) - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - ok(t, err) - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer stdinW.Close() - ok(t, err) - - buffers := newStdBuffers() - process2 := &libcontainer.Process{ - Args: []string{"env"}, - Env: []string{ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "DEBUG=true", - "DEBUG=false", - "ENV=test", - }, - Stdin: buffers.Stdin, - Stdout: buffers.Stdout, - Stderr: buffers.Stderr, - } - err = container.Start(process2) - ok(t, err) - if _, err := process2.Wait(); err != nil { - out := buffers.Stdout.String() - t.Fatal(err, out) - } - stdinW.Close() - if _, err := process.Wait(); err != nil { - t.Log(err) - } - out := buffers.Stdout.String() - // check execin's process environment - if !strings.Contains(out, "DEBUG=false") || - !strings.Contains(out, "ENV=test") || - !strings.Contains(out, "HOME=/root") || - !strings.Contains(out, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") || - strings.Contains(out, "DEBUG=true") { - t.Fatalf("unexpected running process, output %q", out) - } -} - -func TestExecinPassExtraFiles(t *testing.T) { - if testing.Short() { - return - } - rootfs, err := newRootfs() - if err != nil { - t.Fatal(err) - } - defer remove(rootfs) - config := newTemplateConfig(rootfs) - container, err := newContainer(config) - if err != nil { - t.Fatal(err) - } - defer container.Destroy() - - // Execute a first process in the container - stdinR, stdinW, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - process := &libcontainer.Process{ - Args: []string{"cat"}, - Env: standardEnvironment, - Stdin: stdinR, - } - err = container.Start(process) - stdinR.Close() - defer stdinW.Close() - if err != nil { - t.Fatal(err) - } - - var stdout bytes.Buffer - pipeout1, pipein1, err := os.Pipe() - pipeout2, pipein2, err := os.Pipe() - inprocess := &libcontainer.Process{ - Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"}, - Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, - ExtraFiles: []*os.File{pipein1, pipein2}, - Stdin: nil, - Stdout: &stdout, - } - err = container.Start(inprocess) - if err != nil { - t.Fatal(err) - } - - waitProcess(inprocess, t) - - out := string(stdout.Bytes()) - // fd 5 is the directory handle for /proc/$$/fd - if out != "0 1 2 3 4 5" { - t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to exec, got '%s'", out) - } - var buf = []byte{0} - _, err = pipeout1.Read(buf) - if err != nil { - t.Fatal(err) - } - out1 := string(buf) - if out1 != "1" { - t.Fatalf("expected first pipe to receive '1', got '%s'", out1) - } - - _, err = pipeout2.Read(buf) - if err != nil { - t.Fatal(err) - } - out2 := string(buf) - if out2 != "2" { - t.Fatalf("expected second pipe to receive '2', got '%s'", out2) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/init_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/integration/init_test.go deleted file mode 100644 index 1f75ef525e2..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/init_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package integration - -import ( - "log" - "os" - "runtime" - - "github.com/docker/libcontainer" - _ "github.com/docker/libcontainer/nsenter" -) - -// init runs the libcontainer initialization code because of the busybox style needs -// to work around the go runtime and the issues with forking -func init() { - if len(os.Args) < 2 || os.Args[1] != "init" { - return - } - runtime.GOMAXPROCS(1) - runtime.LockOSThread() - factory, err := libcontainer.New("") - if err != nil { - log.Fatalf("unable to initialize for container: %s", err) - } - if err := factory.StartInitialization(); err != nil { - log.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/template_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/integration/template_test.go deleted file mode 100644 index cb991b4170f..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/template_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package integration - -import ( - "syscall" - - "github.com/docker/libcontainer/configs" -) - -var standardEnvironment = []string{ - "HOME=/root", - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "HOSTNAME=integration", - "TERM=xterm", -} - -const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV - -// newTemplateConfig returns a base template for running a container -// -// it uses a network strategy of just setting a loopback interface -// and the default setup for devices -func newTemplateConfig(rootfs string) *configs.Config { - return &configs.Config{ - Rootfs: rootfs, - Capabilities: []string{ - "CHOWN", - "DAC_OVERRIDE", - "FSETID", - "FOWNER", - "MKNOD", - "NET_RAW", - "SETGID", - "SETUID", - "SETFCAP", - "SETPCAP", - "NET_BIND_SERVICE", - "SYS_CHROOT", - "KILL", - "AUDIT_WRITE", - }, - Namespaces: configs.Namespaces([]configs.Namespace{ - {Type: configs.NEWNS}, - {Type: configs.NEWUTS}, - {Type: configs.NEWIPC}, - {Type: configs.NEWPID}, - {Type: configs.NEWNET}, - }), - Cgroups: &configs.Cgroup{ - Name: "test", - Parent: "integration", - AllowAllDevices: false, - AllowedDevices: configs.DefaultAllowedDevices, - }, - MaskPaths: []string{ - "/proc/kcore", - }, - ReadonlyPaths: []string{ - "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus", - }, - Devices: configs.DefaultAutoCreatedDevices, - Hostname: "integration", - Mounts: []*configs.Mount{ - { - Source: "proc", - Destination: "/proc", - Device: "proc", - Flags: defaultMountFlags, - }, - { - Source: "tmpfs", - Destination: "/dev", - Device: "tmpfs", - Flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME, - Data: "mode=755", - }, - { - Source: "devpts", - Destination: "/dev/pts", - Device: "devpts", - Flags: syscall.MS_NOSUID | syscall.MS_NOEXEC, - Data: "newinstance,ptmxmode=0666,mode=0620,gid=5", - }, - { - Device: "tmpfs", - Source: "shm", - Destination: "/dev/shm", - Data: "mode=1777,size=65536k", - Flags: defaultMountFlags, - }, - { - Source: "mqueue", - Destination: "/dev/mqueue", - Device: "mqueue", - Flags: defaultMountFlags, - }, - { - Source: "sysfs", - Destination: "/sys", - Device: "sysfs", - Flags: defaultMountFlags | syscall.MS_RDONLY, - }, - }, - Networks: []*configs.Network{ - { - Type: "loopback", - Address: "127.0.0.1/0", - Gateway: "localhost", - }, - }, - Rlimits: []configs.Rlimit{ - { - Type: syscall.RLIMIT_NOFILE, - Hard: uint64(1025), - Soft: uint64(1025), - }, - }, - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/utils_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/integration/utils_test.go deleted file mode 100644 index 263d89d3b56..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/integration/utils_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package integration - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "syscall" - "testing" - - "github.com/docker/libcontainer" - "github.com/docker/libcontainer/configs" -) - -func newStdBuffers() *stdBuffers { - return &stdBuffers{ - Stdin: bytes.NewBuffer(nil), - Stdout: bytes.NewBuffer(nil), - Stderr: bytes.NewBuffer(nil), - } -} - -type stdBuffers struct { - Stdin *bytes.Buffer - Stdout *bytes.Buffer - Stderr *bytes.Buffer -} - -func (b *stdBuffers) String() string { - s := []string{} - if b.Stderr != nil { - s = append(s, b.Stderr.String()) - } - if b.Stdout != nil { - s = append(s, b.Stdout.String()) - } - return strings.Join(s, "|") -} - -// ok fails the test if an err is not nil. -func ok(t testing.TB, err error) { - if err != nil { - _, file, line, _ := runtime.Caller(1) - t.Fatalf("%s:%d: unexpected error: %s\n\n", filepath.Base(file), line, err.Error()) - } -} - -// newRootfs creates a new tmp directory and copies the busybox root filesystem -func newRootfs() (string, error) { - dir, err := ioutil.TempDir("", "") - if err != nil { - return "", err - } - if err := os.MkdirAll(dir, 0700); err != nil { - return "", err - } - if err := copyBusybox(dir); err != nil { - return "", nil - } - return dir, nil -} - -func remove(dir string) { - os.RemoveAll(dir) -} - -// copyBusybox copies the rootfs for a busybox container created for the test image -// into the new directory for the specific test -func copyBusybox(dest string) error { - out, err := exec.Command("sh", "-c", fmt.Sprintf("cp -R /busybox/* %s/", dest)).CombinedOutput() - if err != nil { - return fmt.Errorf("copy error %q: %q", err, out) - } - return nil -} - -func newContainer(config *configs.Config) (libcontainer.Container, error) { - cgm := libcontainer.Cgroupfs - if config.Cgroups != nil && config.Cgroups.Slice == "system.slice" { - cgm = libcontainer.SystemdCgroups - } - - factory, err := libcontainer.New(".", - libcontainer.InitArgs(os.Args[0], "init", "--"), - cgm, - ) - if err != nil { - return nil, err - } - return factory.Create("testCT", config) -} - -// runContainer runs the container with the specific config and arguments -// -// buffers are returned containing the STDOUT and STDERR output for the run -// along with the exit code and any go error -func runContainer(config *configs.Config, console string, args ...string) (buffers *stdBuffers, exitCode int, err error) { - container, err := newContainer(config) - if err != nil { - return nil, -1, err - } - defer container.Destroy() - buffers = newStdBuffers() - process := &libcontainer.Process{ - Args: args, - Env: standardEnvironment, - Stdin: buffers.Stdin, - Stdout: buffers.Stdout, - Stderr: buffers.Stderr, - } - - err = container.Start(process) - if err != nil { - return nil, -1, err - } - ps, err := process.Wait() - if err != nil { - return nil, -1, err - } - status := ps.Sys().(syscall.WaitStatus) - if status.Exited() { - exitCode = status.ExitStatus() - } else if status.Signaled() { - exitCode = -int(status.Signal()) - } else { - return nil, -1, err - } - return -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/label/label_selinux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/label/label_selinux_test.go deleted file mode 100644 index acbd59da615..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/label/label_selinux_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// +build selinux,linux - -package label - -import ( - "strings" - "testing" - - "github.com/docker/libcontainer/selinux" -) - -func TestInit(t *testing.T) { - if selinux.SelinuxEnabled() { - var testNull []string - plabel, mlabel, err := InitLabels(testNull) - if err != nil { - t.Log("InitLabels Failed") - t.Fatal(err) - } - testDisabled := []string{"disable"} - plabel, mlabel, err = InitLabels(testDisabled) - if err != nil { - t.Log("InitLabels Disabled Failed") - t.Fatal(err) - } - if plabel != "" { - t.Log("InitLabels Disabled Failed") - t.Fatal() - } - testUser := []string{"user:user_u", "role:user_r", "type:user_t", "level:s0:c1,c15"} - plabel, mlabel, err = InitLabels(testUser) - if err != nil { - t.Log("InitLabels User Failed") - t.Fatal(err) - } - if plabel != "user_u:user_r:user_t:s0:c1,c15" || mlabel != "user_u:object_r:svirt_sandbox_file_t:s0:c1,c15" { - t.Log("InitLabels User Match Failed") - t.Log(plabel, mlabel) - t.Fatal(err) - } - - testBadData := []string{"user", "role:user_r", "type:user_t", "level:s0:c1,c15"} - plabel, mlabel, err = InitLabels(testBadData) - if err == nil { - t.Log("InitLabels Bad Failed") - t.Fatal(err) - } - } -} -func TestDuplicateLabel(t *testing.T) { - secopt := DupSecOpt("system_u:system_r:svirt_lxc_net_t:s0:c1,c2") - t.Log(secopt) - for _, opt := range secopt { - con := strings.SplitN(opt, ":", 3) - if len(con) != 3 || con[0] != "label" { - t.Errorf("Invalid DupSecOpt return value") - continue - } - if con[1] == "user" { - if con[2] != "system_u" { - t.Errorf("DupSecOpt Failed user incorrect") - } - continue - } - if con[1] == "role" { - if con[2] != "system_r" { - t.Errorf("DupSecOpt Failed role incorrect") - } - continue - } - if con[1] == "type" { - if con[2] != "svirt_lxc_net_t" { - t.Errorf("DupSecOpt Failed type incorrect") - } - continue - } - if con[1] == "level" { - if con[2] != "s0:c1,c2" { - t.Errorf("DupSecOpt Failed level incorrect") - } - continue - } - t.Errorf("DupSecOpt Failed invalid field %q", con[1]) - } - secopt = DisableSecOpt() - if secopt[0] != "label:disable" { - t.Errorf("DisableSecOpt Failed level incorrect") - } -} -func TestRelabel(t *testing.T) { - testdir := "/tmp/test" - label := "system_u:system_r:svirt_sandbox_file_t:s0:c1,c2" - if err := Relabel(testdir, "", "z"); err != nil { - t.Fatal("Relabel with no label failed: %v", err) - } - if err := Relabel(testdir, label, ""); err != nil { - t.Fatal("Relabel with no relabel field failed: %v", err) - } - if err := Relabel(testdir, label, "z"); err != nil { - t.Fatal("Relabel shared failed: %v", err) - } - if err := Relabel(testdir, label, "Z"); err != nil { - t.Fatal("Relabel unshared failed: %v", err) - } - if err := Relabel(testdir, label, "zZ"); err == nil { - t.Fatal("Relabel with shared and unshared succeeded: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/netlink/netlink_linux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/netlink/netlink_linux_test.go deleted file mode 100644 index 3f6511abfe8..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/netlink/netlink_linux_test.go +++ /dev/null @@ -1,408 +0,0 @@ -package netlink - -import ( - "net" - "strings" - "syscall" - "testing" -) - -type testLink struct { - name string - linkType string -} - -func addLink(t *testing.T, name string, linkType string) { - if err := NetworkLinkAdd(name, linkType); err != nil { - t.Fatalf("Unable to create %s link: %s", name, err) - } -} - -func readLink(t *testing.T, name string) *net.Interface { - iface, err := net.InterfaceByName(name) - if err != nil { - t.Fatalf("Could not find %s interface: %s", name, err) - } - - return iface -} - -func deleteLink(t *testing.T, name string) { - if err := NetworkLinkDel(name); err != nil { - t.Fatalf("Unable to delete %s link: %s", name, err) - } -} - -func upLink(t *testing.T, name string) { - iface := readLink(t, name) - if err := NetworkLinkUp(iface); err != nil { - t.Fatalf("Could not bring UP %#v interface: %s", iface, err) - } -} - -func downLink(t *testing.T, name string) { - iface := readLink(t, name) - if err := NetworkLinkDown(iface); err != nil { - t.Fatalf("Could not bring DOWN %#v interface: %s", iface, err) - } -} - -func ipAssigned(iface *net.Interface, ip net.IP) bool { - addrs, _ := iface.Addrs() - - for _, addr := range addrs { - args := strings.SplitN(addr.String(), "/", 2) - if args[0] == ip.String() { - return true - } - } - - return false -} - -func TestNetworkLinkAddDel(t *testing.T) { - if testing.Short() { - return - } - - testLinks := []testLink{ - {"tstEth", "dummy"}, - {"tstBr", "bridge"}, - } - - for _, tl := range testLinks { - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - readLink(t, tl.name) - } -} - -func TestNetworkLinkUpDown(t *testing.T) { - if testing.Short() { - return - } - - tl := testLink{name: "tstEth", linkType: "dummy"} - - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - - upLink(t, tl.name) - ifcAfterUp := readLink(t, tl.name) - - if (ifcAfterUp.Flags & syscall.IFF_UP) != syscall.IFF_UP { - t.Fatalf("Could not bring UP %#v initerface", tl) - } - - downLink(t, tl.name) - ifcAfterDown := readLink(t, tl.name) - - if (ifcAfterDown.Flags & syscall.IFF_UP) == syscall.IFF_UP { - t.Fatalf("Could not bring DOWN %#v initerface", tl) - } -} - -func TestNetworkSetMacAddress(t *testing.T) { - if testing.Short() { - return - } - - tl := testLink{name: "tstEth", linkType: "dummy"} - macaddr := "22:ce:e0:99:63:6f" - - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - - ifcBeforeSet := readLink(t, tl.name) - - if err := NetworkSetMacAddress(ifcBeforeSet, macaddr); err != nil { - t.Fatalf("Could not set %s MAC address on %#v interface: %s", macaddr, tl, err) - } - - ifcAfterSet := readLink(t, tl.name) - - if ifcAfterSet.HardwareAddr.String() != macaddr { - t.Fatalf("Could not set %s MAC address on %#v interface", macaddr, tl) - } -} - -func TestNetworkSetMTU(t *testing.T) { - if testing.Short() { - return - } - - tl := testLink{name: "tstEth", linkType: "dummy"} - mtu := 1400 - - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - - ifcBeforeSet := readLink(t, tl.name) - - if err := NetworkSetMTU(ifcBeforeSet, mtu); err != nil { - t.Fatalf("Could not set %d MTU on %#v interface: %s", mtu, tl, err) - } - - ifcAfterSet := readLink(t, tl.name) - - if ifcAfterSet.MTU != mtu { - t.Fatalf("Could not set %d MTU on %#v interface", mtu, tl) - } -} - -func TestNetworkSetMasterNoMaster(t *testing.T) { - if testing.Short() { - return - } - - master := testLink{"tstBr", "bridge"} - slave := testLink{"tstEth", "dummy"} - testLinks := []testLink{master, slave} - - for _, tl := range testLinks { - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - upLink(t, tl.name) - } - - masterIfc := readLink(t, master.name) - slaveIfc := readLink(t, slave.name) - if err := NetworkSetMaster(slaveIfc, masterIfc); err != nil { - t.Fatalf("Could not set %#v to be the master of %#v: %s", master, slave, err) - } - - // Trying to figure out a way to test which will not break on RHEL6. - // We could check for existence of /sys/class/net/tstEth/upper_tstBr - // which should point to the ../tstBr which is the UPPER device i.e. network bridge - - if err := NetworkSetNoMaster(slaveIfc); err != nil { - t.Fatalf("Could not UNset %#v master of %#v: %s", master, slave, err) - } -} - -func TestNetworkChangeName(t *testing.T) { - if testing.Short() { - return - } - - tl := testLink{"tstEth", "dummy"} - newName := "newTst" - - addLink(t, tl.name, tl.linkType) - - linkIfc := readLink(t, tl.name) - if err := NetworkChangeName(linkIfc, newName); err != nil { - deleteLink(t, tl.name) - t.Fatalf("Could not change %#v interface name to %s: %s", tl, newName, err) - } - - readLink(t, newName) - deleteLink(t, newName) -} - -func TestNetworkLinkAddVlan(t *testing.T) { - if testing.Short() { - return - } - - tl := struct { - name string - id uint16 - }{ - name: "tstVlan", - id: 32, - } - masterLink := testLink{"tstEth", "dummy"} - - addLink(t, masterLink.name, masterLink.linkType) - defer deleteLink(t, masterLink.name) - - if err := NetworkLinkAddVlan(masterLink.name, tl.name, tl.id); err != nil { - t.Fatalf("Unable to create %#v VLAN interface: %s", tl, err) - } - - readLink(t, tl.name) -} - -func TestNetworkLinkAddMacVlan(t *testing.T) { - if testing.Short() { - return - } - - tl := struct { - name string - mode string - }{ - name: "tstVlan", - mode: "private", - } - masterLink := testLink{"tstEth", "dummy"} - - addLink(t, masterLink.name, masterLink.linkType) - defer deleteLink(t, masterLink.name) - - if err := NetworkLinkAddMacVlan(masterLink.name, tl.name, tl.mode); err != nil { - t.Fatalf("Unable to create %#v MAC VLAN interface: %s", tl, err) - } - - readLink(t, tl.name) -} - -func TestNetworkLinkAddMacVtap(t *testing.T) { - if testing.Short() { - return - } - - tl := struct { - name string - mode string - }{ - name: "tstVtap", - mode: "private", - } - masterLink := testLink{"tstEth", "dummy"} - - addLink(t, masterLink.name, masterLink.linkType) - defer deleteLink(t, masterLink.name) - - if err := NetworkLinkAddMacVtap(masterLink.name, tl.name, tl.mode); err != nil { - t.Fatalf("Unable to create %#v MAC VTAP interface: %s", tl, err) - } - - readLink(t, tl.name) -} - -func TestAddDelNetworkIp(t *testing.T) { - if testing.Short() { - return - } - - ifaceName := "lo" - ip := net.ParseIP("127.0.1.1") - mask := net.IPv4Mask(255, 255, 255, 255) - ipNet := &net.IPNet{IP: ip, Mask: mask} - - iface, err := net.InterfaceByName(ifaceName) - if err != nil { - t.Skip("No 'lo' interface; skipping tests") - } - - if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil { - t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err) - } - - if !ipAssigned(iface, ip) { - t.Fatalf("Could not locate address '%s' in lo address list.", ip.String()) - } - - if err := NetworkLinkDelIp(iface, ip, ipNet); err != nil { - t.Fatalf("Could not delete IP address %s from interface %#v: %s", ip.String(), iface, err) - } - - if ipAssigned(iface, ip) { - t.Fatalf("Located address '%s' in lo address list after removal.", ip.String()) - } -} - -func TestAddRouteSourceSelection(t *testing.T) { - tstIp := "127.1.1.1" - tl := testLink{name: "tstEth", linkType: "dummy"} - - addLink(t, tl.name, tl.linkType) - defer deleteLink(t, tl.name) - - ip := net.ParseIP(tstIp) - mask := net.IPv4Mask(255, 255, 255, 255) - ipNet := &net.IPNet{IP: ip, Mask: mask} - - iface, err := net.InterfaceByName(tl.name) - if err != nil { - t.Fatalf("Lost created link %#v", tl) - } - - if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil { - t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err) - } - - upLink(t, tl.name) - defer downLink(t, tl.name) - - if err := AddRoute("127.0.0.0/8", tstIp, "", tl.name); err != nil { - t.Fatalf("Failed to add route with source address") - } -} - -func TestCreateVethPair(t *testing.T) { - if testing.Short() { - return - } - - var ( - name1 = "veth1" - name2 = "veth2" - ) - - if err := NetworkCreateVethPair(name1, name2, 0); err != nil { - t.Fatalf("Could not create veth pair %s %s: %s", name1, name2, err) - } - defer NetworkLinkDel(name1) - - readLink(t, name1) - readLink(t, name2) -} - -// -// netlink package tests which do not use RTNETLINK -// -func TestCreateBridgeWithMac(t *testing.T) { - if testing.Short() { - return - } - - name := "testbridge" - - if err := CreateBridge(name, true); err != nil { - t.Fatal(err) - } - - if _, err := net.InterfaceByName(name); err != nil { - t.Fatal(err) - } - - // cleanup and tests - - if err := DeleteBridge(name); err != nil { - t.Fatal(err) - } - - if _, err := net.InterfaceByName(name); err == nil { - t.Fatalf("expected error getting interface because %s bridge was deleted", name) - } -} - -func TestSetMacAddress(t *testing.T) { - if testing.Short() { - return - } - - name := "testmac" - mac := randMacAddr() - - if err := NetworkLinkAdd(name, "bridge"); err != nil { - t.Fatal(err) - } - defer NetworkLinkDel(name) - - if err := SetMacAddress(name, mac); err != nil { - t.Fatal(err) - } - - iface, err := net.InterfaceByName(name) - if err != nil { - t.Fatal(err) - } - - if iface.HardwareAddr.String() != mac { - t.Fatalf("mac address %q does not match %q", iface.HardwareAddr, mac) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/notify_linux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/notify_linux_test.go deleted file mode 100644 index 09bdf64432a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/notify_linux_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build linux - -package libcontainer - -import ( - "encoding/binary" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" - "time" -) - -func TestNotifyOnOOM(t *testing.T) { - memoryPath, err := ioutil.TempDir("", "testnotifyoom-") - if err != nil { - t.Fatal(err) - } - oomPath := filepath.Join(memoryPath, "memory.oom_control") - eventPath := filepath.Join(memoryPath, "cgroup.event_control") - if err := ioutil.WriteFile(oomPath, []byte{}, 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(eventPath, []byte{}, 0700); err != nil { - t.Fatal(err) - } - var eventFd, oomControlFd int - paths := map[string]string{ - "memory": memoryPath, - } - ooms, err := notifyOnOOM(paths) - if err != nil { - t.Fatal("expected no error, got:", err) - } - - data, err := ioutil.ReadFile(eventPath) - if err != nil { - t.Fatal("couldn't read event control file:", err) - } - - if _, err := fmt.Sscanf(string(data), "%d %d", &eventFd, &oomControlFd); err != nil { - t.Fatalf("invalid control data %q: %s", data, err) - } - - // re-open the eventfd - efd, err := syscall.Dup(eventFd) - if err != nil { - t.Fatal("unable to reopen eventfd:", err) - } - defer syscall.Close(efd) - - if err != nil { - t.Fatal("unable to dup event fd:", err) - } - - buf := make([]byte, 8) - binary.LittleEndian.PutUint64(buf, 1) - - if _, err := syscall.Write(efd, buf); err != nil { - t.Fatal("unable to write to eventfd:", err) - } - - select { - case <-ooms: - case <-time.After(100 * time.Millisecond): - t.Fatal("no notification on oom channel after 100ms") - } - - // simulate what happens when a cgroup is destroyed by cleaning up and then - // writing to the eventfd. - if err := os.RemoveAll(memoryPath); err != nil { - t.Fatal(err) - } - if _, err := syscall.Write(efd, buf); err != nil { - t.Fatal("unable to write to eventfd:", err) - } - - // give things a moment to shut down - select { - case _, ok := <-ooms: - if ok { - t.Fatal("expected no oom to be triggered") - } - case <-time.After(100 * time.Millisecond): - } - - if _, _, err := syscall.Syscall(syscall.SYS_FCNTL, uintptr(oomControlFd), syscall.F_GETFD, 0); err != syscall.EBADF { - t.Error("expected oom control to be closed") - } - - if _, _, err := syscall.Syscall(syscall.SYS_FCNTL, uintptr(eventFd), syscall.F_GETFD, 0); err != syscall.EBADF { - t.Error("expected event fd to be closed") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/nsenter/nsenter_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/nsenter/nsenter_test.go deleted file mode 100644 index db27b8a4099..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/nsenter/nsenter_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package nsenter - -import ( - "encoding/json" - "fmt" - "os" - "os/exec" - "strings" - "testing" -) - -type pid struct { - Pid int `json:"Pid"` -} - -func TestNsenterAlivePid(t *testing.T) { - args := []string{"nsenter-exec"} - r, w, err := os.Pipe() - if err != nil { - t.Fatalf("failed to create pipe %v", err) - } - - cmd := &exec.Cmd{ - Path: os.Args[0], - Args: args, - ExtraFiles: []*os.File{w}, - Env: []string{fmt.Sprintf("_LIBCONTAINER_INITPID=%d", os.Getpid()), "_LIBCONTAINER_INITPIPE=3"}, - } - - if err := cmd.Start(); err != nil { - t.Fatalf("nsenter failed to start %v", err) - } - w.Close() - - decoder := json.NewDecoder(r) - var pid *pid - - if err := decoder.Decode(&pid); err != nil { - t.Fatalf("%v", err) - } - - if err := cmd.Wait(); err != nil { - t.Fatalf("nsenter exits with a non-zero exit status") - } - p, err := os.FindProcess(pid.Pid) - if err != nil { - t.Fatalf("%v", err) - } - p.Wait() -} - -func TestNsenterInvalidPid(t *testing.T) { - args := []string{"nsenter-exec"} - - cmd := &exec.Cmd{ - Path: os.Args[0], - Args: args, - Env: []string{"_LIBCONTAINER_INITPID=-1"}, - } - - err := cmd.Run() - if err == nil { - t.Fatal("nsenter exits with a zero exit status") - } -} - -func TestNsenterDeadPid(t *testing.T) { - dead_cmd := exec.Command("true") - if err := dead_cmd.Run(); err != nil { - t.Fatal(err) - } - args := []string{"nsenter-exec"} - - cmd := &exec.Cmd{ - Path: os.Args[0], - Args: args, - Env: []string{fmt.Sprintf("_LIBCONTAINER_INITPID=%d", dead_cmd.Process.Pid)}, - } - - err := cmd.Run() - if err == nil { - t.Fatal("nsenter exits with a zero exit status") - } -} - -func init() { - if strings.HasPrefix(os.Args[0], "nsenter-") { - os.Exit(0) - } - return -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/selinux/selinux_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/selinux/selinux_test.go deleted file mode 100644 index 228ad8361c8..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/selinux/selinux_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build linux - -package selinux_test - -import ( - "os" - "testing" - - "github.com/docker/libcontainer/selinux" -) - -func testSetfilecon(t *testing.T) { - if selinux.SelinuxEnabled() { - tmp := "selinux_test" - out, _ := os.OpenFile(tmp, os.O_WRONLY, 0) - out.Close() - err := selinux.Setfilecon(tmp, "system_u:object_r:bin_t:s0") - if err != nil { - t.Log("Setfilecon failed") - t.Fatal(err) - } - os.Remove(tmp) - } -} - -func TestSELinux(t *testing.T) { - var ( - err error - plabel, flabel string - ) - - if selinux.SelinuxEnabled() { - t.Log("Enabled") - plabel, flabel = selinux.GetLxcContexts() - t.Log(plabel) - t.Log(flabel) - selinux.FreeLxcContexts(plabel) - plabel, flabel = selinux.GetLxcContexts() - t.Log(plabel) - t.Log(flabel) - selinux.FreeLxcContexts(plabel) - t.Log("getenforce ", selinux.SelinuxGetEnforce()) - t.Log("getenforcemode ", selinux.SelinuxGetEnforceMode()) - pid := os.Getpid() - t.Logf("PID:%d MCS:%s\n", pid, selinux.IntToMcs(pid, 1023)) - err = selinux.Setfscreatecon("unconfined_u:unconfined_r:unconfined_t:s0") - if err == nil { - t.Log(selinux.Getfscreatecon()) - } else { - t.Log("setfscreatecon failed", err) - t.Fatal(err) - } - err = selinux.Setfscreatecon("") - if err == nil { - t.Log(selinux.Getfscreatecon()) - } else { - t.Log("setfscreatecon failed", err) - t.Fatal(err) - } - t.Log(selinux.Getpidcon(1)) - } else { - t.Log("Disabled") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/capture_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/capture_test.go deleted file mode 100644 index 3f435d51a64..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/capture_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package stacktrace - -import "testing" - -func captureFunc() Stacktrace { - return Capture(0) -} - -func TestCaptureTestFunc(t *testing.T) { - stack := captureFunc() - - if len(stack.Frames) == 0 { - t.Fatal("expected stack frames to be returned") - } - - // the first frame is the caller - frame := stack.Frames[0] - if expected := "captureFunc"; frame.Function != expected { - t.Fatalf("expteced function %q but recevied %q", expected, frame.Function) - } - if expected := "github.com/docker/libcontainer/stacktrace"; frame.Package != expected { - t.Fatalf("expected package %q but received %q", expected, frame.Package) - } - if expected := "capture_test.go"; frame.File != expected { - t.Fatalf("expected file %q but received %q", expected, frame.File) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/frame_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/frame_test.go deleted file mode 100644 index ae95ec4847d..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/stacktrace/frame_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package stacktrace - -import "testing" - -func TestParsePackageName(t *testing.T) { - var ( - name = "github.com/docker/libcontainer/stacktrace.captureFunc" - expectedPackage = "github.com/docker/libcontainer/stacktrace" - expectedFunction = "captureFunc" - ) - - pack, funcName := parseFunctionName(name) - if pack != expectedPackage { - t.Fatalf("expected package %q but received %q", expectedPackage, pack) - } - - if funcName != expectedFunction { - t.Fatalf("expected function %q but received %q", expectedFunction, funcName) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/user/user_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/user/user_test.go deleted file mode 100644 index 4fe008fb397..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/user/user_test.go +++ /dev/null @@ -1,352 +0,0 @@ -package user - -import ( - "io" - "reflect" - "strings" - "testing" -) - -func TestUserParseLine(t *testing.T) { - var ( - a, b string - c []string - d int - ) - - parseLine("", &a, &b) - if a != "" || b != "" { - t.Fatalf("a and b should be empty ('%v', '%v')", a, b) - } - - parseLine("a", &a, &b) - if a != "a" || b != "" { - t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) - } - - parseLine("bad boys:corny cows", &a, &b) - if a != "bad boys" || b != "corny cows" { - t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) - } - - parseLine("", &c) - if len(c) != 0 { - t.Fatalf("c should be empty (%#v)", c) - } - - parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) - if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { - t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("::::::::::", &a, &b, &c) - if a != "" || b != "" || len(c) != 0 { - t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("not a number", &d) - if d != 0 { - t.Fatalf("d should be 0 (%v)", d) - } - - parseLine("b:12:c", &a, &d, &b) - if a != "b" || b != "c" || d != 12 { - t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) - } -} - -func TestUserParsePasswd(t *testing.T) { - users, err := ParsePasswdFilter(strings.NewReader(` -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm:/bin/false -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(users) != 3 { - t.Fatalf("Expected 3 users, got %v", len(users)) - } - if users[0].Uid != 0 || users[0].Name != "root" { - t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) - } - if users[1].Uid != 3 || users[1].Name != "adm" { - t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) - } -} - -func TestUserParseGroup(t *testing.T) { - groups, err := ParseGroupFilter(strings.NewReader(` -root:x:0:root -adm:x:4:root,adm,daemon -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(groups) != 3 { - t.Fatalf("Expected 3 groups, got %v", len(groups)) - } - if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { - t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) - } - if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { - t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) - } -} - -func TestValidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - expected ExecUser - }{ - { - ref: "root", - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{0, 1234}, - Home: "/root", - }, - }, - { - ref: "adm", - expected: ExecUser{ - Uid: 42, - Gid: 43, - Sgids: []int{1234}, - Home: "/var/adm", - }, - }, - { - ref: "root:adm", - expected: ExecUser{ - Uid: 0, - Gid: 43, - Sgids: defaultExecUser.Sgids, - Home: "/root", - }, - }, - { - ref: "adm:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "42:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "1337:1234", - expected: ExecUser{ - Uid: 1337, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "1337", - expected: ExecUser{ - Uid: 1337, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "", - expected: ExecUser{ - Uid: defaultExecUser.Uid, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestInvalidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - tests := []string{ - // No such user/group. - "notuser", - "notuser:notgroup", - "root:notgroup", - "notuser:adm", - "8888:notgroup", - "notuser:8888", - - // Invalid user/group values. - "-1:0", - "0:-3", - "-5:-2", - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test, nil, passwd, group) - if err == nil { - t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) - t.Fail() - continue - } - } -} - -func TestGetExecUserNilSources(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - passwd, group bool - expected ExecUser - }{ - { - ref: "", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "root", - passwd: true, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/root", - }, - }, - { - ref: "0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "0:0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - } - - for _, test := range tests { - var passwd, group io.Reader - - if test.passwd { - passwd = strings.NewReader(passwdContent) - } - - if test.group { - group = strings.NewReader(groupContent) - } - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/utils/utils_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/utils/utils_test.go deleted file mode 100644 index 41ef1aa3df5..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/utils/utils_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package utils - -import "testing" - -func TestGenerateName(t *testing.T) { - name, err := GenerateRandomName("veth", 5) - if err != nil { - t.Fatal(err) - } - - expected := 5 + len("veth") - if len(name) != 5+len("veth") { - t.Fatalf("expected name to be %d chars but received %d", expected, len(name)) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/entry_test.go deleted file mode 100644 index 98717df4901..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index 77989da6297..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package logrus - -import ( - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hook_test.go deleted file mode 100644 index 13f34cb6f81..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go deleted file mode 100644 index 96318d00304..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_papertrail - -import ( - "fmt" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/stvp/go-udp-testing" -) - -func TestWritingToUDP(t *testing.T) { - port := 16661 - udp.SetAddr(fmt.Sprintf(":%d", port)) - - hook, err := NewPapertrailHook("localhost", port, "test") - if err != nil { - t.Errorf("Unable to connect to local UDP server.") - } - - log := logrus.New() - log.Hooks.Add(hook) - - udp.ShouldReceive(t, "foo", func() { - log.Info("foo") - }) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go deleted file mode 100644 index 45f18d17047..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package logrus_sentry - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/getsentry/raven-go" -) - -const ( - message = "error message" - server_name = "testserver.internal" - logger_name = "test.logger" -) - -func getTestLogger() *logrus.Logger { - l := logrus.New() - l.Out = ioutil.Discard - return l -} - -func WithTestDSN(t *testing.T, tf func(string, <-chan *raven.Packet)) { - pch := make(chan *raven.Packet, 1) - s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - defer req.Body.Close() - d := json.NewDecoder(req.Body) - p := &raven.Packet{} - err := d.Decode(p) - if err != nil { - t.Fatal(err.Error()) - } - - pch <- p - })) - defer s.Close() - - fragments := strings.SplitN(s.URL, "://", 2) - dsn := fmt.Sprintf( - "%s://public:secret@%s/sentry/project-id", - fragments[0], - fragments[1], - ) - tf(dsn, pch) -} - -func TestSpecialFields(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - logger.WithFields(logrus.Fields{ - "server_name": server_name, - "logger": logger_name, - }).Error(message) - - packet := <-pch - if packet.Logger != logger_name { - t.Errorf("logger should have been %s, was %s", logger_name, packet.Logger) - } - - if packet.ServerName != server_name { - t.Errorf("server_name should have been %s, was %s", server_name, packet.ServerName) - } - }) -} - -func TestSentryHandler(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - - logger.Error(message) - packet := <-pch - if packet.Message != message { - t.Errorf("message should have been %s, was %s", message, packet.Message) - } - }) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go deleted file mode 100644 index 42762dc10d7..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_syslog - -import ( - "github.com/Sirupsen/logrus" - "log/syslog" - "testing" -) - -func TestLocalhostAddAndPrint(t *testing.T) { - log := logrus.New() - hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - - if err != nil { - t.Errorf("Unable to connect to local syslog.") - } - - log.Hooks.Add(hook) - - for _, level := range hook.Levels() { - if len(log.Hooks[level]) != 1 { - t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level])) - } - } - - log.Info("Congratulations!") -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/json_formatter_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/json_formatter_test.go deleted file mode 100644 index 1d70873254d..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/json_formatter_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package logrus - -import ( - "encoding/json" - "errors" - - "testing" -) - -func TestErrorNotLost(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["omg"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestFieldClashWithTime(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("time", "right now!")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.time"] != "right now!" { - t.Fatal("fields.time not set to original time field") - } - - if entry["time"] != "0001-01-01T00:00:00Z" { - t.Fatal("time field not set to current time, was: ", entry["time"]) - } -} - -func TestFieldClashWithMsg(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("msg", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.msg"] != "something" { - t.Fatal("fields.msg not set to original msg field") - } -} - -func TestFieldClashWithLevel(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.level"] != "something" { - t.Fatal("fields.level not set to original level field") - } -} - -func TestJSONEntryEndsWithNewline(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - if b[len(b)-1] != '\n' { - t.Fatal("Expected JSON log entry to end with a newline") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/logrus_test.go deleted file mode 100644 index d85dba4dcbb..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "sync" - "testing" - - "github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1) - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} - -func TestGetSetLevelRace(t *testing.T) { - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i%2 == 0 { - SetLevel(InfoLevel) - } else { - GetLevel() - } - }(i) - - } - wg.Wait() -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index 28a94990796..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/Sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - - "testing" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(false, "1234567890") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} - -// TODO add tests for sorting etc., this requires a parser for the text -// formatter output. diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/app_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/app_test.go deleted file mode 100644 index a9156241032..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/app_test.go +++ /dev/null @@ -1,399 +0,0 @@ -package cli_test - -import ( - "fmt" - "os" - "testing" - - "github.com/codegangsta/cli" -) - -func ExampleApp() { - // set args for examples sake - os.Args = []string{"greet", "--name", "Jeremy"} - - app := cli.NewApp() - app.Name = "greet" - app.Flags = []cli.Flag{ - cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"}, - } - app.Action = func(c *cli.Context) { - fmt.Printf("Hello %v\n", c.String("name")) - } - app.Run(os.Args) - // Output: - // Hello Jeremy -} - -func ExampleAppSubcommand() { - // set args for examples sake - os.Args = []string{"say", "hi", "english", "--name", "Jeremy"} - app := cli.NewApp() - app.Name = "say" - app.Commands = []cli.Command{ - { - Name: "hello", - ShortName: "hi", - Usage: "use it to see a description", - Description: "This is how we describe hello the function", - Subcommands: []cli.Command{ - { - Name: "english", - ShortName: "en", - Usage: "sends a greeting in english", - Description: "greets someone in english", - Flags: []cli.Flag{ - cli.StringFlag{Name: "name", Value: "Bob", Usage: "Name of the person to greet"}, - }, - Action: func(c *cli.Context) { - fmt.Println("Hello,", c.String("name")) - }, - }, - }, - }, - } - - app.Run(os.Args) - // Output: - // Hello, Jeremy -} - -func ExampleAppHelp() { - // set args for examples sake - os.Args = []string{"greet", "h", "describeit"} - - app := cli.NewApp() - app.Name = "greet" - app.Flags = []cli.Flag{ - cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"}, - } - app.Commands = []cli.Command{ - { - Name: "describeit", - ShortName: "d", - Usage: "use it to see a description", - Description: "This is how we describe describeit the function", - Action: func(c *cli.Context) { - fmt.Printf("i like to describe things") - }, - }, - } - app.Run(os.Args) - // Output: - // NAME: - // describeit - use it to see a description - // - // USAGE: - // command describeit [arguments...] - // - // DESCRIPTION: - // This is how we describe describeit the function -} - -func ExampleAppBashComplete() { - // set args for examples sake - os.Args = []string{"greet", "--generate-bash-completion"} - - app := cli.NewApp() - app.Name = "greet" - app.EnableBashCompletion = true - app.Commands = []cli.Command{ - { - Name: "describeit", - ShortName: "d", - Usage: "use it to see a description", - Description: "This is how we describe describeit the function", - Action: func(c *cli.Context) { - fmt.Printf("i like to describe things") - }, - }, { - Name: "next", - Usage: "next example", - Description: "more stuff to see when generating bash completion", - Action: func(c *cli.Context) { - fmt.Printf("the next example") - }, - }, - } - - app.Run(os.Args) - // Output: - // describeit - // d - // next - // help - // h -} - -func TestApp_Run(t *testing.T) { - s := "" - - app := cli.NewApp() - app.Action = func(c *cli.Context) { - s = s + c.Args().First() - } - - err := app.Run([]string{"command", "foo"}) - expect(t, err, nil) - err = app.Run([]string{"command", "bar"}) - expect(t, err, nil) - expect(t, s, "foobar") -} - -var commandAppTests = []struct { - name string - expected bool -}{ - {"foobar", true}, - {"batbaz", true}, - {"b", true}, - {"f", true}, - {"bat", false}, - {"nothing", false}, -} - -func TestApp_Command(t *testing.T) { - app := cli.NewApp() - fooCommand := cli.Command{Name: "foobar", ShortName: "f"} - batCommand := cli.Command{Name: "batbaz", ShortName: "b"} - app.Commands = []cli.Command{ - fooCommand, - batCommand, - } - - for _, test := range commandAppTests { - expect(t, app.Command(test.name) != nil, test.expected) - } -} - -func TestApp_CommandWithArgBeforeFlags(t *testing.T) { - var parsedOption, firstArg string - - app := cli.NewApp() - command := cli.Command{ - Name: "cmd", - Flags: []cli.Flag{ - cli.StringFlag{Name: "option", Value: "", Usage: "some option"}, - }, - Action: func(c *cli.Context) { - parsedOption = c.String("option") - firstArg = c.Args().First() - }, - } - app.Commands = []cli.Command{command} - - app.Run([]string{"", "cmd", "my-arg", "--option", "my-option"}) - - expect(t, parsedOption, "my-option") - expect(t, firstArg, "my-arg") -} - -func TestApp_Float64Flag(t *testing.T) { - var meters float64 - - app := cli.NewApp() - app.Flags = []cli.Flag{ - cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"}, - } - app.Action = func(c *cli.Context) { - meters = c.Float64("height") - } - - app.Run([]string{"", "--height", "1.93"}) - expect(t, meters, 1.93) -} - -func TestApp_ParseSliceFlags(t *testing.T) { - var parsedOption, firstArg string - var parsedIntSlice []int - var parsedStringSlice []string - - app := cli.NewApp() - command := cli.Command{ - Name: "cmd", - Flags: []cli.Flag{ - cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"}, - cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"}, - }, - Action: func(c *cli.Context) { - parsedIntSlice = c.IntSlice("p") - parsedStringSlice = c.StringSlice("ip") - parsedOption = c.String("option") - firstArg = c.Args().First() - }, - } - app.Commands = []cli.Command{command} - - app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"}) - - IntsEquals := func(a, b []int) bool { - if len(a) != len(b) { - return false - } - for i, v := range a { - if v != b[i] { - return false - } - } - return true - } - - StrsEquals := func(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i, v := range a { - if v != b[i] { - return false - } - } - return true - } - var expectedIntSlice = []int{22, 80} - var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"} - - if !IntsEquals(parsedIntSlice, expectedIntSlice) { - t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice) - } - - if !StrsEquals(parsedStringSlice, expectedStringSlice) { - t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice) - } -} - -func TestApp_BeforeFunc(t *testing.T) { - beforeRun, subcommandRun := false, false - beforeError := fmt.Errorf("fail") - var err error - - app := cli.NewApp() - - app.Before = func(c *cli.Context) error { - beforeRun = true - s := c.String("opt") - if s == "fail" { - return beforeError - } - - return nil - } - - app.Commands = []cli.Command{ - cli.Command{ - Name: "sub", - Action: func(c *cli.Context) { - subcommandRun = true - }, - }, - } - - app.Flags = []cli.Flag{ - cli.StringFlag{Name: "opt"}, - } - - // run with the Before() func succeeding - err = app.Run([]string{"command", "--opt", "succeed", "sub"}) - - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if beforeRun == false { - t.Errorf("Before() not executed when expected") - } - - if subcommandRun == false { - t.Errorf("Subcommand not executed when expected") - } - - // reset - beforeRun, subcommandRun = false, false - - // run with the Before() func failing - err = app.Run([]string{"command", "--opt", "fail", "sub"}) - - // should be the same error produced by the Before func - if err != beforeError { - t.Errorf("Run error expected, but not received") - } - - if beforeRun == false { - t.Errorf("Before() not executed when expected") - } - - if subcommandRun == true { - t.Errorf("Subcommand executed when NOT expected") - } - -} - -func TestAppHelpPrinter(t *testing.T) { - oldPrinter := cli.HelpPrinter - defer func() { - cli.HelpPrinter = oldPrinter - }() - - var wasCalled = false - cli.HelpPrinter = func(template string, data interface{}) { - wasCalled = true - } - - app := cli.NewApp() - app.Run([]string{"-h"}) - - if wasCalled == false { - t.Errorf("Help printer expected to be called, but was not") - } -} - -func TestAppCommandNotFound(t *testing.T) { - beforeRun, subcommandRun := false, false - app := cli.NewApp() - - app.CommandNotFound = func(c *cli.Context, command string) { - beforeRun = true - } - - app.Commands = []cli.Command{ - cli.Command{ - Name: "bar", - Action: func(c *cli.Context) { - subcommandRun = true - }, - }, - } - - app.Run([]string{"command", "foo"}) - - expect(t, beforeRun, true) - expect(t, subcommandRun, false) -} - -func TestGlobalFlagsInSubcommands(t *testing.T) { - subcommandRun := false - app := cli.NewApp() - - app.Flags = []cli.Flag{ - cli.BoolFlag{Name: "debug, d", Usage: "Enable debugging"}, - } - - app.Commands = []cli.Command{ - cli.Command{ - Name: "foo", - Subcommands: []cli.Command{ - { - Name: "bar", - Action: func(c *cli.Context) { - if c.GlobalBool("debug") { - subcommandRun = true - } - }, - }, - }, - }, - } - - app.Run([]string{"command", "-d", "foo", "bar"}) - - expect(t, subcommandRun, true) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/cli_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/cli_test.go deleted file mode 100644 index 4d7bd8479a4..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/cli_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package cli_test - -import ( - "os" - - "github.com/codegangsta/cli" -) - -func Example() { - app := cli.NewApp() - app.Name = "todo" - app.Usage = "task list on the command line" - app.Commands = []cli.Command{ - { - Name: "add", - ShortName: "a", - Usage: "add a task to the list", - Action: func(c *cli.Context) { - println("added task: ", c.Args().First()) - }, - }, - { - Name: "complete", - ShortName: "c", - Usage: "complete a task on the list", - Action: func(c *cli.Context) { - println("completed task: ", c.Args().First()) - }, - }, - } - - app.Run(os.Args) -} - -func ExampleSubcommand() { - app := cli.NewApp() - app.Name = "say" - app.Commands = []cli.Command{ - { - Name: "hello", - ShortName: "hi", - Usage: "use it to see a description", - Description: "This is how we describe hello the function", - Subcommands: []cli.Command{ - { - Name: "english", - ShortName: "en", - Usage: "sends a greeting in english", - Description: "greets someone in english", - Flags: []cli.Flag{ - cli.StringFlag{Name: "name", Value: "Bob", Usage: "Name of the person to greet"}, - }, - Action: func(c *cli.Context) { - println("Hello, ", c.String("name")) - }, - }, { - Name: "spanish", - ShortName: "sp", - Usage: "sends a greeting in spanish", - Flags: []cli.Flag{ - cli.StringFlag{Name: "surname", Value: "Jones", Usage: "Surname of the person to greet"}, - }, - Action: func(c *cli.Context) { - println("Hola, ", c.String("surname")) - }, - }, { - Name: "french", - ShortName: "fr", - Usage: "sends a greeting in french", - Flags: []cli.Flag{ - cli.StringFlag{Name: "nickname", Value: "Stevie", Usage: "Nickname of the person to greet"}, - }, - Action: func(c *cli.Context) { - println("Bonjour, ", c.String("nickname")) - }, - }, - }, - }, { - Name: "bye", - Usage: "says goodbye", - Action: func(c *cli.Context) { - println("bye") - }, - }, - } - - app.Run(os.Args) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/command_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/command_test.go deleted file mode 100644 index 3afd83e7a67..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/command_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package cli_test - -import ( - "flag" - "github.com/codegangsta/cli" - "testing" -) - -func TestCommandDoNotIgnoreFlags(t *testing.T) { - app := cli.NewApp() - set := flag.NewFlagSet("test", 0) - test := []string{"blah", "blah", "-break"} - set.Parse(test) - - c := cli.NewContext(app, set, set) - - command := cli.Command { - Name: "test-cmd", - ShortName: "tc", - Usage: "this is for testing", - Description: "testing", - Action: func(_ *cli.Context) { }, - } - err := command.Run(c) - - expect(t, err.Error(), "flag provided but not defined: -break") -} - -func TestCommandIgnoreFlags(t *testing.T) { - app := cli.NewApp() - set := flag.NewFlagSet("test", 0) - test := []string{"blah", "blah"} - set.Parse(test) - - c := cli.NewContext(app, set, set) - - command := cli.Command { - Name: "test-cmd", - ShortName: "tc", - Usage: "this is for testing", - Description: "testing", - Action: func(_ *cli.Context) { }, - SkipFlagParsing: true, - } - err := command.Run(c) - - expect(t, err, nil) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/context_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/context_test.go deleted file mode 100644 index 89041b99d40..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/context_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package cli_test - -import ( - "flag" - "github.com/codegangsta/cli" - "testing" -) - -func TestNewContext(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Int("myflag", 12, "doc") - globalSet := flag.NewFlagSet("test", 0) - globalSet.Int("myflag", 42, "doc") - command := cli.Command{Name: "mycommand"} - c := cli.NewContext(nil, set, globalSet) - c.Command = command - expect(t, c.Int("myflag"), 12) - expect(t, c.GlobalInt("myflag"), 42) - expect(t, c.Command.Name, "mycommand") -} - -func TestContext_Int(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Int("myflag", 12, "doc") - c := cli.NewContext(nil, set, set) - expect(t, c.Int("myflag"), 12) -} - -func TestContext_String(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.String("myflag", "hello world", "doc") - c := cli.NewContext(nil, set, set) - expect(t, c.String("myflag"), "hello world") -} - -func TestContext_Bool(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Bool("myflag", false, "doc") - c := cli.NewContext(nil, set, set) - expect(t, c.Bool("myflag"), false) -} - -func TestContext_BoolT(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Bool("myflag", true, "doc") - c := cli.NewContext(nil, set, set) - expect(t, c.BoolT("myflag"), true) -} - -func TestContext_Args(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Bool("myflag", false, "doc") - c := cli.NewContext(nil, set, set) - set.Parse([]string{"--myflag", "bat", "baz"}) - expect(t, len(c.Args()), 2) - expect(t, c.Bool("myflag"), true) -} - -func TestContext_IsSet(t *testing.T) { - set := flag.NewFlagSet("test", 0) - set.Bool("myflag", false, "doc") - set.String("otherflag", "hello world", "doc") - c := cli.NewContext(nil, set, set) - set.Parse([]string{"--myflag", "bat", "baz"}) - expect(t, c.IsSet("myflag"), true) - expect(t, c.IsSet("otherflag"), false) - expect(t, c.IsSet("bogusflag"), false) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/flag_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/flag_test.go deleted file mode 100644 index 1c05f0144d4..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/flag_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package cli_test - -import ( - "github.com/codegangsta/cli" - - "fmt" - "reflect" - "strings" - "testing" -) - -var boolFlagTests = []struct { - name string - expected string -}{ - {"help", "--help\t"}, - {"h", "-h\t"}, -} - -func TestBoolFlagHelpOutput(t *testing.T) { - - for _, test := range boolFlagTests { - flag := cli.BoolFlag{Name: test.name} - output := flag.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } - } -} - -var stringFlagTests = []struct { - name string - value string - expected string -}{ - {"help", "", "--help \t"}, - {"h", "", "-h \t"}, - {"h", "", "-h \t"}, - {"test", "Something", "--test 'Something'\t"}, -} - -func TestStringFlagHelpOutput(t *testing.T) { - - for _, test := range stringFlagTests { - flag := cli.StringFlag{Name: test.name, Value: test.value} - output := flag.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } - } -} - -var intFlagTests = []struct { - name string - expected string -}{ - {"help", "--help '0'\t"}, - {"h", "-h '0'\t"}, -} - -func TestIntFlagHelpOutput(t *testing.T) { - - for _, test := range intFlagTests { - flag := cli.IntFlag{Name: test.name} - output := flag.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } - } -} - -var float64FlagTests = []struct { - name string - expected string -}{ - {"help", "--help '0'\t"}, - {"h", "-h '0'\t"}, -} - -func TestFloat64FlagHelpOutput(t *testing.T) { - - for _, test := range float64FlagTests { - flag := cli.Float64Flag{Name: test.name} - output := flag.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } - } -} - -func TestParseMultiString(t *testing.T) { - (&cli.App{ - Flags: []cli.Flag{ - cli.StringFlag{Name: "serve, s"}, - }, - Action: func(ctx *cli.Context) { - if ctx.String("serve") != "10" { - t.Errorf("main name not set") - } - if ctx.String("s") != "10" { - t.Errorf("short name not set") - } - }, - }).Run([]string{"run", "-s", "10"}) -} - -func TestParseMultiStringSlice(t *testing.T) { - (&cli.App{ - Flags: []cli.Flag{ - cli.StringSliceFlag{Name: "serve, s", Value: &cli.StringSlice{}}, - }, - Action: func(ctx *cli.Context) { - if !reflect.DeepEqual(ctx.StringSlice("serve"), []string{"10", "20"}) { - t.Errorf("main name not set") - } - if !reflect.DeepEqual(ctx.StringSlice("s"), []string{"10", "20"}) { - t.Errorf("short name not set") - } - }, - }).Run([]string{"run", "-s", "10", "-s", "20"}) -} - -func TestParseMultiInt(t *testing.T) { - a := cli.App{ - Flags: []cli.Flag{ - cli.IntFlag{Name: "serve, s"}, - }, - Action: func(ctx *cli.Context) { - if ctx.Int("serve") != 10 { - t.Errorf("main name not set") - } - if ctx.Int("s") != 10 { - t.Errorf("short name not set") - } - }, - } - a.Run([]string{"run", "-s", "10"}) -} - -func TestParseMultiBool(t *testing.T) { - a := cli.App{ - Flags: []cli.Flag{ - cli.BoolFlag{Name: "serve, s"}, - }, - Action: func(ctx *cli.Context) { - if ctx.Bool("serve") != true { - t.Errorf("main name not set") - } - if ctx.Bool("s") != true { - t.Errorf("short name not set") - } - }, - } - a.Run([]string{"run", "--serve"}) -} - -type Parser [2]string - -func (p *Parser) Set(value string) error { - parts := strings.Split(value, ",") - if len(parts) != 2 { - return fmt.Errorf("invalid format") - } - - (*p)[0] = parts[0] - (*p)[1] = parts[1] - - return nil -} - -func (p *Parser) String() string { - return fmt.Sprintf("%s,%s", p[0], p[1]) -} - -func TestParseGeneric(t *testing.T) { - a := cli.App{ - Flags: []cli.Flag{ - cli.GenericFlag{Name: "serve, s", Value: &Parser{}}, - }, - Action: func(ctx *cli.Context) { - if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) { - t.Errorf("main name not set") - } - if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) { - t.Errorf("short name not set") - } - }, - } - a.Run([]string{"run", "-s", "10,20"}) -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/helpers_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/helpers_test.go deleted file mode 100644 index cdc4feb2fcd..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/codegangsta/cli/helpers_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package cli_test - -import ( - "reflect" - "testing" -) - -/* Test Helpers */ -func expect(t *testing.T, a interface{}, b interface{}) { - if a != b { - t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} - -func refute(t *testing.T, a interface{}, b interface{}) { - if a == b { - t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/files_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/files_test.go deleted file mode 100644 index a1c6948fb2c..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/files_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2013 CoreOS 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 activation - -import ( - "bytes" - "io" - "os" - "os/exec" - "testing" -) - -// correctStringWritten fails the text if the correct string wasn't written -// to the other side of the pipe. -func correctStringWritten(t *testing.T, r *os.File, expected string) bool { - bytes := make([]byte, len(expected)) - io.ReadAtLeast(r, bytes, len(expected)) - - if string(bytes) != expected { - t.Fatalf("Unexpected string %s", string(bytes)) - } - - return true -} - -// TestActivation forks out a copy of activation.go example and reads back two -// strings from the pipes that are passed in. -func TestActivation(t *testing.T) { - cmd := exec.Command("go", "run", "../examples/activation/activation.go") - - r1, w1, _ := os.Pipe() - r2, w2, _ := os.Pipe() - cmd.ExtraFiles = []*os.File{ - w1, - w2, - } - - cmd.Env = os.Environ() - cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1") - - err := cmd.Run() - if err != nil { - t.Fatalf(err.Error()) - } - - correctStringWritten(t, r1, "Hello world") - correctStringWritten(t, r2, "Goodbye world") -} - -func TestActivationNoFix(t *testing.T) { - cmd := exec.Command("go", "run", "../examples/activation/activation.go") - cmd.Env = os.Environ() - cmd.Env = append(cmd.Env, "LISTEN_FDS=2") - - out, _ := cmd.CombinedOutput() - if bytes.Contains(out, []byte("No files")) == false { - t.Fatalf("Child didn't error out as expected") - } -} - -func TestActivationNoFiles(t *testing.T) { - cmd := exec.Command("go", "run", "../examples/activation/activation.go") - cmd.Env = os.Environ() - cmd.Env = append(cmd.Env, "LISTEN_FDS=0", "FIX_LISTEN_PID=1") - - out, _ := cmd.CombinedOutput() - if bytes.Contains(out, []byte("No files")) == false { - t.Fatalf("Child didn't error out as expected") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/listeners_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/listeners_test.go deleted file mode 100644 index c3627d6d4d8..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/activation/listeners_test.go +++ /dev/null @@ -1,88 +0,0 @@ -/* -Copyright 2014 CoreOS 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 activation - -import ( - "io" - "net" - "os" - "os/exec" - "testing" -) - -// correctStringWritten fails the text if the correct string wasn't written -// to the other side of the pipe. -func correctStringWrittenNet(t *testing.T, r net.Conn, expected string) bool { - bytes := make([]byte, len(expected)) - io.ReadAtLeast(r, bytes, len(expected)) - - if string(bytes) != expected { - t.Fatalf("Unexpected string %s", string(bytes)) - } - - return true -} - -// TestActivation forks out a copy of activation.go example and reads back two -// strings from the pipes that are passed in. -func TestListeners(t *testing.T) { - cmd := exec.Command("go", "run", "../examples/activation/listen.go") - - l1, err := net.Listen("tcp", ":9999") - if err != nil { - t.Fatalf(err.Error()) - } - l2, err := net.Listen("tcp", ":1234") - if err != nil { - t.Fatalf(err.Error()) - } - - t1 := l1.(*net.TCPListener) - t2 := l2.(*net.TCPListener) - - f1, _ := t1.File() - f2, _ := t2.File() - - cmd.ExtraFiles = []*os.File{ - f1, - f2, - } - - r1, err := net.Dial("tcp", "127.0.0.1:9999") - if err != nil { - t.Fatalf(err.Error()) - } - r1.Write([]byte("Hi")) - - r2, err := net.Dial("tcp", "127.0.0.1:1234") - if err != nil { - t.Fatalf(err.Error()) - } - r2.Write([]byte("Hi")) - - cmd.Env = os.Environ() - cmd.Env = append(cmd.Env, "LISTEN_FDS=2", "FIX_LISTEN_PID=1") - - out, err := cmd.Output() - if err != nil { - println(string(out)) - t.Fatalf(err.Error()) - } - - correctStringWrittenNet(t, r1, "Hello world") - correctStringWrittenNet(t, r2, "Goodbye world") -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/dbus_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/dbus_test.go deleted file mode 100644 index 2e80f73ef74..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/dbus_test.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2013 CoreOS 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 dbus - -import ( - "testing" -) - -// TestObjectPath ensures path encoding of the systemd rules works. -func TestObjectPath(t *testing.T) { - input := "/silly-path/to@a/unit..service" - output := ObjectPath(input) - expected := "/silly_2dpath/to_40a/unit_2e_2eservice" - - if string(output) != expected { - t.Fatalf("Output '%s' did not match expected '%s'", output, expected) - } -} - -// TestNew ensures that New() works without errors. -func TestNew(t *testing.T) { - _, err := New() - - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/methods_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/methods_test.go deleted file mode 100644 index 8c7ab93eb36..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/methods_test.go +++ /dev/null @@ -1,332 +0,0 @@ -/* -Copyright 2013 CoreOS 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 dbus - -import ( - "fmt" - "math/rand" - "os" - "path/filepath" - "reflect" - "testing" - - "github.com/godbus/dbus" -) - -func setupConn(t *testing.T) *Conn { - conn, err := New() - if err != nil { - t.Fatal(err) - } - - return conn -} - -func findFixture(target string, t *testing.T) string { - abs, err := filepath.Abs("../fixtures/" + target) - if err != nil { - t.Fatal(err) - } - return abs -} - -func setupUnit(target string, conn *Conn, t *testing.T) { - // Blindly stop the unit in case it is running - conn.StopUnit(target, "replace") - - // Blindly remove the symlink in case it exists - targetRun := filepath.Join("/run/systemd/system/", target) - os.Remove(targetRun) -} - -func linkUnit(target string, conn *Conn, t *testing.T) { - abs := findFixture(target, t) - fixture := []string{abs} - - changes, err := conn.LinkUnitFiles(fixture, true, true) - if err != nil { - t.Fatal(err) - } - - if len(changes) < 1 { - t.Fatalf("Expected one change, got %v", changes) - } - - runPath := filepath.Join("/run/systemd/system/", target) - if changes[0].Filename != runPath { - t.Fatal("Unexpected target filename") - } -} - -// Ensure that basic unit starting and stopping works. -func TestStartStopUnit(t *testing.T) { - target := "start-stop.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - // 2. Start the unit - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Job is not done:", job) - } - - units, err := conn.ListUnits() - - var unit *UnitStatus - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit == nil { - t.Fatalf("Test unit not found in list") - } - - if unit.ActiveState != "active" { - t.Fatalf("Test unit not active") - } - - // 3. Stop the unit - job, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - units, err = conn.ListUnits() - - unit = nil - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit != nil { - t.Fatalf("Test unit found in list, should be stopped") - } -} - -// Enables a unit and then immediately tears it down -func TestEnableDisableUnit(t *testing.T) { - target := "enable-disable.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - abs := findFixture(target, t) - runPath := filepath.Join("/run/systemd/system/", target) - - // 1. Enable the unit - install, changes, err := conn.EnableUnitFiles([]string{abs}, true, true) - if err != nil { - t.Fatal(err) - } - - if install != false { - t.Fatal("Install was true") - } - - if len(changes) < 1 { - t.Fatalf("Expected one change, got %v", changes) - } - - if changes[0].Filename != runPath { - t.Fatal("Unexpected target filename") - } - - // 2. Disable the unit - dChanges, err := conn.DisableUnitFiles([]string{abs}, true) - if err != nil { - t.Fatal(err) - } - - if len(dChanges) != 1 { - t.Fatalf("Changes should include the path, %v", dChanges) - } - if dChanges[0].Filename != runPath { - t.Fatalf("Change should include correct filename, %+v", dChanges[0]) - } - if dChanges[0].Destination != "" { - t.Fatalf("Change destination should be empty, %+v", dChanges[0]) - } -} - -// TestGetUnitProperties reads the `-.mount` which should exist on all systemd -// systems and ensures that one of its properties is valid. -func TestGetUnitProperties(t *testing.T) { - conn := setupConn(t) - - unit := "-.mount" - - info, err := conn.GetUnitProperties(unit) - if err != nil { - t.Fatal(err) - } - - names := info["Wants"].([]string) - - if len(names) < 1 { - t.Fatal("/ is unwanted") - } - - if names[0] != "system.slice" { - t.Fatal("unexpected wants for /") - } - - prop, err := conn.GetUnitProperty(unit, "Wants") - if err != nil { - t.Fatal(err) - } - - if prop.Name != "Wants" { - t.Fatal("unexpected property name") - } - - val := prop.Value.Value().([]string) - if !reflect.DeepEqual(val, names) { - t.Fatal("unexpected property value") - } -} - -// TestGetUnitPropertiesRejectsInvalidName attempts to get the properties for a -// unit with an invalid name. This test should be run with --test.timeout set, -// as a fail will manifest as GetUnitProperties hanging indefinitely. -func TestGetUnitPropertiesRejectsInvalidName(t *testing.T) { - conn := setupConn(t) - - unit := "//invalid#$^/" - - _, err := conn.GetUnitProperties(unit) - if err == nil { - t.Fatal("Expected an error, got nil") - } - - _, err = conn.GetUnitProperty(unit, "Wants") - if err == nil { - t.Fatal("Expected an error, got nil") - } -} - -// TestSetUnitProperties changes a cgroup setting on the `tmp.mount` -// which should exist on all systemd systems and ensures that the -// property was set. -func TestSetUnitProperties(t *testing.T) { - conn := setupConn(t) - - unit := "tmp.mount" - - if err := conn.SetUnitProperties(unit, true, Property{"CPUShares", dbus.MakeVariant(uint64(1023))}); err != nil { - t.Fatal(err) - } - - info, err := conn.GetUnitTypeProperties(unit, "Mount") - if err != nil { - t.Fatal(err) - } - - value := info["CPUShares"].(uint64) - if value != 1023 { - t.Fatal("CPUShares of unit is not 1023:", value) - } -} - -// Ensure that basic transient unit starting and stopping works. -func TestStartStopTransientUnit(t *testing.T) { - conn := setupConn(t) - - props := []Property{ - PropExecStart([]string{"/bin/sleep", "400"}, false), - } - target := fmt.Sprintf("testing-transient-%d.service", rand.Int()) - - // Start the unit - job, err := conn.StartTransientUnit(target, "replace", props...) - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Job is not done:", job) - } - - units, err := conn.ListUnits() - - var unit *UnitStatus - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit == nil { - t.Fatalf("Test unit not found in list") - } - - if unit.ActiveState != "active" { - t.Fatalf("Test unit not active") - } - - // 3. Stop the unit - job, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - units, err = conn.ListUnits() - - unit = nil - for _, u := range units { - if u.Name == target { - unit = &u - } - } - - if unit != nil { - t.Fatalf("Test unit found in list, should be stopped") - } -} - -func TestConnJobListener(t *testing.T) { - target := "start-stop.service" - conn := setupConn(t) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - jobSize := len(conn.jobListener.jobs) - - _, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - _, err = conn.StopUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - currentJobSize := len(conn.jobListener.jobs) - if jobSize != currentJobSize { - t.Fatal("JobListener jobs leaked") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/set_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/set_test.go deleted file mode 100644 index c4435f8800c..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/set_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package dbus - -import ( - "testing" -) - -// TestBasicSetActions asserts that Add & Remove behavior is correct -func TestBasicSetActions(t *testing.T) { - s := newSet() - - if s.Contains("foo") { - t.Fatal("set should not contain 'foo'") - } - - s.Add("foo") - - if !s.Contains("foo") { - t.Fatal("set should contain 'foo'") - } - - v := s.Values() - if len(v) != 1 { - t.Fatal("set.Values did not report correct number of values") - } - if v[0] != "foo" { - t.Fatal("set.Values did not report value") - } - - s.Remove("foo") - - if s.Contains("foo") { - t.Fatal("set should not contain 'foo'") - } - - v = s.Values() - if len(v) != 0 { - t.Fatal("set.Values did not report correct number of values") - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go deleted file mode 100644 index 4ecd15376d3..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package dbus - -import ( - "testing" - "time" -) - -// TestSubscribeUnit exercises the basics of subscription of a particular unit. -func TestSubscriptionSetUnit(t *testing.T) { - target := "subscribe-events-set.service" - - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - subSet := conn.NewSubscriptionSet() - evChan, errChan := subSet.Subscribe() - - subSet.Add(target) - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Couldn't start", target) - } - - timeout := make(chan bool, 1) - go func() { - time.Sleep(3 * time.Second) - close(timeout) - }() - - for { - select { - case changes := <-evChan: - tCh, ok := changes[target] - - if !ok { - t.Fatal("Unexpected event:", changes) - } - - if tCh.ActiveState == "active" && tCh.Name == target { - goto success - } - case err = <-errChan: - t.Fatal(err) - case <-timeout: - t.Fatal("Reached timeout") - } - } - -success: - return -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_test.go deleted file mode 100644 index f2b5dfc28c1..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/dbus/subscription_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package dbus - -import ( - "testing" - "time" -) - -// TestSubscribe exercises the basics of subscription -func TestSubscribe(t *testing.T) { - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - err = conn.Unsubscribe() - if err != nil { - t.Fatal(err) - } -} - -// TestSubscribeUnit exercises the basics of subscription of a particular unit. -func TestSubscribeUnit(t *testing.T) { - target := "subscribe-events.service" - - conn, err := New() - - if err != nil { - t.Fatal(err) - } - - err = conn.Subscribe() - if err != nil { - t.Fatal(err) - } - - err = conn.Unsubscribe() - if err != nil { - t.Fatal(err) - } - - evChan, errChan := conn.SubscribeUnits(time.Second) - - setupUnit(target, conn, t) - linkUnit(target, conn, t) - - job, err := conn.StartUnit(target, "replace") - if err != nil { - t.Fatal(err) - } - - if job != "done" { - t.Fatal("Couldn't start", target) - } - - timeout := make(chan bool, 1) - go func() { - time.Sleep(3 * time.Second) - close(timeout) - }() - - for { - select { - case changes := <-evChan: - tCh, ok := changes[target] - - // Just continue until we see our event. - if !ok { - continue - } - - if tCh.ActiveState == "active" && tCh.Name == target { - goto success - } - case err = <-errChan: - t.Fatal(err) - case <-timeout: - t.Fatal("Reached timeout") - } - } - -success: - return -} - - diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/login1/dbus_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/login1/dbus_test.go deleted file mode 100644 index 4439d37380c..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/coreos/go-systemd/login1/dbus_test.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2014 CoreOS 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 login1 - -import ( - "testing" -) - -// TestNew ensures that New() works without errors. -func TestNew(t *testing.T) { - _, err := New() - - if err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/conn_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/conn_test.go deleted file mode 100644 index a2b14e8cc46..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/conn_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package dbus - -import "testing" - -func TestSessionBus(t *testing.T) { - _, err := SessionBus() - if err != nil { - t.Error(err) - } -} - -func TestSystemBus(t *testing.T) { - _, err := SystemBus() - if err != nil { - t.Error(err) - } -} - -func TestSend(t *testing.T) { - bus, err := SessionBus() - if err != nil { - t.Error(err) - } - ch := make(chan *Call, 1) - msg := &Message{ - Type: TypeMethodCall, - Flags: 0, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant(bus.Names()[0]), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/DBus")), - FieldInterface: MakeVariant("org.freedesktop.DBus.Peer"), - FieldMember: MakeVariant("Ping"), - }, - } - call := bus.Send(msg, ch) - <-ch - if call.Err != nil { - t.Error(call.Err) - } -} - -type server struct{} - -func (server) Double(i int64) (int64, *Error) { - return 2 * i, nil -} - -func BenchmarkCall(b *testing.B) { - b.StopTimer() - var s string - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - name := bus.Names()[0] - obj := bus.BusObject() - b.StartTimer() - for i := 0; i < b.N; i++ { - err := obj.Call("org.freedesktop.DBus.GetNameOwner", 0, name).Store(&s) - if err != nil { - b.Fatal(err) - } - if s != name { - b.Errorf("got %s, wanted %s", s, name) - } - } -} - -func BenchmarkCallAsync(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - name := bus.Names()[0] - obj := bus.BusObject() - c := make(chan *Call, 50) - done := make(chan struct{}) - go func() { - for i := 0; i < b.N; i++ { - v := <-c - if v.Err != nil { - b.Error(v.Err) - } - s := v.Body[0].(string) - if s != name { - b.Errorf("got %s, wanted %s", s, name) - } - } - close(done) - }() - b.StartTimer() - for i := 0; i < b.N; i++ { - obj.Go("org.freedesktop.DBus.GetNameOwner", 0, c, name) - } - <-done -} - -func BenchmarkServe(b *testing.B) { - b.StopTimer() - srv, err := SessionBus() - if err != nil { - b.Fatal(err) - } - cli, err := SessionBusPrivate() - if err != nil { - b.Fatal(err) - } - if err = cli.Auth(nil); err != nil { - b.Fatal(err) - } - if err = cli.Hello(); err != nil { - b.Fatal(err) - } - benchmarkServe(b, srv, cli) -} - -func BenchmarkServeAsync(b *testing.B) { - b.StopTimer() - srv, err := SessionBus() - if err != nil { - b.Fatal(err) - } - cli, err := SessionBusPrivate() - if err != nil { - b.Fatal(err) - } - if err = cli.Auth(nil); err != nil { - b.Fatal(err) - } - if err = cli.Hello(); err != nil { - b.Fatal(err) - } - benchmarkServeAsync(b, srv, cli) -} - -func BenchmarkServeSameConn(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - - benchmarkServe(b, bus, bus) -} - -func BenchmarkServeSameConnAsync(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - - benchmarkServeAsync(b, bus, bus) -} - -func benchmarkServe(b *testing.B, srv, cli *Conn) { - var r int64 - var err error - dest := srv.Names()[0] - srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") - obj := cli.Object(dest, "/org/guelfey/DBus/Test") - b.StartTimer() - for i := 0; i < b.N; i++ { - err = obj.Call("org.guelfey.DBus.Test.Double", 0, int64(i)).Store(&r) - if err != nil { - b.Fatal(err) - } - if r != 2*int64(i) { - b.Errorf("got %d, wanted %d", r, 2*int64(i)) - } - } -} - -func benchmarkServeAsync(b *testing.B, srv, cli *Conn) { - dest := srv.Names()[0] - srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") - obj := cli.Object(dest, "/org/guelfey/DBus/Test") - c := make(chan *Call, 50) - done := make(chan struct{}) - go func() { - for i := 0; i < b.N; i++ { - v := <-c - if v.Err != nil { - b.Fatal(v.Err) - } - i, r := v.Args[0].(int64), v.Body[0].(int64) - if 2*i != r { - b.Errorf("got %d, wanted %d", r, 2*i) - } - } - close(done) - }() - b.StartTimer() - for i := 0; i < b.N; i++ { - obj.Go("org.guelfey.DBus.Test.Double", 0, c, int64(i)) - } - <-done -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/examples_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/examples_test.go deleted file mode 100644 index 0218ac55986..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/examples_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package dbus - -import "fmt" - -func ExampleConn_Emit() { - conn, err := SessionBus() - if err != nil { - panic(err) - } - - conn.Emit("/foo/bar", "foo.bar.Baz", uint32(0xDAEDBEEF)) -} - -func ExampleObject_Call() { - var list []string - - conn, err := SessionBus() - if err != nil { - panic(err) - } - - err = conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&list) - if err != nil { - panic(err) - } - for _, v := range list { - fmt.Println(v) - } -} - -func ExampleObject_Go() { - conn, err := SessionBus() - if err != nil { - panic(err) - } - - ch := make(chan *Call, 10) - conn.BusObject().Go("org.freedesktop.DBus.ListActivatableNames", 0, ch) - select { - case call := <-ch: - if call.Err != nil { - panic(err) - } - list := call.Body[0].([]string) - for _, v := range list { - fmt.Println(v) - } - // put some other cases here - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/proto_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/proto_test.go deleted file mode 100644 index 608a770d41f..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/proto_test.go +++ /dev/null @@ -1,369 +0,0 @@ -package dbus - -import ( - "bytes" - "encoding/binary" - "io/ioutil" - "math" - "reflect" - "testing" -) - -var protoTests = []struct { - vs []interface{} - bigEndian []byte - littleEndian []byte -}{ - { - []interface{}{int32(0)}, - []byte{0, 0, 0, 0}, - []byte{0, 0, 0, 0}, - }, - { - []interface{}{true, false}, - []byte{0, 0, 0, 1, 0, 0, 0, 0}, - []byte{1, 0, 0, 0, 0, 0, 0, 0}, - }, - { - []interface{}{byte(0), uint16(12), int16(32), uint32(43)}, - []byte{0, 0, 0, 12, 0, 32, 0, 0, 0, 0, 0, 43}, - []byte{0, 0, 12, 0, 32, 0, 0, 0, 43, 0, 0, 0}, - }, - { - []interface{}{int64(-1), uint64(1<<64 - 1)}, - bytes.Repeat([]byte{255}, 16), - bytes.Repeat([]byte{255}, 16), - }, - { - []interface{}{math.Inf(+1)}, - []byte{0x7f, 0xf0, 0, 0, 0, 0, 0, 0}, - []byte{0, 0, 0, 0, 0, 0, 0xf0, 0x7f}, - }, - { - []interface{}{"foo"}, - []byte{0, 0, 0, 3, 'f', 'o', 'o', 0}, - []byte{3, 0, 0, 0, 'f', 'o', 'o', 0}, - }, - { - []interface{}{Signature{"ai"}}, - []byte{2, 'a', 'i', 0}, - []byte{2, 'a', 'i', 0}, - }, - { - []interface{}{[]int16{42, 256}}, - []byte{0, 0, 0, 4, 0, 42, 1, 0}, - []byte{4, 0, 0, 0, 42, 0, 0, 1}, - }, - { - []interface{}{MakeVariant("foo")}, - []byte{1, 's', 0, 0, 0, 0, 0, 3, 'f', 'o', 'o', 0}, - []byte{1, 's', 0, 0, 3, 0, 0, 0, 'f', 'o', 'o', 0}, - }, - { - []interface{}{MakeVariant(MakeVariant(Signature{"v"}))}, - []byte{1, 'v', 0, 1, 'g', 0, 1, 'v', 0}, - []byte{1, 'v', 0, 1, 'g', 0, 1, 'v', 0}, - }, - { - []interface{}{map[int32]bool{42: true}}, - []byte{0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 1}, - []byte{8, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 1, 0, 0, 0}, - }, - { - []interface{}{map[string]Variant{}, byte(42)}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - }, - { - []interface{}{[]uint64{}, byte(42)}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - }, -} - -func TestProto(t *testing.T) { - for i, v := range protoTests { - buf := new(bytes.Buffer) - bigEnc := newEncoder(buf, binary.BigEndian) - bigEnc.Encode(v.vs...) - marshalled := buf.Bytes() - if bytes.Compare(marshalled, v.bigEndian) != 0 { - t.Errorf("test %d (marshal be): got '%v', but expected '%v'\n", i+1, marshalled, - v.bigEndian) - } - buf.Reset() - litEnc := newEncoder(buf, binary.LittleEndian) - litEnc.Encode(v.vs...) - marshalled = buf.Bytes() - if bytes.Compare(marshalled, v.littleEndian) != 0 { - t.Errorf("test %d (marshal le): got '%v', but expected '%v'\n", i+1, marshalled, - v.littleEndian) - } - unmarshalled := reflect.MakeSlice(reflect.TypeOf(v.vs), - 0, 0) - for i := range v.vs { - unmarshalled = reflect.Append(unmarshalled, - reflect.New(reflect.TypeOf(v.vs[i]))) - } - bigDec := newDecoder(bytes.NewReader(v.bigEndian), binary.BigEndian) - vs, err := bigDec.Decode(SignatureOf(v.vs...)) - if err != nil { - t.Errorf("test %d (unmarshal be): %s\n", i+1, err) - continue - } - if !reflect.DeepEqual(vs, v.vs) { - t.Errorf("test %d (unmarshal be): got %#v, but expected %#v\n", i+1, vs, v.vs) - } - litDec := newDecoder(bytes.NewReader(v.littleEndian), binary.LittleEndian) - vs, err = litDec.Decode(SignatureOf(v.vs...)) - if err != nil { - t.Errorf("test %d (unmarshal le): %s\n", i+1, err) - continue - } - if !reflect.DeepEqual(vs, v.vs) { - t.Errorf("test %d (unmarshal le): got %#v, but expected %#v\n", i+1, vs, v.vs) - } - - } -} - -func TestProtoMap(t *testing.T) { - m := map[string]uint8{ - "foo": 23, - "bar": 2, - } - var n map[string]uint8 - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(m) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"a{sy}"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &n); err != nil { - t.Fatal(err) - } - if len(n) != 2 || n["foo"] != 23 || n["bar"] != 2 { - t.Error("got", n) - } -} - -func TestProtoVariantStruct(t *testing.T) { - var variant Variant - v := MakeVariant(struct { - A int32 - B int16 - }{1, 2}) - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(v) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"v"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &variant); err != nil { - t.Fatal(err) - } - sl := variant.Value().([]interface{}) - v1, v2 := sl[0].(int32), sl[1].(int16) - if v1 != int32(1) { - t.Error("got", v1, "as first int") - } - if v2 != int16(2) { - t.Error("got", v2, "as second int") - } -} - -func TestProtoStructTag(t *testing.T) { - type Bar struct { - A int32 - B chan interface{} `dbus:"-"` - C int32 - } - var bar1, bar2 Bar - bar1.A = 234 - bar2.C = 345 - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(bar1) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"(ii)"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &bar2); err != nil { - t.Fatal(err) - } - if bar1 != bar2 { - t.Error("struct tag test: got", bar2) - } -} - -func TestProtoStoreStruct(t *testing.T) { - var foo struct { - A int32 - B string - c chan interface{} - D interface{} `dbus:"-"` - } - src := []interface{}{[]interface{}{int32(42), "foo"}} - err := Store(src, &foo) - if err != nil { - t.Fatal(err) - } -} - -func TestProtoStoreNestedStruct(t *testing.T) { - var foo struct { - A int32 - B struct { - C string - D float64 - } - } - src := []interface{}{ - []interface{}{ - int32(42), - []interface{}{ - "foo", - 3.14, - }, - }, - } - err := Store(src, &foo) - if err != nil { - t.Fatal(err) - } -} - -func TestMessage(t *testing.T) { - buf := new(bytes.Buffer) - message := new(Message) - message.Type = TypeMethodCall - message.serial = 32 - message.Headers = map[HeaderField]Variant{ - FieldPath: MakeVariant(ObjectPath("/org/foo/bar")), - FieldMember: MakeVariant("baz"), - } - message.Body = make([]interface{}, 0) - err := message.EncodeTo(buf, binary.LittleEndian) - if err != nil { - t.Error(err) - } - _, err = DecodeMessage(buf) - if err != nil { - t.Error(err) - } -} - -func TestProtoStructInterfaces(t *testing.T) { - b := []byte{42} - vs, err := newDecoder(bytes.NewReader(b), binary.LittleEndian).Decode(Signature{"(y)"}) - if err != nil { - t.Fatal(err) - } - if vs[0].([]interface{})[0].(byte) != 42 { - t.Errorf("wrongs results (got %v)", vs) - } -} - -// ordinary org.freedesktop.DBus.Hello call -var smallMessage = &Message{ - Type: TypeMethodCall, - serial: 1, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant("org.freedesktop.DBus"), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/DBus")), - FieldInterface: MakeVariant("org.freedesktop.DBus"), - FieldMember: MakeVariant("Hello"), - }, -} - -// org.freedesktop.Notifications.Notify -var bigMessage = &Message{ - Type: TypeMethodCall, - serial: 2, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant("org.freedesktop.Notifications"), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/Notifications")), - FieldInterface: MakeVariant("org.freedesktop.Notifications"), - FieldMember: MakeVariant("Notify"), - FieldSignature: MakeVariant(Signature{"susssasa{sv}i"}), - }, - Body: []interface{}{ - "app_name", - uint32(0), - "dialog-information", - "Notification", - "This is the body of a notification", - []string{"ok", "Ok"}, - map[string]Variant{ - "sound-name": MakeVariant("dialog-information"), - }, - int32(-1), - }, -} - -func BenchmarkDecodeMessageSmall(b *testing.B) { - var err error - var rd *bytes.Reader - - b.StopTimer() - buf := new(bytes.Buffer) - err = smallMessage.EncodeTo(buf, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - decoded := buf.Bytes() - b.StartTimer() - for i := 0; i < b.N; i++ { - rd = bytes.NewReader(decoded) - _, err = DecodeMessage(rd) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkDecodeMessageBig(b *testing.B) { - var err error - var rd *bytes.Reader - - b.StopTimer() - buf := new(bytes.Buffer) - err = bigMessage.EncodeTo(buf, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - decoded := buf.Bytes() - b.StartTimer() - for i := 0; i < b.N; i++ { - rd = bytes.NewReader(decoded) - _, err = DecodeMessage(rd) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkEncodeMessageSmall(b *testing.B) { - var err error - for i := 0; i < b.N; i++ { - err = smallMessage.EncodeTo(ioutil.Discard, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkEncodeMessageBig(b *testing.B) { - var err error - for i := 0; i < b.N; i++ { - err = bigMessage.EncodeTo(ioutil.Discard, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/sig_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/sig_test.go deleted file mode 100644 index da37bc968e7..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/sig_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package dbus - -import ( - "testing" -) - -var sigTests = []struct { - vs []interface{} - sig Signature -}{ - { - []interface{}{new(int32)}, - Signature{"i"}, - }, - { - []interface{}{new(string)}, - Signature{"s"}, - }, - { - []interface{}{new(Signature)}, - Signature{"g"}, - }, - { - []interface{}{new([]int16)}, - Signature{"an"}, - }, - { - []interface{}{new(int16), new(uint32)}, - Signature{"nu"}, - }, - { - []interface{}{new(map[byte]Variant)}, - Signature{"a{yv}"}, - }, - { - []interface{}{new(Variant), new([]map[int32]string)}, - Signature{"vaa{is}"}, - }, -} - -func TestSig(t *testing.T) { - for i, v := range sigTests { - sig := SignatureOf(v.vs...) - if sig != v.sig { - t.Errorf("test %d: got %q, expected %q", i+1, sig.str, v.sig.str) - } - } -} - -var getSigTest = []interface{}{ - []struct { - b byte - i int32 - t uint64 - s string - }{}, - map[string]Variant{}, -} - -func BenchmarkGetSignatureSimple(b *testing.B) { - for i := 0; i < b.N; i++ { - SignatureOf("", int32(0)) - } -} - -func BenchmarkGetSignatureLong(b *testing.B) { - for i := 0; i < b.N; i++ { - SignatureOf(getSigTest...) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/transport_unix_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/transport_unix_test.go deleted file mode 100644 index 302233fc65e..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/transport_unix_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package dbus - -import ( - "os" - "testing" -) - -const testString = `This is a test! -This text should be read from the file that is created by this test.` - -type unixFDTest struct{} - -func (t unixFDTest) Test(fd UnixFD) (string, *Error) { - var b [4096]byte - file := os.NewFile(uintptr(fd), "testfile") - defer file.Close() - n, err := file.Read(b[:]) - if err != nil { - return "", &Error{"com.github.guelfey.test.Error", nil} - } - return string(b[:n]), nil -} - -func TestUnixFDs(t *testing.T) { - conn, err := SessionBus() - if err != nil { - t.Fatal(err) - } - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - defer w.Close() - if _, err := w.Write([]byte(testString)); err != nil { - t.Fatal(err) - } - name := conn.Names()[0] - test := unixFDTest{} - conn.Export(test, "/com/github/guelfey/test", "com.github.guelfey.test") - var s string - obj := conn.Object(name, "/com/github/guelfey/test") - err = obj.Call("com.github.guelfey.test.Test", 0, UnixFD(r.Fd())).Store(&s) - if err != nil { - t.Fatal(err) - } - if s != testString { - t.Fatal("got", s, "wanted", testString) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/variant_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/variant_test.go deleted file mode 100644 index da917c8e290..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/godbus/dbus/variant_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package dbus - -import "reflect" -import "testing" - -var variantFormatTests = []struct { - v interface{} - s string -}{ - {int32(1), `1`}, - {"foo", `"foo"`}, - {ObjectPath("/org/foo"), `@o "/org/foo"`}, - {Signature{"i"}, `@g "i"`}, - {[]byte{}, `@ay []`}, - {[]int32{1, 2}, `[1, 2]`}, - {[]int64{1, 2}, `@ax [1, 2]`}, - {[][]int32{{3, 4}, {5, 6}}, `[[3, 4], [5, 6]]`}, - {[]Variant{MakeVariant(int32(1)), MakeVariant(1.0)}, `[<1>, <@d 1>]`}, - {map[string]int32{"one": 1, "two": 2}, `{"one": 1, "two": 2}`}, - {map[int32]ObjectPath{1: "/org/foo"}, `@a{io} {1: "/org/foo"}`}, - {map[string]Variant{}, `@a{sv} {}`}, -} - -func TestFormatVariant(t *testing.T) { - for i, v := range variantFormatTests { - if s := MakeVariant(v.v).String(); s != v.s { - t.Errorf("test %d: got %q, wanted %q", i+1, s, v.s) - } - } -} - -var variantParseTests = []struct { - s string - v interface{} -}{ - {"1", int32(1)}, - {"true", true}, - {"false", false}, - {"1.0", float64(1.0)}, - {"0x10", int32(16)}, - {"1e1", float64(10)}, - {`"foo"`, "foo"}, - {`"\a\b\f\n\r\t"`, "\x07\x08\x0c\n\r\t"}, - {`"\u00e4\U0001f603"`, "\u00e4\U0001f603"}, - {"[1]", []int32{1}}, - {"[1, 2, 3]", []int32{1, 2, 3}}, - {"@ai []", []int32{}}, - {"[1, 5.0]", []float64{1, 5.0}}, - {"[[1, 2], [3, 4.0]]", [][]float64{{1, 2}, {3, 4}}}, - {`[@o "/org/foo", "/org/bar"]`, []ObjectPath{"/org/foo", "/org/bar"}}, - {"<1>", MakeVariant(int32(1))}, - {"[<1>, <2.0>]", []Variant{MakeVariant(int32(1)), MakeVariant(2.0)}}, - {`[[], [""]]`, [][]string{{}, {""}}}, - {`@a{ss} {}`, map[string]string{}}, - {`{"foo": 1}`, map[string]int32{"foo": 1}}, - {`[{}, {"foo": "bar"}]`, []map[string]string{{}, {"foo": "bar"}}}, - {`{"a": <1>, "b": <"foo">}`, - map[string]Variant{"a": MakeVariant(int32(1)), "b": MakeVariant("foo")}}, - {`b''`, []byte{0}}, - {`b"abc"`, []byte{'a', 'b', 'c', 0}}, - {`b"\x01\0002\a\b\f\n\r\t"`, []byte{1, 2, 0x7, 0x8, 0xc, '\n', '\r', '\t', 0}}, - {`[[0], b""]`, [][]byte{{0}, {0}}}, - {"int16 0", int16(0)}, - {"byte 0", byte(0)}, -} - -func TestParseVariant(t *testing.T) { - for i, v := range variantParseTests { - nv, err := ParseVariant(v.s, Signature{}) - if err != nil { - t.Errorf("test %d: parsing failed: %s", i+1, err) - continue - } - if !reflect.DeepEqual(nv.value, v.v) { - t.Errorf("test %d: got %q, wanted %q", i+1, nv, v.v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/syndtr/gocapability/capability/capability_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/syndtr/gocapability/capability/capability_test.go deleted file mode 100644 index 8108655c05f..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/vendor/src/github.com/syndtr/gocapability/capability/capability_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -import "testing" - -func TestState(t *testing.T) { - testEmpty := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Empty(i) { - t.Errorf(name+": capabilities set %q wasn't empty", i) - } - } - } - testFull := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Full(i) { - t.Errorf(name+": capabilities set %q wasn't full", i) - } - } - } - testPartial := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && (c.Empty(i) || c.Full(i)) { - t.Errorf(name+": capabilities set %q wasn't partial", i) - } - } - } - testGet := func(name string, c Capabilities, whats CapType, max Cap) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i & whats) == 0 { - continue - } - for j := Cap(0); j <= max; j++ { - if !c.Get(i, j) { - t.Errorf(name+": capability %q wasn't found on %q", j, i) - } - } - } - } - - capf := new(capsFile) - capf.data.version = 2 - for _, tc := range []struct { - name string - c Capabilities - sets CapType - max Cap - }{ - {"v1", new(capsV1), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"v3", new(capsV3), EFFECTIVE | PERMITTED | BOUNDING, CAP_LAST_CAP}, - {"file_v1", new(capsFile), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"file_v2", capf, EFFECTIVE | PERMITTED, CAP_LAST_CAP}, - } { - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Fill(CAPS | BOUNDS) - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Set(i, j) - } - } - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Unset(i, j) - } - } - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Set(PERMITTED, CAP_CHOWN) - testPartial(tc.name, tc.c, PERMITTED) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/libcontainer/xattr/xattr_test.go b/Godeps/_workspace/src/github.com/docker/libcontainer/xattr/xattr_test.go deleted file mode 100644 index d818c691d4b..00000000000 --- a/Godeps/_workspace/src/github.com/docker/libcontainer/xattr/xattr_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// +build linux - -package xattr_test - -import ( - "os" - "testing" - - "github.com/docker/libcontainer/xattr" -) - -func testXattr(t *testing.T) { - tmp := "xattr_test" - out, err := os.OpenFile(tmp, os.O_WRONLY, 0) - if err != nil { - t.Fatal("failed") - } - attr := "user.test" - out.Close() - - if !xattr.XattrEnabled(tmp) { - t.Log("Disabled") - t.Fatal("failed") - } - t.Log("Success") - - err = xattr.Setxattr(tmp, attr, "test") - if err != nil { - t.Fatal("failed") - } - - var value string - value, err = xattr.Getxattr(tmp, attr) - if err != nil { - t.Fatal("failed") - } - if value != "test" { - t.Fatal("failed") - } - t.Log("Success") - - var names []string - names, err = xattr.Listxattr(tmp) - if err != nil { - t.Fatal("failed") - } - - var found int - for _, name := range names { - if name == attr { - found = 1 - } - } - // Listxattr doesn't return trusted.* and system.* namespace - // attrs when run in unprevileged mode. - if found != 1 { - t.Fatal("failed") - } - t.Log("Success") - - big := "0000000000000000000000000000000000000000000000000000000000000000000008c6419ad822dfe29283fb3ac98dcc5908810cb31f4cfe690040c42c144b7492eicompslf20dxmlpgz" - // Test for long xattrs larger than 128 bytes - err = xattr.Setxattr(tmp, attr, big) - if err != nil { - t.Fatal("failed to add long value") - } - value, err = xattr.Getxattr(tmp, attr) - if err != nil { - t.Fatal("failed to get long value") - } - t.Log("Success") - - if value != big { - t.Fatal("failed, value doesn't match") - } - t.Log("Success") -} diff --git a/Godeps/_workspace/src/github.com/docker/spdystream/priority_test.go b/Godeps/_workspace/src/github.com/docker/spdystream/priority_test.go deleted file mode 100644 index 0746be2a80a..00000000000 --- a/Godeps/_workspace/src/github.com/docker/spdystream/priority_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package spdystream - -import ( - "sync" - "testing" - "time" - - "github.com/docker/spdystream/spdy" -) - -func TestPriorityQueueOrdering(t *testing.T) { - queue := NewPriorityFrameQueue(150) - data1 := &spdy.DataFrame{} - data2 := &spdy.DataFrame{} - data3 := &spdy.DataFrame{} - data4 := &spdy.DataFrame{} - queue.Push(data1, 2) - queue.Push(data2, 1) - queue.Push(data3, 1) - queue.Push(data4, 0) - - if queue.Pop() != data4 { - t.Fatalf("Wrong order, expected data4 first") - } - if queue.Pop() != data2 { - t.Fatalf("Wrong order, expected data2 second") - } - if queue.Pop() != data3 { - t.Fatalf("Wrong order, expected data3 third") - } - if queue.Pop() != data1 { - t.Fatalf("Wrong order, expected data1 fourth") - } - - // Insert 50 Medium priority frames - for i := spdy.StreamId(50); i < 100; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 1) - } - // Insert 50 low priority frames - for i := spdy.StreamId(100); i < 150; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 2) - } - // Insert 50 high priority frames - for i := spdy.StreamId(0); i < 50; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 0) - } - - for i := spdy.StreamId(0); i < 150; i++ { - frame := queue.Pop() - if frame.(*spdy.DataFrame).StreamId != i { - t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) - } - } -} - -func TestPriorityQueueSync(t *testing.T) { - queue := NewPriorityFrameQueue(150) - var wg sync.WaitGroup - insertRange := func(start, stop spdy.StreamId, priority uint8) { - for i := start; i < stop; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, priority) - } - wg.Done() - } - wg.Add(3) - go insertRange(spdy.StreamId(100), spdy.StreamId(150), 2) - go insertRange(spdy.StreamId(0), spdy.StreamId(50), 0) - go insertRange(spdy.StreamId(50), spdy.StreamId(100), 1) - - wg.Wait() - for i := spdy.StreamId(0); i < 150; i++ { - frame := queue.Pop() - if frame.(*spdy.DataFrame).StreamId != i { - t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) - } - } -} - -func TestPriorityQueueBlocking(t *testing.T) { - queue := NewPriorityFrameQueue(15) - for i := 0; i < 15; i++ { - queue.Push(&spdy.DataFrame{}, 2) - } - doneChan := make(chan bool) - go func() { - queue.Push(&spdy.DataFrame{}, 2) - close(doneChan) - }() - select { - case <-doneChan: - t.Fatalf("Push succeeded, expected to block") - case <-time.After(time.Millisecond): - break - } - - queue.Pop() - - select { - case <-doneChan: - break - case <-time.After(time.Millisecond): - t.Fatalf("Push should have succeeded, but timeout reached") - } - - for i := 0; i < 15; i++ { - queue.Pop() - } -} diff --git a/Godeps/_workspace/src/github.com/docker/spdystream/spdy/spdy_test.go b/Godeps/_workspace/src/github.com/docker/spdystream/spdy/spdy_test.go deleted file mode 100644 index ce581f1d056..00000000000 --- a/Godeps/_workspace/src/github.com/docker/spdystream/spdy/spdy_test.go +++ /dev/null @@ -1,644 +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 spdy - -import ( - "bytes" - "compress/zlib" - "encoding/base64" - "io" - "io/ioutil" - "net/http" - "reflect" - "testing" -) - -var HeadersFixture = http.Header{ - "Url": []string{"http://www.google.com/"}, - "Method": []string{"get"}, - "Version": []string{"http/1.1"}, -} - -func TestHeaderParsing(t *testing.T) { - var headerValueBlockBuf bytes.Buffer - writeHeaderValueBlock(&headerValueBlockBuf, HeadersFixture) - const bogusStreamId = 1 - newHeaders, err := parseHeaderValueBlock(&headerValueBlockBuf, bogusStreamId) - if err != nil { - t.Fatal("parseHeaderValueBlock:", err) - } - if !reflect.DeepEqual(HeadersFixture, newHeaders) { - t.Fatal("got: ", newHeaders, "\nwant: ", HeadersFixture) - } -} - -func TestCreateParseSynStreamFrameCompressionDisable(t *testing.T) { - buffer := new(bytes.Buffer) - // Fixture framer for no compression test. - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestCreateParseSynStreamFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestCreateParseSynReplyFrameCompressionDisable(t *testing.T) { - buffer := new(bytes.Buffer) - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - synReplyFrame := SynReplyFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynReply, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&synReplyFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedSynReplyFrame, ok := frame.(*SynReplyFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { - t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) - } -} - -func TestCreateParseSynReplyFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - synReplyFrame := SynReplyFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynReply, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - if err := framer.WriteFrame(&synReplyFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedSynReplyFrame, ok := frame.(*SynReplyFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { - t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) - } -} - -func TestCreateParseRstStream(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - rstStreamFrame := RstStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeRstStream, - }, - StreamId: 1, - Status: InvalidStream, - } - if err := framer.WriteFrame(&rstStreamFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedRstStreamFrame, ok := frame.(*RstStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(rstStreamFrame, *parsedRstStreamFrame) { - t.Fatal("got: ", *parsedRstStreamFrame, "\nwant: ", rstStreamFrame) - } -} - -func TestCreateParseSettings(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - settingsFrame := SettingsFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSettings, - }, - FlagIdValues: []SettingsFlagIdValue{ - {FlagSettingsPersistValue, SettingsCurrentCwnd, 10}, - {FlagSettingsPersisted, SettingsUploadBandwidth, 1}, - }, - } - if err := framer.WriteFrame(&settingsFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedSettingsFrame, ok := frame.(*SettingsFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(settingsFrame, *parsedSettingsFrame) { - t.Fatal("got: ", *parsedSettingsFrame, "\nwant: ", settingsFrame) - } -} - -func TestCreateParsePing(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - pingFrame := PingFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypePing, - }, - Id: 31337, - } - if err := framer.WriteFrame(&pingFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if pingFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", pingFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedPingFrame, ok := frame.(*PingFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedPingFrame.CFHeader.Flags != 0 { - t.Fatal("Parsed incorrect frame type:", parsedPingFrame) - } - if !reflect.DeepEqual(pingFrame, *parsedPingFrame) { - t.Fatal("got: ", *parsedPingFrame, "\nwant: ", pingFrame) - } -} - -func TestCreateParseGoAway(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - goAwayFrame := GoAwayFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeGoAway, - }, - LastGoodStreamId: 31337, - Status: 1, - } - if err := framer.WriteFrame(&goAwayFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if goAwayFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", goAwayFrame) - } - if goAwayFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", goAwayFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedGoAwayFrame, ok := frame.(*GoAwayFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedGoAwayFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", parsedGoAwayFrame) - } - if parsedGoAwayFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", parsedGoAwayFrame) - } - if !reflect.DeepEqual(goAwayFrame, *parsedGoAwayFrame) { - t.Fatal("got: ", *parsedGoAwayFrame, "\nwant: ", goAwayFrame) - } -} - -func TestCreateParseHeadersFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - } - headersFrame.Headers = HeadersFixture - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } -} - -func TestCreateParseHeadersFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - } - headersFrame.Headers = HeadersFixture - - framer, err := NewFramer(buffer, buffer) - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } -} - -func TestCreateParseWindowUpdateFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - windowUpdateFrame := WindowUpdateFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeWindowUpdate, - }, - StreamId: 31337, - DeltaWindowSize: 1, - } - if err := framer.WriteFrame(&windowUpdateFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if windowUpdateFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", windowUpdateFrame) - } - if windowUpdateFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", windowUpdateFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedWindowUpdateFrame, ok := frame.(*WindowUpdateFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedWindowUpdateFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) - } - if parsedWindowUpdateFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) - } - if !reflect.DeepEqual(windowUpdateFrame, *parsedWindowUpdateFrame) { - t.Fatal("got: ", *parsedWindowUpdateFrame, "\nwant: ", windowUpdateFrame) - } -} - -func TestCreateParseDataFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - dataFrame := DataFrame{ - StreamId: 1, - Data: []byte{'h', 'e', 'l', 'l', 'o'}, - } - if err := framer.WriteFrame(&dataFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedDataFrame, ok := frame.(*DataFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(dataFrame, *parsedDataFrame) { - t.Fatal("got: ", *parsedDataFrame, "\nwant: ", dataFrame) - } -} - -func TestCompressionContextAcrossFrames(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame (HEADERS):", err) - } - synStreamFrame := SynStreamFrame{ - ControlFrameHeader{ - Version, - TypeSynStream, - 0, // Flags - 0, // length - }, - 2, // StreamId - 0, // AssociatedTOStreamID - 0, // Priority - 1, // Slot - nil, // Headers - } - synStreamFrame.Headers = HeadersFixture - - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame (SYN_STREAM):", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (HEADERS):", err, buffer.Bytes()) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatalf("expected HeadersFrame; got %T %v", frame, frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } - frame, err = framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (SYN_STREAM):", err, buffer.Bytes()) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatalf("expected SynStreamFrame; got %T %v", frame, frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestMultipleSPDYFrames(t *testing.T) { - // Initialize the framers. - pr1, pw1 := io.Pipe() - pr2, pw2 := io.Pipe() - writer, err := NewFramer(pw1, pr2) - if err != nil { - t.Fatal("Failed to create writer:", err) - } - reader, err := NewFramer(pw2, pr1) - if err != nil { - t.Fatal("Failed to create reader:", err) - } - - // Set up the frames we're actually transferring. - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - Headers: HeadersFixture, - } - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - - // Start the goroutines to write the frames. - go func() { - if err := writer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame (HEADERS): ", err) - } - if err := writer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame (SYN_STREAM): ", err) - } - }() - - // Read the frames and verify they look as expected. - frame, err := reader.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (HEADERS): ", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } - frame, err = reader.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (SYN_STREAM):", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type.") - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestReadMalformedZlibHeader(t *testing.T) { - // These were constructed by corrupting the first byte of the zlib - // header after writing. - malformedStructs := map[string]string{ - "SynStreamFrame": "gAIAAQAAABgAAAACAAAAAAAAF/nfolGyYmAAAAAA//8=", - "SynReplyFrame": "gAIAAgAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", - "HeadersFrame": "gAIACAAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", - } - for name, bad := range malformedStructs { - b, err := base64.StdEncoding.DecodeString(bad) - if err != nil { - t.Errorf("Unable to decode base64 encoded frame %s: %v", name, err) - } - buf := bytes.NewBuffer(b) - reader, err := NewFramer(buf, buf) - if err != nil { - t.Fatalf("NewFramer: %v", err) - } - _, err = reader.ReadFrame() - if err != zlib.ErrHeader { - t.Errorf("Frame %s, expected: %#v, actual: %#v", name, zlib.ErrHeader, err) - } - } -} - -// TODO: these tests are too weak for updating SPDY spec. Fix me. - -type zeroStream struct { - frame Frame - encoded string -} - -var streamIdZeroFrames = map[string]zeroStream{ - "SynStreamFrame": { - &SynStreamFrame{StreamId: 0}, - "gAIAAQAAABgAAAAAAAAAAAAAePnfolGyYmAAAAAA//8=", - }, - "SynReplyFrame": { - &SynReplyFrame{StreamId: 0}, - "gAIAAgAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", - }, - "RstStreamFrame": { - &RstStreamFrame{StreamId: 0}, - "gAIAAwAAAAgAAAAAAAAAAA==", - }, - "HeadersFrame": { - &HeadersFrame{StreamId: 0}, - "gAIACAAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", - }, - "DataFrame": { - &DataFrame{StreamId: 0}, - "AAAAAAAAAAA=", - }, - "PingFrame": { - &PingFrame{Id: 0}, - "gAIABgAAAAQAAAAA", - }, -} - -func TestNoZeroStreamId(t *testing.T) { - t.Log("skipping") // TODO: update to work with SPDY3 - return - - for name, f := range streamIdZeroFrames { - b, err := base64.StdEncoding.DecodeString(f.encoded) - if err != nil { - t.Errorf("Unable to decode base64 encoded frame %s: %v", f, err) - continue - } - framer, err := NewFramer(ioutil.Discard, bytes.NewReader(b)) - if err != nil { - t.Fatalf("NewFramer: %v", err) - } - err = framer.WriteFrame(f.frame) - checkZeroStreamId(t, name, "WriteFrame", err) - - _, err = framer.ReadFrame() - checkZeroStreamId(t, name, "ReadFrame", err) - } -} - -func checkZeroStreamId(t *testing.T, frame string, method string, err error) { - if err == nil { - t.Errorf("%s ZeroStreamId, no error on %s", method, frame) - return - } - eerr, ok := err.(*Error) - if !ok || eerr.Err != ZeroStreamId { - t.Errorf("%s ZeroStreamId, incorrect error %#v, frame %s", method, eerr, frame) - } -} diff --git a/Godeps/_workspace/src/github.com/docker/spdystream/spdy_bench_test.go b/Godeps/_workspace/src/github.com/docker/spdystream/spdy_bench_test.go deleted file mode 100644 index 6f9e4910151..00000000000 --- a/Godeps/_workspace/src/github.com/docker/spdystream/spdy_bench_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package spdystream - -import ( - "fmt" - "io" - "net" - "net/http" - "sync" - "testing" -) - -func configureServer() (io.Closer, string, *sync.WaitGroup) { - authenticated = true - wg := &sync.WaitGroup{} - server, listen, serverErr := runServer(wg) - - if serverErr != nil { - panic(serverErr) - } - - return server, listen, wg -} - -func BenchmarkDial10000(b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - panic(fmt.Sprintf("Error dialing server: %s", dialErr)) - } - conn.Close() - } -} - -func BenchmarkDialWithSPDYStream10000(b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - b.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - b.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - closeErr := spdyConn.Close() - if closeErr != nil { - b.Fatalf("Error closing connection: %s, closeErr") - } - } -} - -func benchmarkStreamWithDataAndSize(size uint64, b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - b.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - b.Fatalf("Error creating spdy connection: %s", spdyErr) - } - - go spdyConn.Serve(MirrorStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - - writer := make([]byte, size) - - stream.Write(writer) - - if err != nil { - panic(err) - } - - reader := make([]byte, size) - stream.Read(reader) - - stream.Close() - - closeErr := spdyConn.Close() - if closeErr != nil { - b.Fatalf("Error closing connection: %s, closeErr") - } - } -} - -func BenchmarkStreamWith1Byte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1, b) } -func BenchmarkStreamWith1KiloByte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024, b) } -func BenchmarkStreamWith1Megabyte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024*1024, b) } diff --git a/Godeps/_workspace/src/github.com/docker/spdystream/spdy_test.go b/Godeps/_workspace/src/github.com/docker/spdystream/spdy_test.go deleted file mode 100644 index 9c8fa131a7e..00000000000 --- a/Godeps/_workspace/src/github.com/docker/spdystream/spdy_test.go +++ /dev/null @@ -1,909 +0,0 @@ -package spdystream - -import ( - "bufio" - "bytes" - "io" - "net" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" -) - -func TestSpdyStreams(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - message := []byte("hello") - writeErr := stream.WriteData(message, false) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - buf := make([]byte, 10) - n, readErr := stream.Read(buf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 5 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) - } - if bytes.Compare(buf[:n], message) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) - } - - headers := http.Header{ - "TestKey": []string{"TestVal"}, - } - sendErr := stream.SendHeader(headers, false) - if sendErr != nil { - t.Fatalf("Error sending headers: %s", sendErr) - } - receiveHeaders, receiveErr := stream.ReceiveHeader() - if receiveErr != nil { - t.Fatalf("Error receiving headers: %s", receiveErr) - } - if len(receiveHeaders) != 1 { - t.Fatalf("Unexpected number of headers:\nActual: %d\nExpecting:%d", len(receiveHeaders), 1) - } - testVal := receiveHeaders.Get("TestKey") - if testVal != "TestVal" { - t.Fatalf("Wrong test value:\nActual: %q\nExpecting: %q", testVal, "TestVal") - } - - writeErr = stream.WriteData(message, true) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - smallBuf := make([]byte, 3) - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 3 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 3", n) - } - if bytes.Compare(smallBuf[:n], []byte("hel")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", smallBuf[:n], message) - } - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 2 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 2", n) - } - if bytes.Compare(smallBuf[:n], []byte("lo")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpected: lo", smallBuf[:n]) - } - - n, readErr = stream.Read(buf) - if readErr != io.EOF { - t.Fatalf("Expected EOF reading from finished stream, read %d bytes", n) - } - - // Closing again should return error since stream is already closed - streamCloseErr := stream.Close() - if streamCloseErr == nil { - t.Fatalf("No error closing finished stream") - } - if streamCloseErr != ErrWriteClosedStream { - t.Fatalf("Unexpected error closing stream: %s", streamCloseErr) - } - - streamResetErr := stream.Reset() - if streamResetErr != nil { - t.Fatalf("Error reseting stream: %s", streamResetErr) - } - - authenticated = false - badStream, badStreamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if badStreamErr != nil { - t.Fatalf("Error creating stream: %s", badStreamErr) - } - - waitErr = badStream.Wait() - if waitErr == nil { - t.Fatalf("Did not receive error creating stream") - } - if waitErr != ErrReset { - t.Fatalf("Unexpected error creating stream: %s", waitErr) - } - streamCloseErr = badStream.Close() - if streamCloseErr == nil { - t.Fatalf("No error closing bad stream") - } - - spdyCloseErr := spdyConn.Close() - if spdyCloseErr != nil { - t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestPing(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - pingTime, pingErr := spdyConn.Ping() - if pingErr != nil { - t.Fatalf("Error pinging server: %s", pingErr) - } - if pingTime == time.Duration(0) { - t.Fatalf("Expecting non-zero ping time") - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestHalfClose(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - message := []byte("hello and will read after close") - writeErr := stream.WriteData(message, false) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - streamCloseErr := stream.Close() - if streamCloseErr != nil { - t.Fatalf("Error closing stream: %s", streamCloseErr) - } - - buf := make([]byte, 40) - n, readErr := stream.Read(buf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 31 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) - } - if bytes.Compare(buf[:n], message) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) - } - - spdyCloseErr := spdyConn.Close() - if spdyCloseErr != nil { - t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestUnexpectedRemoteConnectionClosed(t *testing.T) { - tt := []struct { - closeReceiver bool - closeSender bool - }{ - {closeReceiver: true, closeSender: false}, - {closeReceiver: false, closeSender: true}, - {closeReceiver: false, closeSender: false}, - } - for tix, tc := range tt { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - - var serverConn net.Conn - var connErr error - go func() { - serverConn, connErr = listener.Accept() - if connErr != nil { - t.Fatalf("Error accepting: %v", connErr) - } - - serverSpdyConn, _ := NewConnection(serverConn, true) - go serverSpdyConn.Serve(func(stream *Stream) { - stream.SendReply(http.Header{}, tc.closeSender) - }) - }() - - conn, dialErr := net.Dial("tcp", listener.Addr().String()) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - if tc.closeReceiver { - // make stream half closed, receive only - stream.Close() - } - - streamch := make(chan error, 1) - go func() { - b := make([]byte, 1) - _, err := stream.Read(b) - streamch <- err - }() - - closeErr := serverConn.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - - select { - case e := <-streamch: - if e == nil || e != io.EOF { - t.Fatalf("(%d) Expected to get an EOF stream error", tix) - } - } - - closeErr = conn.Close() - if closeErr != nil { - t.Fatalf("Error closing client connection: %s", closeErr) - } - - listenErr = listener.Close() - if listenErr != nil { - t.Fatalf("Error closing listener: %s", listenErr) - } - } -} - -func TestCloseNotification(t *testing.T) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - listen := listener.Addr().String() - - serverConnChan := make(chan net.Conn) - go func() { - serverConn, err := listener.Accept() - if err != nil { - t.Fatalf("Error accepting: %v", err) - } - - serverSpdyConn, err := NewConnection(serverConn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(NoOpStreamHandler) - <-serverSpdyConn.CloseChan() - serverConnChan <- serverConn - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - // close client conn - err := conn.Close() - if err != nil { - t.Fatalf("Error closing client connection: %v", err) - } - - var serverConn net.Conn - select { - case serverConn = <-serverConnChan: - } - - err = serverConn.Close() - if err != nil { - t.Fatalf("Error closing serverConn: %v", err) - } - - listenErr = listener.Close() - if listenErr != nil { - t.Fatalf("Error closing listener: %s", listenErr) - } -} - -func TestIdleShutdownRace(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - spdyConn.SetIdleTimeout(5 * time.Millisecond) - go func() { - time.Sleep(5 * time.Millisecond) - stream.Reset() - }() - - select { - case <-spdyConn.CloseChan(): - case <-time.After(20 * time.Millisecond): - t.Fatal("Timed out waiting for idle connection closure") - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleNoTimeoutSet(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - select { - case <-spdyConn.CloseChan(): - t.Fatal("Unexpected connection closure") - case <-time.After(10 * time.Millisecond): - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleClearTimeout(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - spdyConn.SetIdleTimeout(0) - select { - case <-spdyConn.CloseChan(): - t.Fatal("Unexpected connection closure") - case <-time.After(20 * time.Millisecond): - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleNoData(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - <-spdyConn.CloseChan() - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleWithData(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(25 * time.Millisecond) - - authenticated = true - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - writeCh := make(chan struct{}) - - go func() { - b := []byte{1, 2, 3, 4, 5} - for i := 0; i < 10; i++ { - _, err = stream.Write(b) - if err != nil { - t.Fatalf("Error writing to stream: %v", err) - } - time.Sleep(10 * time.Millisecond) - } - close(writeCh) - }() - - writesFinished := false - -Loop: - for { - select { - case <-writeCh: - writesFinished = true - case <-spdyConn.CloseChan(): - if !writesFinished { - t.Fatal("Connection closed before all writes finished") - } - break Loop - } - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleRace(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - - authenticated = true - - for i := 0; i < 10; i++ { - _, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - } - - <-spdyConn.CloseChan() - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestHalfClosedIdleTimeout(t *testing.T) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - listen := listener.Addr().String() - - go func() { - serverConn, err := listener.Accept() - if err != nil { - t.Fatalf("Error accepting: %v", err) - } - - serverSpdyConn, err := NewConnection(serverConn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(func(s *Stream) { - s.SendReply(http.Header{}, true) - }) - serverSpdyConn.SetIdleTimeout(10 * time.Millisecond) - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - time.Sleep(20 * time.Millisecond) - - stream.Reset() - - err = spdyConn.Close() - if err != nil { - t.Fatalf("Error closing client spdy conn: %v", err) - } -} - -func TestStreamReset(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") - for i := 0; i < 10; i++ { - if _, err := stream.Write(buf); err != nil { - t.Fatalf("Error writing to stream: %s", err) - } - } - for i := 0; i < 10; i++ { - if _, err := stream.Read(buf); err != nil { - t.Fatalf("Error reading from stream: %s", err) - } - } - - // fmt.Printf("Resetting...\n") - if err := stream.Reset(); err != nil { - t.Fatalf("Error reseting stream: %s", err) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestStreamResetWithDataRemaining(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") - for i := 0; i < 10; i++ { - if _, err := stream.Write(buf); err != nil { - t.Fatalf("Error writing to stream: %s", err) - } - } - - // read a bit to make sure a goroutine gets to <-dataChan - if _, err := stream.Read(buf); err != nil { - t.Fatalf("Error reading from stream: %s", err) - } - - // fmt.Printf("Resetting...\n") - if err := stream.Reset(); err != nil { - t.Fatalf("Error reseting stream: %s", err) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -type roundTripper struct { - conn net.Conn -} - -func (s *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - r := *req - req = &r - - conn, err := net.Dial("tcp", req.URL.Host) - if err != nil { - return nil, err - } - - err = req.Write(conn) - if err != nil { - return nil, err - } - - resp, err := http.ReadResponse(bufio.NewReader(conn), req) - if err != nil { - return nil, err - } - - s.conn = conn - - return resp, nil -} - -// see https://github.com/GoogleCloudPlatform/kubernetes/issues/4882 -func TestFramingAfterRemoteConnectionClosed(t *testing.T) { - server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - streamCh := make(chan *Stream) - - w.WriteHeader(http.StatusSwitchingProtocols) - - netconn, _, _ := w.(http.Hijacker).Hijack() - conn, _ := NewConnection(netconn, true) - go conn.Serve(func(s *Stream) { - s.SendReply(http.Header{}, false) - streamCh <- s - }) - - stream := <-streamCh - io.Copy(stream, stream) - - closeChan := make(chan struct{}) - go func() { - stream.Reset() - conn.Close() - close(closeChan) - }() - - <-closeChan - })) - - server.Start() - defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("Error creating request: %s", err) - } - - rt := &roundTripper{} - client := &http.Client{Transport: rt} - - _, err = client.Do(req) - if err != nil { - t.Fatalf("unexpected error from client.Do: %s", err) - } - - conn, err := NewConnection(rt.conn, false) - go conn.Serve(NoOpStreamHandler) - - stream, err := conn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("error creating client stream: %s", err) - } - - n, err := stream.Write([]byte("hello")) - if err != nil { - t.Fatalf("error writing to stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to write 5 bytes, but actually wrote %d", n) - } - - b := make([]byte, 5) - n, err = stream.Read(b) - if err != nil { - t.Fatalf("error reading from stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to read 5 bytes, but actually read %d", n) - } - if e, a := "hello", string(b[0:n]); e != a { - t.Fatalf("expected '%s', got '%s'", e, a) - } - - stream.Reset() - conn.Close() -} - -var authenticated bool - -func authStreamHandler(stream *Stream) { - if !authenticated { - stream.Refuse() - } - MirrorStreamHandler(stream) -} - -func runServer(wg *sync.WaitGroup) (io.Closer, string, error) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - return nil, "", listenErr - } - wg.Add(1) - go func() { - for { - conn, connErr := listener.Accept() - if connErr != nil { - break - } - - spdyConn, _ := NewConnection(conn, true) - go spdyConn.Serve(authStreamHandler) - - } - wg.Done() - }() - return listener, listener.Addr().String(), nil -} diff --git a/Godeps/_workspace/src/github.com/docker/spdystream/ws/ws_test.go b/Godeps/_workspace/src/github.com/docker/spdystream/ws/ws_test.go deleted file mode 100644 index 36c4a46ac84..00000000000 --- a/Godeps/_workspace/src/github.com/docker/spdystream/ws/ws_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package ws - -import ( - "bytes" - "github.com/docker/spdystream" - "github.com/gorilla/websocket" - "io" - "log" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -var upgrader = websocket.Upgrader{ - ReadBufferSize: 1024, - WriteBufferSize: 1024, -} - -var serverSpdyConn *spdystream.Connection - -// Connect to the Websocket endpoint at ws://localhost -// using SPDY over Websockets framing. -func ExampleConn() { - wsconn, _, _ := websocket.DefaultDialer.Dial("ws://localhost/", http.Header{"Origin": {"http://localhost/"}}) - conn, _ := spdystream.NewConnection(NewConnection(wsconn), false) - go conn.Serve(spdystream.NoOpStreamHandler, spdystream.NoAuthHandler) - stream, _ := conn.CreateStream(http.Header{}, nil, false) - stream.Wait() -} - -func serveWs(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - http.Error(w, "Method not allowed", 405) - return - } - - ws, err := upgrader.Upgrade(w, r, nil) - if err != nil { - if _, ok := err.(websocket.HandshakeError); !ok { - log.Println(err) - } - return - } - - wrap := NewConnection(ws) - spdyConn, err := spdystream.NewConnection(wrap, true) - if err != nil { - log.Fatal(err) - return - } - serverSpdyConn = spdyConn - go spdyConn.Serve(spdystream.MirrorStreamHandler, authStreamHandler) -} - -func TestSpdyStreamOverWs(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(serveWs)) - defer server.Close() - defer func() { - if serverSpdyConn != nil { - serverSpdyConn.Close() - } - }() - - wsconn, _, err := websocket.DefaultDialer.Dial(strings.Replace(server.URL, "http://", "ws://", 1), http.Header{"Origin": {server.URL}}) - if err != nil { - t.Fatal(err) - } - - wrap := NewConnection(wsconn) - spdyConn, err := spdystream.NewConnection(wrap, false) - if err != nil { - defer wsconn.Close() - t.Fatal(err) - } - defer spdyConn.Close() - authenticated = true - go spdyConn.Serve(spdystream.NoOpStreamHandler, spdystream.RejectAuthHandler) - - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - message := []byte("hello") - writeErr := stream.WriteData(message, false) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - buf := make([]byte, 10) - n, readErr := stream.Read(buf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 5 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) - } - if bytes.Compare(buf[:n], message) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) - } - - writeErr = stream.WriteData(message, true) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - smallBuf := make([]byte, 3) - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 3 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 3", n) - } - if bytes.Compare(smallBuf[:n], []byte("hel")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", smallBuf[:n], message) - } - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 2 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 2", n) - } - if bytes.Compare(smallBuf[:n], []byte("lo")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpected: lo", smallBuf[:n]) - } - - n, readErr = stream.Read(buf) - if readErr != io.EOF { - t.Fatalf("Expected EOF reading from finished stream, read %d bytes", n) - } - - streamCloseErr := stream.Close() - if streamCloseErr != nil { - t.Fatalf("Error closing stream: %s", streamCloseErr) - } - - // Closing again should return nil - streamCloseErr = stream.Close() - if streamCloseErr != nil { - t.Fatalf("Error closing stream: %s", streamCloseErr) - } - - authenticated = false - badStream, badStreamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if badStreamErr != nil { - t.Fatalf("Error creating stream: %s", badStreamErr) - } - - waitErr = badStream.Wait() - if waitErr == nil { - t.Fatalf("Did not receive error creating stream") - } - if waitErr != spdystream.ErrReset { - t.Fatalf("Unexpected error creating stream: %s", waitErr) - } - - spdyCloseErr := spdyConn.Close() - if spdyCloseErr != nil { - t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) - } -} - -var authenticated bool - -func authStreamHandler(header http.Header, slot uint8, parent uint32) bool { - return authenticated -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/counterecryptor_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/counterecryptor_test.go deleted file mode 100644 index 12b31e16f48..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/counterecryptor_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package goproxy_test - -import ( - "bytes" - "crypto/rsa" - "encoding/binary" - "github.com/elazarl/goproxy" - "io" - "math" - "math/rand" - "testing" -) - -type RandSeedReader struct { - r rand.Rand -} - -func (r *RandSeedReader) Read(b []byte) (n int, err error) { - for i := range b { - b[i] = byte(r.r.Int() & 0xFF) - } - return len(b), nil -} - -func TestCounterEncDifferentConsecutive(t *testing.T) { - k, err := rsa.GenerateKey(&RandSeedReader{*rand.New(rand.NewSource(0xFF43109))}, 128) - fatalOnErr(err, "rsa.GenerateKey", t) - c, err := goproxy.NewCounterEncryptorRandFromKey(k, []byte("the quick brown fox run over the lazy dog")) - fatalOnErr(err, "NewCounterEncryptorRandFromKey", t) - for i := 0; i < 100*1000; i++ { - var a, b int64 - binary.Read(&c, binary.BigEndian, &a) - binary.Read(&c, binary.BigEndian, &b) - if a == b { - t.Fatal("two consecutive equal int64", a, b) - } - } -} - -func TestCounterEncIdenticalStreams(t *testing.T) { - k, err := rsa.GenerateKey(&RandSeedReader{*rand.New(rand.NewSource(0xFF43109))}, 128) - fatalOnErr(err, "rsa.GenerateKey", t) - c1, err := goproxy.NewCounterEncryptorRandFromKey(k, []byte("the quick brown fox run over the lazy dog")) - fatalOnErr(err, "NewCounterEncryptorRandFromKey", t) - c2, err := goproxy.NewCounterEncryptorRandFromKey(k, []byte("the quick brown fox run over the lazy dog")) - fatalOnErr(err, "NewCounterEncryptorRandFromKey", t) - nout := 1000 - out1, out2 := make([]byte, nout), make([]byte, nout) - io.ReadFull(&c1, out1) - tmp := out2[:] - rand.Seed(0xFF43109) - for len(tmp) > 0 { - n := 1 + rand.Intn(256) - if n > len(tmp) { - n = len(tmp) - } - n, err := c2.Read(tmp[:n]) - fatalOnErr(err, "CounterEncryptorRand.Read", t) - tmp = tmp[n:] - } - if !bytes.Equal(out1, out2) { - t.Error("identical CSPRNG does not produce the same output") - } -} - -func stddev(data []int) float64 { - var sum, sum_sqr float64 = 0, 0 - for _, h := range data { - sum += float64(h) - sum_sqr += float64(h) * float64(h) - } - n := float64(len(data)) - variance := (sum_sqr - ((sum * sum) / n)) / (n - 1) - return math.Sqrt(variance) -} - -func TestCounterEncStreamHistogram(t *testing.T) { - k, err := rsa.GenerateKey(&RandSeedReader{*rand.New(rand.NewSource(0xFF43109))}, 128) - fatalOnErr(err, "rsa.GenerateKey", t) - c, err := goproxy.NewCounterEncryptorRandFromKey(k, []byte("the quick brown fox run over the lazy dog")) - fatalOnErr(err, "NewCounterEncryptorRandFromKey", t) - nout := 100 * 1000 - out := make([]byte, nout) - io.ReadFull(&c, out) - refhist := make([]int, 256) - for i := 0; i < nout; i++ { - refhist[rand.Intn(256)]++ - } - hist := make([]int, 256) - for _, b := range out { - hist[int(b)]++ - } - refstddev, stddev := stddev(refhist), stddev(hist) - // due to lack of time, I guestimate - t.Logf("ref:%v - act:%v = %v", refstddev, stddev, math.Abs(refstddev-stddev)) - if math.Abs(refstddev-stddev) >= 1 { - t.Errorf("stddev of ref histogram different than regular PRNG: %v %v", refstddev, stddev) - } -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/examples/goproxy-jquery-version/jquery_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/examples/goproxy-jquery-version/jquery_test.go deleted file mode 100644 index af300aaf31a..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/examples/goproxy-jquery-version/jquery_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package main - -import ( - "bytes" - "io/ioutil" - "log" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" -) - -func equal(u, v []string) bool { - if len(u) != len(v) { - return false - } - for i, _ := range u { - if u[i] != v[i] { - return false - } - } - return true -} - -func readFile(fname string, t *testing.T) string { - b, err := ioutil.ReadFile(fname) - if err != nil { - t.Fatal("readFile", err) - } - return string(b) -} - -func TestDefectiveScriptParser(t *testing.T) { - if l := len(findScriptSrc(` - - - - - - - `)); l != 0 { - t.Fail() - } - urls := findScriptSrc(readFile("w3schools.html", t)) - if !equal(urls, []string{"http://partner.googleadservices.com/gampad/google_service.js", - "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"}) { - t.Error("w3schools.html", "src scripts are not recognized", urls) - } - urls = findScriptSrc(readFile("jquery_homepage.html", t)) - if !equal(urls, []string{"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", - "http://code.jquery.com/jquery-1.4.2.min.js", - "http://static.jquery.com/files/rocker/scripts/custom.js", - "http://static.jquery.com/donate/donate.js"}) { - t.Error("jquery_homepage.html", "src scripts are not recognized", urls) - } -} - -func proxyWithLog() (*http.Client, *bytes.Buffer) { - proxy := NewJqueryVersionProxy() - proxyServer := httptest.NewServer(proxy) - buf := new(bytes.Buffer) - proxy.Logger = log.New(buf, "", 0) - proxyUrl, _ := url.Parse(proxyServer.URL) - tr := &http.Transport{Proxy: http.ProxyURL(proxyUrl)} - client := &http.Client{Transport: tr} - return client, buf -} - -func get(t *testing.T, server *httptest.Server, client *http.Client, url string) { - resp, err := client.Get(server.URL + url) - if err != nil { - t.Fatal("cannot get proxy", err) - } - ioutil.ReadAll(resp.Body) - resp.Body.Close() -} - -func TestProxyServiceTwoVersions(t *testing.T) { - var fs = httptest.NewServer(http.FileServer(http.Dir("."))) - defer fs.Close() - - client, buf := proxyWithLog() - - get(t, fs, client, "/w3schools.html") - get(t, fs, client, "/php_man.html") - if buf.String() != "" && - !strings.Contains(buf.String(), " uses jquery ") { - t.Error("shouldn't warn on a single URL", buf.String()) - } - get(t, fs, client, "/jquery1.html") - warnings := buf.String() - if !strings.Contains(warnings, "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js") || - !strings.Contains(warnings, "jquery.1.4.js") || - !strings.Contains(warnings, "Contradicting") { - t.Error("contradicting jquery versions (php_man.html, w3schools.html) does not issue warning", warnings) - } -} - -func TestProxyService(t *testing.T) { - var fs = httptest.NewServer(http.FileServer(http.Dir("."))) - defer fs.Close() - - client, buf := proxyWithLog() - - get(t, fs, client, "/jquery_homepage.html") - warnings := buf.String() - if !strings.Contains(warnings, "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js") || - !strings.Contains(warnings, "http://code.jquery.com/jquery-1.4.2.min.js") || - !strings.Contains(warnings, "Contradicting") { - t.Error("contradicting jquery versions does not issue warning") - } -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/auth/basic_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/auth/basic_test.go deleted file mode 100644 index 792d789bcd2..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/auth/basic_test.go +++ /dev/null @@ -1,175 +0,0 @@ -package auth_test - -import ( - "encoding/base64" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "os/signal" - "sync/atomic" - "testing" - - "github.com/elazarl/goproxy" - "github.com/elazarl/goproxy/ext/auth" -) - -type ConstantHanlder string - -func (h ConstantHanlder) ServeHTTP(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, string(h)) -} - -func oneShotProxy(proxy *goproxy.ProxyHttpServer) (client *http.Client, s *httptest.Server) { - s = httptest.NewServer(proxy) - - proxyUrl, _ := url.Parse(s.URL) - tr := &http.Transport{Proxy: http.ProxyURL(proxyUrl)} - client = &http.Client{Transport: tr} - return -} - -func times(n int, s string) string { - r := make([]byte, 0, n*len(s)) - for i := 0; i < n; i++ { - r = append(r, s...) - } - return string(r) -} - -func TestBasicConnectAuthWithCurl(t *testing.T) { - expected := ":c>" - background := httptest.NewTLSServer(ConstantHanlder(expected)) - defer background.Close() - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().HandleConnect(auth.BasicConnect("my_realm", func(user, passwd string) bool { - return user == "user" && passwd == "open sesame" - })) - _, proxyserver := oneShotProxy(proxy) - defer proxyserver.Close() - - cmd := exec.Command("curl", - "--silent", "--show-error", "--insecure", - "-x", proxyserver.URL, - "-U", "user:open sesame", - "-p", - "--url", background.URL+"/[1-3]", - ) - out, err := cmd.CombinedOutput() // if curl got error, it'll show up in stderr - if err != nil { - t.Fatal(err, string(out)) - } - finalexpected := times(3, expected) - if string(out) != finalexpected { - t.Error("Expected", finalexpected, "got", string(out)) - } -} - -func TestBasicAuthWithCurl(t *testing.T) { - expected := ":c>" - background := httptest.NewServer(ConstantHanlder(expected)) - defer background.Close() - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().Do(auth.Basic("my_realm", func(user, passwd string) bool { - return user == "user" && passwd == "open sesame" - })) - _, proxyserver := oneShotProxy(proxy) - defer proxyserver.Close() - - cmd := exec.Command("curl", - "--silent", "--show-error", - "-x", proxyserver.URL, - "-U", "user:open sesame", - "--url", background.URL+"/[1-3]", - ) - out, err := cmd.CombinedOutput() // if curl got error, it'll show up in stderr - if err != nil { - t.Fatal(err, string(out)) - } - finalexpected := times(3, expected) - if string(out) != finalexpected { - t.Error("Expected", finalexpected, "got", string(out)) - } -} - -func TestBasicAuth(t *testing.T) { - expected := "hello" - background := httptest.NewServer(ConstantHanlder(expected)) - defer background.Close() - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().Do(auth.Basic("my_realm", func(user, passwd string) bool { - return user == "user" && passwd == "open sesame" - })) - client, proxyserver := oneShotProxy(proxy) - defer proxyserver.Close() - - // without auth - resp, err := client.Get(background.URL) - if err != nil { - t.Fatal(err) - } - if resp.Header.Get("Proxy-Authenticate") != "Basic realm=my_realm" { - t.Error("Expected Proxy-Authenticate header got", resp.Header.Get("Proxy-Authenticate")) - } - if resp.StatusCode != 407 { - t.Error("Expected status 407 Proxy Authentication Required, got", resp.Status) - } - - // with auth - req, err := http.NewRequest("GET", background.URL, nil) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Proxy-Authorization", - "Basic "+base64.StdEncoding.EncodeToString([]byte("user:open sesame"))) - resp, err = client.Do(req) - if err != nil { - t.Fatal(err) - } - if resp.StatusCode != 200 { - t.Error("Expected status 200 OK, got", resp.Status) - } - msg, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatal(err) - } - if string(msg) != "hello" { - t.Errorf("Expected '%s', actual '%s'", expected, string(msg)) - } -} - -func TestWithBrowser(t *testing.T) { - // an easy way to check if auth works with webserver - // to test, run with - // $ go test -run TestWithBrowser -- server - // configure a browser to use the printed proxy address, use the proxy - // and exit with Ctrl-C. It will throw error if your haven't acutally used the proxy - if os.Args[len(os.Args)-1] != "server" { - return - } - proxy := goproxy.NewProxyHttpServer() - println("proxy localhost port 8082") - access := int32(0) - proxy.OnRequest().Do(auth.Basic("my_realm", func(user, passwd string) bool { - atomic.AddInt32(&access, 1) - return user == "user" && passwd == "1234" - })) - l, err := net.Listen("tcp", "localhost:8082") - if err != nil { - t.Fatal(err) - } - ch := make(chan os.Signal) - signal.Notify(ch, os.Interrupt) - go func() { - <-ch - l.Close() - }() - http.Serve(l, proxy) - if access <= 0 { - t.Error("No one accessed the proxy") - } -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/html/html_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/html/html_test.go deleted file mode 100644 index 9c876f75224..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/ext/html/html_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package goproxy_html_test - -import ( - "github.com/elazarl/goproxy" - "github.com/elazarl/goproxy/ext/html" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "testing" -) - -type ConstantServer int - -func (s ConstantServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain; charset=iso-8859-8") - //w.Header().Set("Content-Type","text/plain; charset=cp-1255") - w.Write([]byte{0xe3, 0xf3}) -} - -func TestCharset(t *testing.T) { - s := httptest.NewServer(ConstantServer(1)) - defer s.Close() - - ch := make(chan string, 2) - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse().Do(goproxy_html.HandleString( - func(s string, ctx *goproxy.ProxyCtx) string { - ch <- s - return s - })) - proxyServer := httptest.NewServer(proxy) - defer proxyServer.Close() - - proxyUrl, _ := url.Parse(proxyServer.URL) - client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}} - - resp, err := client.Get(s.URL + "/cp1255.txt") - if err != nil { - t.Fatal("GET:", err) - } - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatal("readAll:", err) - } - resp.Body.Close() - - inHandleString := "" - select { - case inHandleString = <-ch: - default: - } - - if len(b) != 2 || b[0] != 0xe3 || b[1] != 0xf3 { - t.Error("Did not translate back to 0xe3,0xf3, instead", b) - } - if inHandleString != "דף" { - t.Error("HandleString did not convert DALET & PEH SOFIT (דף) from ISO-8859-8 to utf-8, got", []byte(inHandleString)) - } -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/proxy_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/proxy_test.go deleted file mode 100644 index 8b147cfd04e..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/proxy_test.go +++ /dev/null @@ -1,767 +0,0 @@ -package goproxy_test - -import ( - "bufio" - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/base64" - "image" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "strings" - "testing" - - "github.com/elazarl/goproxy" - "github.com/elazarl/goproxy/ext/image" -) - -var acceptAllCerts = &tls.Config{InsecureSkipVerify: true} - -var noProxyClient = &http.Client{Transport: &http.Transport{TLSClientConfig: acceptAllCerts}} - -var https = httptest.NewTLSServer(nil) -var srv = httptest.NewServer(nil) -var fs = httptest.NewServer(http.FileServer(http.Dir("."))) - -type QueryHandler struct{} - -func (QueryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if err := req.ParseForm(); err != nil { - panic(err) - } - io.WriteString(w, req.Form.Get("result")) -} - -func init() { - http.DefaultServeMux.Handle("/bobo", ConstantHanlder("bobo")) - http.DefaultServeMux.Handle("/query", QueryHandler{}) -} - -type ConstantHanlder string - -func (h ConstantHanlder) ServeHTTP(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, string(h)) -} - -func get(url string, client *http.Client) ([]byte, error) { - resp, err := client.Get(url) - if err != nil { - return nil, err - } - txt, err := ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return nil, err - } - return txt, nil -} - -func getOrFail(url string, client *http.Client, t *testing.T) []byte { - txt, err := get(url, client) - if err != nil { - t.Fatal("Can't fetch url", url, err) - } - return txt -} - -func localFile(url string) string { return fs.URL + "/" + url } -func localTls(url string) string { return https.URL + url } - -func TestSimpleHttpReqWithProxy(t *testing.T) { - client, s := oneShotProxy(goproxy.NewProxyHttpServer(), t) - defer s.Close() - - if r := string(getOrFail(srv.URL+"/bobo", client, t)); r != "bobo" { - t.Error("proxy server does not serve constant handlers", r) - } - if r := string(getOrFail(srv.URL+"/bobo", client, t)); r != "bobo" { - t.Error("proxy server does not serve constant handlers", r) - } - - if string(getOrFail(https.URL+"/bobo", client, t)) != "bobo" { - t.Error("TLS server does not serve constant handlers, when proxy is used") - } -} - -func oneShotProxy(proxy *goproxy.ProxyHttpServer, t *testing.T) (client *http.Client, s *httptest.Server) { - s = httptest.NewServer(proxy) - - proxyUrl, _ := url.Parse(s.URL) - tr := &http.Transport{TLSClientConfig: acceptAllCerts, Proxy: http.ProxyURL(proxyUrl)} - client = &http.Client{Transport: tr} - return -} - -func TestSimpleHook(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest(goproxy.SrcIpIs("127.0.0.1")).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - req.URL.Path = "/bobo" - return req, nil - }) - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "bobo" { - t.Error("Redirecting all requests from 127.0.0.1 to bobo, didn't work." + - " (Might break if Go's client sets RemoteAddr to IPv6 address). Got: " + - result) - } -} - -func TestAlwaysHook(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - req.URL.Path = "/bobo" - return req, nil - }) - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "bobo" { - t.Error("Redirecting all requests from 127.0.0.1 to bobo, didn't work." + - " (Might break if Go's client sets RemoteAddr to IPv6 address). Got: " + - result) - } -} - -func TestReplaceResponse(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - resp.StatusCode = http.StatusOK - resp.Body = ioutil.NopCloser(bytes.NewBufferString("chico")) - return resp - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if result := string(getOrFail(srv.URL+("/momo"), client, t)); result != "chico" { - t.Error("hooked response, should be chico, instead:", result) - } -} - -func TestReplaceReponseForUrl(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse(goproxy.UrlIs("/koko")).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - resp.StatusCode = http.StatusOK - resp.Body = ioutil.NopCloser(bytes.NewBufferString("chico")) - return resp - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if result := string(getOrFail(srv.URL+("/koko"), client, t)); result != "chico" { - t.Error("hooked 'koko', should be chico, instead:", result) - } - if result := string(getOrFail(srv.URL+("/bobo"), client, t)); result != "bobo" { - t.Error("still, bobo should stay as usual, instead:", result) - } -} - -func TestOneShotFileServer(t *testing.T) { - client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t) - defer l.Close() - - file := "test_data/panda.png" - info, err := os.Stat(file) - if err != nil { - t.Fatal("Cannot find", file) - } - if resp, err := client.Get(fs.URL + "/" + file); err == nil { - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatal("got", string(b)) - } - if int64(len(b)) != info.Size() { - t.Error("Expected Length", file, info.Size(), "actually", len(b), "starts", string(b[:10])) - } - } else { - t.Fatal("Cannot read from fs server", err) - } -} - -func TestContentType(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse(goproxy.ContentTypeIs("image/png")).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - resp.Header.Set("X-Shmoopi", "1") - return resp - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - for _, file := range []string{"test_data/panda.png", "test_data/football.png"} { - if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "1" { - if err == nil { - t.Error("pngs should have X-Shmoopi header = 1, actually", resp.Header.Get("X-Shmoopi")) - } else { - t.Error("error reading png", err) - } - } - } - - file := "baby.jpg" - if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "" { - if err == nil { - t.Error("Non png images should NOT have X-Shmoopi header at all", resp.Header.Get("X-Shmoopi")) - } else { - t.Error("error reading png", err) - } - } -} - -func getImage(file string, t *testing.T) image.Image { - newimage, err := ioutil.ReadFile(file) - if err != nil { - t.Fatal("Cannot read file", file, err) - } - img, _, err := image.Decode(bytes.NewReader(newimage)) - if err != nil { - t.Fatal("Cannot decode image", file, err) - } - return img -} - -func readAll(r io.Reader, t *testing.T) []byte { - b, err := ioutil.ReadAll(r) - if err != nil { - t.Fatal("Cannot read", err) - } - return b -} -func readFile(file string, t *testing.T) []byte { - b, err := ioutil.ReadFile(file) - if err != nil { - t.Fatal("Cannot read", err) - } - return b -} -func fatalOnErr(err error, msg string, t *testing.T) { - if err != nil { - t.Fatal(msg, err) - } -} -func panicOnErr(err error, msg string) { - if err != nil { - println(err.Error() + ":-" + msg) - os.Exit(-1) - } -} - -func compareImage(eImg, aImg image.Image, t *testing.T) { - if eImg.Bounds().Dx() != aImg.Bounds().Dx() || eImg.Bounds().Dy() != aImg.Bounds().Dy() { - t.Error("image sizes different") - return - } - for i := 0; i < eImg.Bounds().Dx(); i++ { - for j := 0; j < eImg.Bounds().Dy(); j++ { - er, eg, eb, ea := eImg.At(i, j).RGBA() - ar, ag, ab, aa := aImg.At(i, j).RGBA() - if er != ar || eg != ag || eb != ab || ea != aa { - t.Error("images different at", i, j, "vals\n", er, eg, eb, ea, "\n", ar, ag, ab, aa, aa) - return - } - } - } -} - -func TestConstantImageHandler(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - //panda := getImage("panda.png", t) - football := getImage("test_data/football.png", t) - proxy.OnResponse().Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { - return football - })) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - resp, err := client.Get(localFile("test_data/panda.png")) - if err != nil { - t.Fatal("Cannot get panda.png", err) - } - - img, _, err := image.Decode(resp.Body) - if err != nil { - t.Error("decode", err) - } else { - compareImage(football, img, t) - } -} - -func TestImageHandler(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - football := getImage("test_data/football.png", t) - - proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { - return football - })) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - resp, err := client.Get(localFile("test_data/panda.png")) - if err != nil { - t.Fatal("Cannot get panda.png", err) - } - - img, _, err := image.Decode(resp.Body) - if err != nil { - t.Error("decode", err) - } else { - compareImage(football, img, t) - } - - // and again - resp, err = client.Get(localFile("test_data/panda.png")) - if err != nil { - t.Fatal("Cannot get panda.png", err) - } - - img, _, err = image.Decode(resp.Body) - if err != nil { - t.Error("decode", err) - } else { - compareImage(football, img, t) - } -} - -func TestChangeResp(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - resp.Body.Read([]byte{0}) - resp.Body = ioutil.NopCloser(new(bytes.Buffer)) - return resp - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - resp, err := client.Get(localFile("test_data/panda.png")) - if err != nil { - t.Fatal(err) - } - ioutil.ReadAll(resp.Body) - _, err = client.Get(localFile("/bobo")) - if err != nil { - t.Fatal(err) - } -} -func TestReplaceImage(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - - panda := getImage("test_data/panda.png", t) - football := getImage("test_data/football.png", t) - - proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { - return football - })) - proxy.OnResponse(goproxy.UrlIs("/test_data/football.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { - return panda - })) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - imgByPandaReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/panda.png"), client, t))) - fatalOnErr(err, "decode panda", t) - compareImage(football, imgByPandaReq, t) - - imgByFootballReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/football.png"), client, t))) - fatalOnErr(err, "decode football", t) - compareImage(panda, imgByFootballReq, t) -} - -func getCert(c *tls.Conn, t *testing.T) []byte { - if err := c.Handshake(); err != nil { - t.Fatal("cannot handshake", err) - } - return c.ConnectionState().PeerCertificates[0].Raw -} - -func TestSimpleMitm(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest(goproxy.ReqHostIs(https.Listener.Addr().String())).HandleConnect(goproxy.AlwaysMitm) - proxy.OnRequest(goproxy.ReqHostIs("no such host exists")).HandleConnect(goproxy.AlwaysMitm) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - c, err := tls.Dial("tcp", https.Listener.Addr().String(), &tls.Config{InsecureSkipVerify: true}) - if err != nil { - t.Fatal("cannot dial to tcp server", err) - } - origCert := getCert(c, t) - c.Close() - - c2, err := net.Dial("tcp", l.Listener.Addr().String()) - if err != nil { - t.Fatal("dialing to proxy", err) - } - creq, err := http.NewRequest("CONNECT", https.URL, nil) - //creq,err := http.NewRequest("CONNECT","https://google.com:443",nil) - if err != nil { - t.Fatal("create new request", creq) - } - creq.Write(c2) - c2buf := bufio.NewReader(c2) - resp, err := http.ReadResponse(c2buf, creq) - if err != nil || resp.StatusCode != 200 { - t.Fatal("Cannot CONNECT through proxy", err) - } - c2tls := tls.Client(c2, &tls.Config{InsecureSkipVerify: true}) - proxyCert := getCert(c2tls, t) - - if bytes.Equal(proxyCert, origCert) { - t.Errorf("Certificate after mitm is not different\n%v\n%v", - base64.StdEncoding.EncodeToString(origCert), - base64.StdEncoding.EncodeToString(proxyCert)) - } - - if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" { - t.Error("Wrong response when mitm", resp, "expected bobo") - } - if resp := string(getOrFail(https.URL+"/query?result=bar", client, t)); resp != "bar" { - t.Error("Wrong response when mitm", resp, "expected bar") - } -} - -func TestConnectHandler(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - althttps := httptest.NewTLSServer(ConstantHanlder("althttps")) - proxy.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) { - u, _ := url.Parse(althttps.URL) - return goproxy.OkConnect, u.Host - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - if resp := string(getOrFail(https.URL+"/alturl", client, t)); resp != "althttps" { - t.Error("Proxy should redirect CONNECT requests to local althttps server, expected 'althttps' got ", resp) - } -} - -func TestMitmIsFiltered(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - //proxy.Verbose = true - proxy.OnRequest(goproxy.ReqHostIs(https.Listener.Addr().String())).HandleConnect(goproxy.AlwaysMitm) - proxy.OnRequest(goproxy.UrlIs("/momo")).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - return nil, goproxy.TextResponse(req, "koko") - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if resp := string(getOrFail(https.URL+"/momo", client, t)); resp != "koko" { - t.Error("Proxy should capture /momo to be koko and not", resp) - } - - if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" { - t.Error("But still /bobo should be bobo and not", resp) - } -} - -func TestFirstHandlerMatches(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - return nil, goproxy.TextResponse(req, "koko") - }) - proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - panic("should never get here, previous response is no null") - }) - - client, l := oneShotProxy(proxy, t) - defer l.Close() - - if resp := string(getOrFail(srv.URL+"/", client, t)); resp != "koko" { - t.Error("should return always koko and not", resp) - } -} - -func constantHttpServer(content []byte) (addr string) { - l, err := net.Listen("tcp", "localhost:0") - panicOnErr(err, "listen") - go func() { - c, err := l.Accept() - panicOnErr(err, "accept") - buf := bufio.NewReader(c) - _, err = http.ReadRequest(buf) - panicOnErr(err, "readReq") - c.Write(content) - c.Close() - l.Close() - }() - return l.Addr().String() -} - -func TestIcyResponse(t *testing.T) { - // TODO: fix this test - return // skip for now - s := constantHttpServer([]byte("ICY 200 OK\r\n\r\nblablabla")) - proxy := goproxy.NewProxyHttpServer() - proxy.Verbose = true - _, l := oneShotProxy(proxy, t) - defer l.Close() - req, err := http.NewRequest("GET", "http://"+s, nil) - panicOnErr(err, "newReq") - proxyip := l.URL[len("http://"):] - println("got ip: " + proxyip) - c, err := net.Dial("tcp", proxyip) - panicOnErr(err, "dial") - defer c.Close() - req.WriteProxy(c) - raw, err := ioutil.ReadAll(c) - panicOnErr(err, "readAll") - if string(raw) != "ICY 200 OK\r\n\r\nblablabla" { - t.Error("Proxy did not send the malformed response received") - } -} - -type VerifyNoProxyHeaders struct { - *testing.T -} - -func (v VerifyNoProxyHeaders) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Connection") != "" || r.Header.Get("Proxy-Connection") != "" || - r.Header.Get("Proxy-Authenticate") != "" || r.Header.Get("Proxy-Authorization") != "" { - v.Error("Got Connection header from goproxy", r.Header) - } -} - -func TestNoProxyHeaders(t *testing.T) { - s := httptest.NewServer(VerifyNoProxyHeaders{t}) - client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t) - defer l.Close() - req, err := http.NewRequest("GET", s.URL, nil) - panicOnErr(err, "bad request") - req.Header.Add("Connection", "close") - req.Header.Add("Proxy-Connection", "close") - req.Header.Add("Proxy-Authenticate", "auth") - req.Header.Add("Proxy-Authorization", "auth") - client.Do(req) -} - -func TestNoProxyHeadersHttps(t *testing.T) { - s := httptest.NewTLSServer(VerifyNoProxyHeaders{t}) - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) - client, l := oneShotProxy(proxy, t) - defer l.Close() - req, err := http.NewRequest("GET", s.URL, nil) - panicOnErr(err, "bad request") - req.Header.Add("Connection", "close") - req.Header.Add("Proxy-Connection", "close") - client.Do(req) -} - -func TestHeadReqHasContentLength(t *testing.T) { - client, l := oneShotProxy(goproxy.NewProxyHttpServer(), t) - defer l.Close() - - resp, err := client.Head(localFile("test_data/panda.png")) - panicOnErr(err, "resp to HEAD") - if resp.Header.Get("Content-Length") == "" { - t.Error("Content-Length should exist on HEAD requests") - } -} - -func TestChunkedResponse(t *testing.T) { - l, err := net.Listen("tcp", ":10234") - panicOnErr(err, "listen") - defer l.Close() - go func() { - for i := 0; i < 2; i++ { - c, err := l.Accept() - panicOnErr(err, "accept") - _, err = http.ReadRequest(bufio.NewReader(c)) - panicOnErr(err, "readrequest") - io.WriteString(c, "HTTP/1.1 200 OK\r\n"+ - "Content-Type: text/plain\r\n"+ - "Transfer-Encoding: chunked\r\n\r\n"+ - "25\r\n"+ - "This is the data in the first chunk\r\n\r\n"+ - "1C\r\n"+ - "and this is the second one\r\n\r\n"+ - "3\r\n"+ - "con\r\n"+ - "8\r\n"+ - "sequence\r\n0\r\n\r\n") - c.Close() - } - }() - - c, err := net.Dial("tcp", "localhost:10234") - panicOnErr(err, "dial") - defer c.Close() - req, _ := http.NewRequest("GET", "/", nil) - req.Write(c) - resp, err := http.ReadResponse(bufio.NewReader(c), req) - panicOnErr(err, "readresp") - b, err := ioutil.ReadAll(resp.Body) - panicOnErr(err, "readall") - expected := "This is the data in the first chunk\r\nand this is the second one\r\nconsequence" - if string(b) != expected { - t.Errorf("Got `%v` expected `%v`", string(b), expected) - } - - proxy := goproxy.NewProxyHttpServer() - proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - panicOnErr(ctx.Error, "error reading output") - b, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - panicOnErr(err, "readall onresp") - if enc := resp.Header.Get("Transfer-Encoding"); enc != "" { - t.Fatal("Chunked response should be received as plaintext", enc) - } - resp.Body = ioutil.NopCloser(bytes.NewBufferString(strings.Replace(string(b), "e", "E", -1))) - return resp - }) - - client, s := oneShotProxy(proxy, t) - defer s.Close() - - resp, err = client.Get("http://localhost:10234/") - panicOnErr(err, "client.Get") - b, err = ioutil.ReadAll(resp.Body) - panicOnErr(err, "readall proxy") - if string(b) != strings.Replace(expected, "e", "E", -1) { - t.Error("expected", expected, "w/ e->E. Got", string(b)) - } -} - -func TestGoproxyThroughProxy(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy2 := goproxy.NewProxyHttpServer() - doubleString := func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response { - b, err := ioutil.ReadAll(resp.Body) - panicOnErr(err, "readAll resp") - resp.Body = ioutil.NopCloser(bytes.NewBufferString(string(b) + " " + string(b))) - return resp - } - proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) - proxy.OnResponse().DoFunc(doubleString) - - _, l := oneShotProxy(proxy, t) - defer l.Close() - - proxy2.ConnectDial = proxy2.NewConnectDialToProxy(l.URL) - - client, l2 := oneShotProxy(proxy2, t) - defer l2.Close() - if r := string(getOrFail(https.URL+"/bobo", client, t)); r != "bobo bobo" { - t.Error("Expected bobo doubled twice, got", r) - } - -} - -func TestGoproxyHijackConnect(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest(goproxy.ReqHostIs(srv.Listener.Addr().String())). - HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) { - t.Logf("URL %+#v\nSTR %s", req.URL, req.URL.String()) - resp, err := http.Get("http:" + req.URL.String() + "/bobo") - panicOnErr(err, "http.Get(CONNECT url)") - panicOnErr(resp.Write(client), "resp.Write(client)") - resp.Body.Close() - client.Close() - }) - client, l := oneShotProxy(proxy, t) - defer l.Close() - proxyAddr := l.Listener.Addr().String() - conn, err := net.Dial("tcp", proxyAddr) - panicOnErr(err, "conn "+proxyAddr) - buf := bufio.NewReader(conn) - writeConnect(conn) - readConnectResponse(buf) - if txt := readResponse(buf); txt != "bobo" { - t.Error("Expected bobo for CONNECT /foo, got", txt) - } - - if r := string(getOrFail(https.URL+"/bobo", client, t)); r != "bobo" { - t.Error("Expected bobo would keep working with CONNECT", r) - } -} - -func readResponse(buf *bufio.Reader) string { - req, err := http.NewRequest("GET", srv.URL, nil) - panicOnErr(err, "NewRequest") - resp, err := http.ReadResponse(buf, req) - panicOnErr(err, "resp.Read") - defer resp.Body.Close() - txt, err := ioutil.ReadAll(resp.Body) - panicOnErr(err, "resp.Read") - return string(txt) -} - -func writeConnect(w io.Writer) { - req, err := http.NewRequest("CONNECT", srv.URL[len("http://"):], nil) - panicOnErr(err, "NewRequest") - req.Write(w) - panicOnErr(err, "req(CONNECT).Write") -} - -func readConnectResponse(buf *bufio.Reader) { - _, err := buf.ReadString('\n') - panicOnErr(err, "resp.Read connect resp") - _, err = buf.ReadString('\n') - panicOnErr(err, "resp.Read connect resp") -} - -func TestCurlMinusP(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) { - return goproxy.HTTPMitmConnect, host - }) - called := false - proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - called = true - return req, nil - }) - _, l := oneShotProxy(proxy, t) - defer l.Close() - cmd := exec.Command("curl", "-p", "-sS", "--proxy", l.URL, srv.URL+"/bobo") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - if string(output) != "bobo" { - t.Error("Expected bobo, got", string(output)) - } - if !called { - t.Error("handler not called") - } -} - -func TestSelfRequest(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - _, l := oneShotProxy(proxy, t) - defer l.Close() - if !strings.Contains(string(getOrFail(l.URL, http.DefaultClient, t)), "non-proxy") { - t.Fatal("non proxy requests should fail") - } -} - -func TestHasGoproxyCA(t *testing.T) { - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) - s := httptest.NewServer(proxy) - - proxyUrl, _ := url.Parse(s.URL) - goproxyCA := x509.NewCertPool() - goproxyCA.AddCert(goproxy.GoproxyCa.Leaf) - - tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: goproxyCA}, Proxy: http.ProxyURL(proxyUrl)} - client := &http.Client{Transport: tr} - - if resp := string(getOrFail(https.URL+"/bobo", client, t)); resp != "bobo" { - t.Error("Wrong response when mitm", resp, "expected bobo") - } -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/regretable/regretreader_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/regretable/regretreader_test.go deleted file mode 100644 index 55fa752bc80..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/regretable/regretreader_test.go +++ /dev/null @@ -1,174 +0,0 @@ -package regretable_test - -import ( - . "github.com/elazarl/goproxy/regretable" - "bytes" - "io" - "io/ioutil" - "strings" - "testing" -) - -func TestRegretableReader(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - fivebytes := make([]byte, 5) - mb.Read(fivebytes) - mb.Regret() - - s, _ := ioutil.ReadAll(mb) - if string(s) != word { - t.Errorf("Uncommited read is gone, [%d,%d] actual '%v' expected '%v'\n", len(s), len(word), string(s), word) - } -} - -func TestRegretableEmptyRead(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - zero := make([]byte, 0) - mb.Read(zero) - mb.Regret() - - s, err := ioutil.ReadAll(mb) - if string(s) != word { - t.Error("Uncommited read is gone, actual:", string(s), "expected:", word, "err:", err) - } -} - -func TestRegretableAlsoEmptyRead(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - one := make([]byte, 1) - zero := make([]byte, 0) - five := make([]byte, 5) - mb.Read(one) - mb.Read(zero) - mb.Read(five) - mb.Regret() - - s, _ := ioutil.ReadAll(mb) - if string(s) != word { - t.Error("Uncommited read is gone", string(s), "expected", word) - } -} - -func TestRegretableRegretBeforeRead(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - five := make([]byte, 5) - mb.Regret() - mb.Read(five) - - s, err := ioutil.ReadAll(mb) - if string(s) != "678" { - t.Error("Uncommited read is gone", string(s), len(string(s)), "expected", "678", len("678"), "err:", err) - } -} - -func TestRegretableFullRead(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - twenty := make([]byte, 20) - mb.Read(twenty) - mb.Regret() - - s, _ := ioutil.ReadAll(mb) - if string(s) != word { - t.Error("Uncommited read is gone", string(s), len(string(s)), "expected", word, len(word)) - } -} - -func assertEqual(t *testing.T, expected, actual string) { - if expected!=actual { - t.Fatal("Expected", expected, "actual", actual) - } -} - -func assertReadAll(t *testing.T, r io.Reader) string { - s, err := ioutil.ReadAll(r) - if err!=nil { - t.Fatal("error when reading", err) - } - return string(s) -} - -func TestRegretableRegretTwice(t *testing.T) { - buf := new(bytes.Buffer) - mb := NewRegretableReader(buf) - word := "12345678" - buf.WriteString(word) - - assertEqual(t, word, assertReadAll(t, mb)) - mb.Regret() - assertEqual(t, word, assertReadAll(t, mb)) - mb.Regret() - assertEqual(t, word, assertReadAll(t, mb)) -} - -type CloseCounter struct { - r io.Reader - closed int -} - -func (cc *CloseCounter) Read(b []byte) (int, error) { - return cc.r.Read(b) -} - -func (cc *CloseCounter) Close() error { - cc.closed++ - return nil -} - -func assert(t *testing.T, b bool, msg string) { - if !b { - t.Errorf("Assertion Error: %s", msg) - } -} - -func TestRegretableCloserSizeRegrets(t *testing.T) { - defer func() { - if r := recover(); r == nil || !strings.Contains(r.(string), "regret") { - t.Error("Did not panic when regretting overread buffer:", r) - } - }() - buf := new(bytes.Buffer) - buf.WriteString("123456") - mb := NewRegretableReaderCloserSize(ioutil.NopCloser(buf), 3) - mb.Read(make([]byte, 4)) - mb.Regret() -} - -func TestRegretableCloserRegretsClose(t *testing.T) { - buf := new(bytes.Buffer) - cc := &CloseCounter{buf, 0} - mb := NewRegretableReaderCloser(cc) - word := "12345678" - buf.WriteString(word) - - mb.Read([]byte{0}) - mb.Close() - if cc.closed != 1 { - t.Error("RegretableReaderCloser ignores Close") - } - mb.Regret() - mb.Close() - if cc.closed != 2 { - t.Error("RegretableReaderCloser does ignore Close after regret") - } - // TODO(elazar): return an error if client issues Close more than once after regret -} diff --git a/Godeps/_workspace/src/github.com/elazarl/goproxy/signer_test.go b/Godeps/_workspace/src/github.com/elazarl/goproxy/signer_test.go deleted file mode 100644 index d0e24d29851..00000000000 --- a/Godeps/_workspace/src/github.com/elazarl/goproxy/signer_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package goproxy - -import ( - "crypto/tls" - "crypto/x509" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "os/exec" - "strings" - "testing" - "time" -) - -func orFatal(msg string, err error, t *testing.T) { - if err != nil { - t.Fatal(msg, err) - } -} - -type ConstantHanlder string - -func (h ConstantHanlder) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(h)) -} - -func getBrowser(args []string) string { - for i, arg := range args { - if arg == "-browser" && i+1 < len(arg) { - return args[i+1] - } - if strings.HasPrefix(arg, "-browser=") { - return arg[len("-browser="):] - } - } - return "" -} - -func TestSingerTls(t *testing.T) { - cert, err := signHost(GoproxyCa, []string{"example.com", "1.1.1.1", "localhost"}) - orFatal("singHost", err, t) - cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) - orFatal("ParseCertificate", err, t) - expected := "key verifies with Go" - server := httptest.NewUnstartedServer(ConstantHanlder(expected)) - defer server.Close() - server.TLS = &tls.Config{Certificates: []tls.Certificate{cert, GoproxyCa}} - server.TLS.BuildNameToCertificate() - server.StartTLS() - certpool := x509.NewCertPool() - certpool.AddCert(GoproxyCa.Leaf) - tr := &http.Transport{ - TLSClientConfig: &tls.Config{RootCAs: certpool}, - } - asLocalhost := strings.Replace(server.URL, "127.0.0.1", "localhost", -1) - req, err := http.NewRequest("GET", asLocalhost, nil) - orFatal("NewRequest", err, t) - resp, err := tr.RoundTrip(req) - orFatal("RoundTrip", err, t) - txt, err := ioutil.ReadAll(resp.Body) - orFatal("ioutil.ReadAll", err, t) - if string(txt) != expected { - t.Errorf("Expected '%s' got '%s'", expected, string(txt)) - } - browser := getBrowser(os.Args) - if browser != "" { - exec.Command(browser, asLocalhost).Run() - time.Sleep(10 * time.Second) - } -} - -func TestSingerX509(t *testing.T) { - cert, err := signHost(GoproxyCa, []string{"example.com", "1.1.1.1", "localhost"}) - orFatal("singHost", err, t) - cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) - orFatal("ParseCertificate", err, t) - certpool := x509.NewCertPool() - certpool.AddCert(GoproxyCa.Leaf) - orFatal("VerifyHostname", cert.Leaf.VerifyHostname("example.com"), t) - orFatal("CheckSignatureFrom", cert.Leaf.CheckSignatureFrom(GoproxyCa.Leaf), t) - _, err = cert.Leaf.Verify(x509.VerifyOptions{ - DNSName: "example.com", - Roots: certpool, - }) - orFatal("Verify", err, t) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go deleted file mode 100644 index db6a1a75244..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_curly_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package restful - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" -) - -func setupCurly(container *Container) []string { - wsCount := 26 - rtCount := 26 - urisCurly := []string{} - - container.Router(CurlyRouter{}) - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).Consumes("application/xml").Produces("application/xml").To(echoCurly)) - } - container.Add(ws) - for _, each := range ws.Routes() { - urisCurly = append(urisCurly, "http://bench.com"+each.Path) - } - } - return urisCurly -} - -func echoCurly(req *Request, resp *Response) {} - -func BenchmarkManyCurly(b *testing.B) { - container := NewContainer() - urisCurly := setupCurly(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for r := 0; r < 1000; r++ { - for _, each := range urisCurly { - sendNoReturnTo(each, container, t) - } - } - } -} - -func sendNoReturnTo(address string, container *Container, t int) { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "application/xml") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go deleted file mode 100644 index 3e77c2d292b..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/bench_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package restful - -import ( - "fmt" - "io" - "testing" -) - -var uris = []string{} - -func setup(container *Container) { - wsCount := 26 - rtCount := 26 - - for i := 0; i < wsCount; i++ { - root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) - ws := new(WebService).Path(root) - for j := 0; j < rtCount; j++ { - sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) - ws.Route(ws.GET(sub).To(echo)) - } - container.Add(ws) - for _, each := range ws.Routes() { - uris = append(uris, "http://bench.com"+each.Path) - } - } -} - -func echo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "echo") -} - -func BenchmarkMany(b *testing.B) { - container := NewContainer() - setup(container) - b.ResetTimer() - for t := 0; t < b.N; t++ { - for _, each := range uris { - // println(each) - sendItTo(each, container) - } - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go deleted file mode 100644 index 84a93c3fc90..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/compress_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "bytes" - "compress/gzip" - "compress/zlib" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestGzip ...restful -func TestGzip(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "gzip,deflate") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept gzip") - } - if encoding != "gzip" { - t.Fatal("expected gzip") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "gzip" { - t.Fatal("Missing gzip header") - } - reader, err := gzip.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestDeflate(t *testing.T) { - EnableContentEncoding = true - httpRequest, _ := http.NewRequest("GET", "/test", nil) - httpRequest.Header.Set("Accept-Encoding", "deflate,gzip") - httpWriter := httptest.NewRecorder() - wanted, encoding := wantsCompressedResponse(httpRequest) - if !wanted { - t.Fatal("should accept deflate") - } - if encoding != "deflate" { - t.Fatal("expected deflate") - } - c, err := NewCompressingResponseWriter(httpWriter, encoding) - if err != nil { - t.Fatal(err.Error()) - } - c.Write([]byte("Hello World")) - c.Close() - if httpWriter.Header().Get("Content-Encoding") != "deflate" { - t.Fatal("Missing deflate header") - } - reader, err := zlib.NewReader(httpWriter.Body) - if err != nil { - t.Fatal(err.Error()) - } - data, err := ioutil.ReadAll(reader) - if err != nil { - t.Fatal(err.Error()) - } - if got, want := string(data), "Hello World"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestGzipDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newGzipWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "gzip") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestZlibDecompressRequestBody(t *testing.T) { - b := new(bytes.Buffer) - w := newZlibWriter() - w.Reset(b) - io.WriteString(w, `{"msg":"hi"}`) - w.Flush() - w.Close() - - req := new(Request) - httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) - httpRequest.Header.Set("Content-Type", "application/json") - httpRequest.Header.Set("Content-Encoding", "deflate") - req.Request = httpRequest - - doCacheReadEntityBytes = false - doc := make(map[string]interface{}) - req.ReadEntity(&doc) - - if got, want := doc["msg"], "hi"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go deleted file mode 100644 index 6e581ae1a1c..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/container_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package restful - -import ( - "net/http" - "testing" -) - -// go test -v -test.run TestContainer_computeAllowedMethods ...restful -func TestContainer_computeAllowedMethods(t *testing.T) { - wc := NewContainer() - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("{i}").To(dummy)) - ws1.Route(ws1.POST("{i}").To(dummy)) - wc.Add(ws1) - httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil) - rreq := Request{Request: httpRequest} - m := wc.computeAllowedMethods(&rreq) - if len(m) != 2 { - t.Errorf("got %d expected 2 methods, %v", len(m), m) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go deleted file mode 100644 index 9b4723089bf..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/cors_filter_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestCORSFilter_Preflight ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Preflight(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Preflight - httpRequest, _ := http.NewRequest("OPTIONS", "http://api.alice.com/cors", nil) - httpRequest.Method = "OPTIONS" - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set(HEADER_AccessControlRequestMethod, "PUT") - httpRequest.Header.Set(HEADER_AccessControlRequestHeaders, "X-Custom-Header, X-Additional-Header") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowMethods) - if "PUT" != actual { - t.Fatal("expected: PUT but got:" + actual) - } - actual = httpWriter.Header().Get(HEADER_AccessControlAllowHeaders) - if "X-Custom-Header, X-Additional-Header" != actual { - t.Fatal("expected: X-Custom-Header, X-Additional-Header but got:" + actual) - } - - if !cors.isOriginAllowed("somewhere") { - t.Fatal("origin expected to be allowed") - } - cors.AllowedDomains = []string{"overthere.com"} - if cors.isOriginAllowed("somewhere") { - t.Fatal("origin [somewhere] expected NOT to be allowed") - } - if !cors.isOriginAllowed("overthere.com") { - t.Fatal("origin [overthere] expected to be allowed") - } - -} - -// go test -v -test.run TestCORSFilter_Actual ...restful -// http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request -func TestCORSFilter_Actual(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - ExposeHeaders: []string{"X-Custom-Header"}, - AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - // Actual - httpRequest, _ := http.NewRequest("PUT", "http://api.alice.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") - httpRequest.Header.Set("X-Custom-Header", "value") - - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if "http://api.bob.com" != actual { - t.Fatal("expected: http://api.bob.com but got:" + actual) - } - if httpWriter.Body.String() != "dummy" { - t.Fatal("expected: dummy but got:" + httpWriter.Body.String()) - } -} - -var allowedDomainInput = []struct { - domains []string - origin string - accepted bool -}{ - {[]string{}, "http://anything.com", true}, -} - -// go test -v -test.run TestCORSFilter_AllowedDomains ...restful -func TestCORSFilter_AllowedDomains(t *testing.T) { - for _, each := range allowedDomainInput { - tearDown() - ws := new(WebService) - ws.Route(ws.PUT("/cors").To(dummy)) - Add(ws) - - cors := CrossOriginResourceSharing{ - AllowedDomains: each.domains, - CookiesAllowed: true, - Container: DefaultContainer} - Filter(cors.Filter) - - httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) - httpRequest.Header.Set(HEADER_Origin, each.origin) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) - if actual != each.origin && each.accepted { - t.Fatal("expected to be accepted") - } - if actual == each.origin && !each.accepted { - t.Fatal("did not expect to be accepted") - } - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go deleted file mode 100644 index 31d66dcbda4..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/curly_test.go +++ /dev/null @@ -1,231 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "testing" -) - -var requestPaths = []struct { - // url with path (1) is handled by service with root (2) and remainder has value final (3) - path, root string -}{ - {"/", "/"}, - {"/p", "/p"}, - {"/p/x", "/p/{q}"}, - {"/q/x", "/q"}, - {"/p/x/", "/p/{q}"}, - {"/p/x/y", "/p/{q}"}, - {"/q/x/y", "/q"}, - {"/z/q", "/{p}/q"}, - {"/a/b/c/q", "/"}, -} - -// go test -v -test.run TestCurlyDetectWebService ...restful -func TestCurlyDetectWebService(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws7 := new(WebService).Path("/{p}/q") - var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7} - - for _, each := range wss { - t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens) - } - - router := CurlyRouter{} - - ok := true - for i, fixture := range requestPaths { - requestTokens := tokenizePath(fixture.path) - who := router.detectWebService(requestTokens, wss) - if who != nil && who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - } - if !ok { - t.Fail() - } -} - -var serviceDetects = []struct { - path string - found bool - root string -}{ - {"/a/b", true, "/{p}/{q}/{r}"}, - {"/p/q", true, "/p/q"}, - {"/q/p", true, "/q"}, - {"/", true, "/"}, - {"/p/q/r", true, "/p/q"}, -} - -// go test -v -test.run Test_detectWebService ...restful -func Test_detectWebService(t *testing.T) { - router := CurlyRouter{} - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - ws8 := new(WebService).Path("/{p}/{q}/{r}") - var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1} - for _, fix := range serviceDetects { - requestPath := fix.path - requestTokens := tokenizePath(requestPath) - for _, ws := range wss { - serviceTokens := ws.pathExpr.tokens - matches, score := router.computeWebserviceScore(requestTokens, serviceTokens) - t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches) - } - best := router.detectWebService(requestTokens, wss) - if best != nil { - if fix.found { - t.Logf("best=%s", best.RootPath()) - } else { - t.Fatalf("should have found:%s", fix.root) - } - } - } -} - -var routeMatchers = []struct { - route string - path string - matches bool - paramCount int - staticCount int -}{ - // route, request-path - {"/a", "/a", true, 0, 1}, - {"/a", "/b", false, 0, 0}, - {"/a", "/b", false, 0, 0}, - {"/a/{b}/c/", "/a/2/c", true, 1, 2}, - {"/{a}/{b}/{c}/", "/a/b", false, 0, 0}, - {"/{x:*}", "/", false, 0, 0}, - {"/{x:*}", "/a", true, 1, 0}, - {"/{x:*}", "/a/b", true, 1, 0}, - {"/a/{x:*}", "/a/b", true, 1, 1}, - {"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1}, - {"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1}, -} - -// clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful -func Test_matchesRouteByPathTokens(t *testing.T) { - router := CurlyRouter{} - for i, each := range routeMatchers { - routeToks := tokenizePath(each.route) - reqToks := tokenizePath(each.path) - matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks) - if matches != each.matches { - t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches) - } - if pCount != each.paramCount { - t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount) - } - if sCount != each.staticCount { - t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount) - } - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful -func TestExtractParameters_Wildcard1(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t) - if params["var"] != "remainder" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful -func TestExtractParameters_Wildcard2(t *testing.T) { - params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t) - if params["var"] != "remain/der" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful -func TestExtractParameters_Wildcard3(t *testing.T) { - params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t) - if params["var"] != "test/sub/hi.html" { - t.Errorf("parameter mismatch var: %s", params["var"]) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34 ...restful -func TestCurly_ISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful -func TestCurly_ISSUE_34_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) - routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// clear && go test -v -test.run TestCurly_JsonHtml ...restful -func TestCurly_JsonHtml(t *testing.T) { - ws1 := new(WebService) - ws1.Path("/") - ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html")) - req, _ := http.NewRequest("GET", "/some.html", nil) - req.Header.Set("Accept", "application/json") - _, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - if err == nil { - t.Error("error expected") - } - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137 ...restful -func TestCurly_ISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Error("no route expected") - } -} - -// go test -v -test.run TestCurly_ISSUE_137_2 ...restful -func TestCurly_ISSUE_137_2(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(curlyDummy)) - ws1.Path("/") - req, _ := http.NewRequest("GET", "/hello/bob", nil) - _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) - t.Log(route) - if route != nil { - t.Errorf("no route expected, got %v", route) - } -} - -func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") } diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go deleted file mode 100644 index e1a2f3b8efb..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/doc_examples_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package restful - -import "net/http" - -func ExampleOPTIONSFilter() { - // Install the OPTIONS filter on the default Container - Filter(OPTIONSFilter()) -} -func ExampleContainer_OPTIONSFilter() { - // Install the OPTIONS filter on a Container - myContainer := new(Container) - myContainer.Filter(myContainer.OPTIONSFilter) -} - -func ExampleContainer() { - // The Default container of go-restful uses the http.DefaultServeMux. - // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container - - ws := new(WebService) - wsContainer := NewContainer() - wsContainer.Add(ws) - server := &http.Server{Addr: ":8080", Handler: wsContainer} - server.ListenAndServe() -} - -func ExampleCrossOriginResourceSharing() { - // To install this filter on the Default Container use: - cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} - Filter(cors.Filter) -} - -func ExampleServiceError() { - resp := new(Response) - resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter")) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go deleted file mode 100644 index 20c366bf919..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-route_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/emicklei/go-restful" -) - -var ( - Result string -) - -func TestRouteExtractParameter(t *testing.T) { - // setup service - ws := new(restful.WebService) - ws.Consumes(restful.MIME_XML) - ws.Route(ws.GET("/test/{param}").To(DummyHandler)) - restful.Add(ws) - - // setup request + writer - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test/THIS", bodyReader) - httpRequest.Header.Set("Content-Type", restful.MIME_XML) - httpWriter := httptest.NewRecorder() - - // run - restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest) - - if Result != "THIS" { - t.Fatalf("Result is actually: %s", Result) - } -} - -func DummyHandler(rq *restful.Request, rp *restful.Response) { - Result = rq.PathParameter("param") -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go deleted file mode 100644 index 957c0555078..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/examples/restful-routefunction_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/emicklei/go-restful" -) - -// This example show how to test one particular RouteFunction (getIt) -// It uses the httptest.ResponseRecorder to capture output - -func getIt(req *restful.Request, resp *restful.Response) { - resp.WriteHeader(204) -} - -func TestCallFunction(t *testing.T) { - httpReq, _ := http.NewRequest("GET", "/", nil) - req := restful.NewRequest(httpReq) - - recorder := new(httptest.ResponseRecorder) - resp := restful.NewResponse(recorder) - - getIt(req, resp) - if recorder.Code != 204 { - t.Fatalf("Missing or wrong status code:%d", recorder.Code) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go deleted file mode 100644 index fadfb570f6c..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/filter_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package restful - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" -) - -func setupServices(addGlobalFilter bool, addServiceFilter bool, addRouteFilter bool) { - if addGlobalFilter { - Filter(globalFilter) - } - Add(newTestService(addServiceFilter, addRouteFilter)) -} - -func tearDown() { - DefaultContainer.webServices = []*WebService{} - DefaultContainer.isRegisteredOnRoot = true // this allows for setupServices multiple times - DefaultContainer.containerFilters = []FilterFunction{} -} - -func newTestService(addServiceFilter bool, addRouteFilter bool) *WebService { - ws := new(WebService).Path("") - if addServiceFilter { - ws.Filter(serviceFilter) - } - rb := ws.GET("/foo").To(foo) - if addRouteFilter { - rb.Filter(routeFilter) - } - ws.Route(rb) - ws.Route(ws.GET("/bar").To(bar)) - return ws -} - -func foo(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "foo") -} - -func bar(req *Request, resp *Response) { - io.WriteString(resp.ResponseWriter, "bar") -} - -func fail(req *Request, resp *Response) { - http.Error(resp.ResponseWriter, "something failed", http.StatusInternalServerError) -} - -func globalFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "global-") - chain.ProcessFilter(req, resp) -} - -func serviceFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "service-") - chain.ProcessFilter(req, resp) -} - -func routeFilter(req *Request, resp *Response, chain *FilterChain) { - io.WriteString(resp.ResponseWriter, "route-") - chain.ProcessFilter(req, resp) -} - -func TestNoFilter(t *testing.T) { - tearDown() - setupServices(false, false, false) - actual := sendIt("http://example.com/foo") - if "foo" != actual { - t.Fatal("expected: foo but got:" + actual) - } -} - -func TestGlobalFilter(t *testing.T) { - tearDown() - setupServices(true, false, false) - actual := sendIt("http://example.com/foo") - if "global-foo" != actual { - t.Fatal("expected: global-foo but got:" + actual) - } -} - -func TestWebServiceFilter(t *testing.T) { - tearDown() - setupServices(true, true, false) - actual := sendIt("http://example.com/foo") - if "global-service-foo" != actual { - t.Fatal("expected: global-service-foo but got:" + actual) - } -} - -func TestRouteFilter(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/foo") - if "global-service-route-foo" != actual { - t.Fatal("expected: global-service-route-foo but got:" + actual) - } -} - -func TestRouteFilterOnly(t *testing.T) { - tearDown() - setupServices(false, false, true) - actual := sendIt("http://example.com/foo") - if "route-foo" != actual { - t.Fatal("expected: route-foo but got:" + actual) - } -} - -func TestBar(t *testing.T) { - tearDown() - setupServices(false, true, false) - actual := sendIt("http://example.com/bar") - if "service-bar" != actual { - t.Fatal("expected: service-bar but got:" + actual) - } -} - -func TestAllFiltersBar(t *testing.T) { - tearDown() - setupServices(true, true, true) - actual := sendIt("http://example.com/bar") - if "global-service-bar" != actual { - t.Fatal("expected: global-service-bar but got:" + actual) - } -} - -func sendIt(address string) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} - -func sendItTo(address string, container *Container) string { - httpRequest, _ := http.NewRequest("GET", address, nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - container.dispatch(httpWriter, httpRequest) - return httpWriter.Body.String() -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go deleted file mode 100644 index 3e79a6def79..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/jsr311_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package restful - -import ( - "io" - "sort" - "testing" -) - -// -// Step 1 tests -// -var paths = []struct { - // url with path (1) is handled by service with root (2) and last capturing group has value final (3) - path, root, final string -}{ - {"/", "/", "/"}, - {"/p", "/p", ""}, - {"/p/x", "/p/{q}", ""}, - {"/q/x", "/q", "/x"}, - {"/p/x/", "/p/{q}", "/"}, - {"/p/x/y", "/p/{q}", "/y"}, - {"/q/x/y", "/q", "/x/y"}, - {"/z/q", "/{p}/q", ""}, - {"/a/b/c/q", "/", "/a/b/c/q"}, -} - -func TestDetectDispatcher(t *testing.T) { - ws1 := new(WebService).Path("/") - ws2 := new(WebService).Path("/p") - ws3 := new(WebService).Path("/q") - ws4 := new(WebService).Path("/p/q") - ws5 := new(WebService).Path("/p/{q}") - ws6 := new(WebService).Path("/p/{q}/") - ws7 := new(WebService).Path("/{p}/q") - var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7} - - wc := NewContainer() - for _, each := range dispatchers { - wc.Add(each) - } - - router := RouterJSR311{} - - ok := true - for i, fixture := range paths { - who, final, err := router.detectDispatcher(fixture.path, dispatchers) - if err != nil { - t.Logf("error in detection:%v", err) - ok = false - } - if who.RootPath() != fixture.root { - t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) - ok = false - } - if final != fixture.final { - t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final) - ok = false - } - } - if !ok { - t.Fail() - } -} - -// -// Step 2 tests -// - -// go test -v -test.run TestISSUE_179 ...restful -func TestISSUE_179(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub") - t.Logf("%v", routes) -} - -// go test -v -test.run TestISSUE_30 ...restful -func TestISSUE_30(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.GET("/{id}").To(dummy)) - ws1.Route(ws1.POST("/login").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/login") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/users/login" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34 ...restful -func TestISSUE_34(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - t.Logf("routes:%v", routes) - } -} - -// go test -v -test.run TestISSUE_34_2 ...restful -func TestISSUE_34_2(t *testing.T) { - ws1 := new(WebService).Path("/") - // change the registration order - ws1.Route(ws1.GET("/network/{id}").To(dummy)) - ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") - if len(routes) != 2 { - t.Fatal("expected 2 routes") - } - if routes[0].Path != "/network/{id}" { - t.Error("first is", routes[0].Path) - } -} - -// go test -v -test.run TestISSUE_137 ...restful -func TestISSUE_137(t *testing.T) { - ws1 := new(WebService) - ws1.Route(ws1.GET("/hello").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/") - t.Log(routes) - if len(routes) > 0 { - t.Error("no route expected") - } -} - -func TestSelectRoutesSlash(t *testing.T) { - ws1 := new(WebService).Path("/") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/u").To(dummy)) - ws1.Route(ws1.POST("/u").To(dummy)) - ws1.Route(ws1.POST("/u/v").To(dummy)) - ws1.Route(ws1.POST("/u/{w}").To(dummy)) - ws1.Route(ws1.POST("/u/{w}/z").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/u") - checkRoutesContains(routes, "/u", t) - checkRoutesContainsNo(routes, "/u/v", t) - checkRoutesContainsNo(routes, "/", t) - checkRoutesContainsNo(routes, "/u/{w}/z", t) -} -func TestSelectRoutesU(t *testing.T) { - ws1 := new(WebService).Path("/u") - ws1.Route(ws1.GET("").To(dummy)) - ws1.Route(ws1.GET("/").To(dummy)) - ws1.Route(ws1.GET("/v").To(dummy)) - ws1.Route(ws1.POST("/{w}").To(dummy)) - ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z - routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v - checkRoutesContains(routes, "/u/{w}", t) -} - -func TestSelectRoutesUsers1(t *testing.T) { - ws1 := new(WebService).Path("/users") - ws1.Route(ws1.POST("").To(dummy)) - ws1.Route(ws1.POST("/").To(dummy)) - ws1.Route(ws1.PUT("/{id}").To(dummy)) - routes := RouterJSR311{}.selectRoutes(ws1, "/1") - checkRoutesContains(routes, "/users/{id}", t) -} -func checkRoutesContains(routes []Route, path string, t *testing.T) { - if !containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should include [%v]:", path) - } -} -func checkRoutesContainsNo(routes []Route, path string, t *testing.T) { - if containsRoutePath(routes, path, t) { - for _, r := range routes { - t.Logf("route %v %v", r.Method, r.Path) - } - t.Fatalf("routes should not include [%v]:", path) - } -} -func containsRoutePath(routes []Route, path string, t *testing.T) bool { - for _, each := range routes { - if each.Path == path { - return true - } - } - return false -} - -// go test -v -test.run TestSortableRouteCandidates ...restful -func TestSortableRouteCandidates(t *testing.T) { - fixture := &sortableRouteCandidates{} - r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0} - r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1} - r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1} - r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0} - r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0} - fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1) - sort.Sort(sort.Reverse(fixture)) - first := fixture.candidates[0] - if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 { - t.Fatal("expected r4") - } - last := fixture.candidates[len(fixture.candidates)-1] - if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 { - t.Fatal("expected r1") - } -} - -func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") } diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go deleted file mode 100644 index f0fceb834e6..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/options_filter_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -// go test -v -test.run TestOptionsFilter ...restful -func TestOptionsFilter(t *testing.T) { - tearDown() - ws := new(WebService) - ws.Route(ws.GET("/candy/{kind}").To(dummy)) - ws.Route(ws.DELETE("/candy/{kind}").To(dummy)) - ws.Route(ws.POST("/candies").To(dummy)) - Add(ws) - Filter(OPTIONSFilter()) - - httpRequest, _ := http.NewRequest("OPTIONS", "http://here.io/candy/gum", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual := httpWriter.Header().Get(HEADER_Allow) - if "GET,DELETE" != actual { - t.Fatal("expected: GET,DELETE but got:" + actual) - } - - httpRequest, _ = http.NewRequest("OPTIONS", "http://here.io/candies", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - actual = httpWriter.Header().Get(HEADER_Allow) - if "POST" != actual { - t.Fatal("expected: POST but got:" + actual) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go deleted file mode 100644 index 334fcef7398..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/path_expression_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package restful - -import "testing" - -var tempregexs = []struct { - template, regex string - literalCount, varCount int -}{ - {"", "^(/.*)?$", 0, 0}, - {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, - {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, - {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, - {"/a/{b:*}", "^/a/(.*)(/.*)?$", 1, 1}, - {"/a/{b:[a-z]+}", "^/a/([a-z]+)(/.*)?$", 1, 1}, -} - -func TestTemplateToRegularExpression(t *testing.T) { - ok := true - for i, fixture := range tempregexs { - actual, lCount, vCount, _ := templateToRegularExpression(fixture.template) - if actual != fixture.regex { - t.Logf("regex mismatch, expected:%v , actual:%v, line:%v\n", fixture.regex, actual, i) // 11 = where the data starts - ok = false - } - if lCount != fixture.literalCount { - t.Logf("literal count mismatch, expected:%v , actual:%v, line:%v\n", fixture.literalCount, lCount, i) - ok = false - } - if vCount != fixture.varCount { - t.Logf("variable count mismatch, expected:%v , actual:%v, line:%v\n", fixture.varCount, vCount, i) - ok = false - } - } - if !ok { - t.Fatal("one or more expression did not match") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go deleted file mode 100644 index 6e7c55bc039..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/request_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package restful - -import ( - "encoding/json" - "net/http" - "net/url" - "strconv" - "strings" - "testing" -) - -func TestQueryParameter(t *testing.T) { - hreq := http.Request{Method: "GET"} - hreq.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") - rreq := Request{Request: &hreq} - if rreq.QueryParameter("q") != "foo" { - t.Errorf("q!=foo %#v", rreq) - } -} - -type Anything map[string]interface{} - -type Number struct { - ValueFloat float64 - ValueInt int64 -} - -type Sample struct { - Value string -} - -func TestReadEntityXml(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent == nil { - t.Fatal("no expected cached bytes found") - } -} - -func TestReadEntityXmlNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader("42") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/xml") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } - if request.bodyContent != nil { - t.Fatal("unexpected cached bytes found") - } -} - -func TestReadEntityJson(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonCharset(t *testing.T) { - bodyReader := strings.NewReader(`{"Value" : "42"}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json; charset=UTF-8") - request := NewRequest(httpRequest) - sam := new(Sample) - request.ReadEntity(sam) - if sam.Value != "42" { - t.Fatal("read failed") - } -} - -func TestReadEntityJsonNumber(t *testing.T) { - SetCacheReadEntity(true) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonNumberNonCached(t *testing.T) { - SetCacheReadEntity(false) - bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - any := make(Anything) - request.ReadEntity(&any) - number, ok := any["Value"].(json.Number) - if !ok { - t.Fatal("read failed") - } - vint, err := number.Int64() - if err != nil { - t.Fatal("convert failed") - } - if vint != 4899710515899924123 { - t.Fatal("read failed") - } - vfloat, err := number.Float64() - if err != nil { - t.Fatal("convert failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestReadEntityJsonLong(t *testing.T) { - bodyReader := strings.NewReader(`{"ValueFloat" : 4899710515899924123, "ValueInt": 4899710515899924123}`) - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/json") - request := &Request{Request: httpRequest} - number := new(Number) - request.ReadEntity(&number) - if number.ValueInt != 4899710515899924123 { - t.Fatal("read failed") - } - // match the default behaviour - vstring := strconv.FormatFloat(number.ValueFloat, 'e', 15, 64) - if vstring != "4.899710515899924e+18" { - t.Fatal("convert float64 failed") - } -} - -func TestBodyParameter(t *testing.T) { - bodyReader := strings.NewReader(`value1=42&value2=43`) - httpRequest, _ := http.NewRequest("POST", "/test?value1=44", bodyReader) // POST and PUT body parameters take precedence over URL query string - httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") - request := NewRequest(httpRequest) - v1, err := request.BodyParameter("value1") - if err != nil { - t.Error(err) - } - v2, err := request.BodyParameter("value2") - if err != nil { - t.Error(err) - } - if v1 != "42" || v2 != "43" { - t.Fatal("read failed") - } -} - -func TestReadEntityUnkown(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - httpRequest.Header.Set("Content-Type", "application/rubbish") - request := NewRequest(httpRequest) - sam := new(Sample) - err := request.ReadEntity(sam) - if err == nil { - t.Fatal("read should be in error") - } -} - -func TestSetAttribute(t *testing.T) { - bodyReader := strings.NewReader("?") - httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) - request := NewRequest(httpRequest) - request.SetAttribute("go", "there") - there := request.Attribute("go") - if there != "there" { - t.Fatalf("missing request attribute:%v", there) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go deleted file mode 100644 index c66b1f33523..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/response_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package restful - -import ( - "errors" - "net/http" - "net/http/httptest" - "testing" -) - -func TestWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(123) - if resp.StatusCode() != 123 { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -func TestNoWriteHeader(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - if resp.StatusCode() != http.StatusOK { - t.Errorf("Unexpected status code:%d", resp.StatusCode()) - } -} - -type food struct { - Kind string -} - -// go test -v -test.run TestMeasureContentLengthXml ...restful -func TestMeasureContentLengthXml(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsXml(food{"apple"}) - if resp.ContentLength() != 76 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJson ...restful -func TestMeasureContentLengthJson(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 22 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthJsonNotPretty ...restful -func TestMeasureContentLengthJsonNotPretty(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, false, nil} - resp.WriteAsJson(food{"apple"}) - if resp.ContentLength() != 16 { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestMeasureContentLengthWriteErrorString ...restful -func TestMeasureContentLengthWriteErrorString(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteErrorString(404, "Invalid") - if resp.ContentLength() != len("Invalid") { - t.Errorf("Incorrect measured length:%d", resp.ContentLength()) - } -} - -// go test -v -test.run TestStatusIsPassedToResponse ...restful -func TestStatusIsPassedToResponse(t *testing.T) { - for _, each := range []struct { - write, read int - }{ - {write: 204, read: 204}, - {write: 304, read: 304}, - {write: 200, read: 200}, - {write: 400, read: 200}, - } { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} - resp.WriteHeader(each.write) - if got, want := httpWriter.Code, each.read; got != want { - t.Error("got %v want %v", got, want) - } - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue54 ...restful -func TestStatusCreatedAndContentTypeJson_Issue54(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(201) - resp.WriteAsJson(food{"Juicy"}) - if httpWriter.HeaderMap.Get("Content-Type") != "application/json" { - t.Errorf("Expected content type json but got:%d", httpWriter.HeaderMap.Get("Content-Type")) - } - if httpWriter.Code != 201 { - t.Errorf("Expected status 201 but got:%d", httpWriter.Code) - } -} - -type errorOnWriteRecorder struct { - *httptest.ResponseRecorder -} - -func (e errorOnWriteRecorder) Write(bytes []byte) (int, error) { - return 0, errors.New("fail") -} - -// go test -v -test.run TestLastWriteErrorCaught ...restful -func TestLastWriteErrorCaught(t *testing.T) { - httpWriter := errorOnWriteRecorder{httptest.NewRecorder()} - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - err := resp.WriteAsJson(food{"Juicy"}) - if err.Error() != "fail" { - t.Errorf("Unexpected error message:%v", err) - } -} - -// go test -v -test.run TestAcceptStarStar_Issue83 ...restful -func TestAcceptStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "application/bogus,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptSkipStarStar_Issue83 ...restful -func TestAcceptSkipStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, " application/xml ,*/* ; q=0.8", []string{"application/json", "application/xml"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/xml" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestAcceptXmlBeforeStarStar_Issue83 ...restful -func TestAcceptXmlBeforeStarStar_Issue83(t *testing.T) { - httpWriter := httptest.NewRecorder() - // Accept Produces - resp := Response{httpWriter, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} - resp.WriteEntity(food{"Juicy"}) - ct := httpWriter.Header().Get("Content-Type") - if "application/json" != ct { - t.Errorf("Unexpected content type:%s", ct) - } -} - -// go test -v -test.run TestWriteHeaderNoContent_Issue124 ...restful -func TestWriteHeaderNoContent_Issue124(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "text/plain", []string{"text/plain"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNoContent) - if httpWriter.Code != http.StatusNoContent { - t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) - } -} - -// go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue163 ...restful -func TestStatusCreatedAndContentTypeJson_Issue163(t *testing.T) { - httpWriter := httptest.NewRecorder() - resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} - resp.WriteHeader(http.StatusNotModified) - if httpWriter.Code != http.StatusNotModified { - t.Errorf("Got %d want %d", httpWriter.Code, http.StatusNotModified) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go deleted file mode 100644 index 56dbe02e476..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_builder_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package restful - -import ( - "testing" -) - -func TestRouteBuilder_PathParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - b := new(RouteBuilder) - b.function = dummy - b.Param(p) - r := b.Build() - if !r.ParameterDocs[0].Data().AllowMultiple { - t.Error("AllowMultiple invalid") - } - if r.ParameterDocs[0].Data().DataType != "int" { - t.Error("dataType invalid") - } - if !r.ParameterDocs[0].Data().Required { - t.Error("required invalid") - } - if r.ParameterDocs[0].Data().Kind != PathParameterKind { - t.Error("kind invalid") - } - if r.ParameterDocs[0].Data().AllowableValues["a"] != "b" { - t.Error("allowableValues invalid") - } - if b.ParameterNamed("name") == nil { - t.Error("access to parameter failed") - } -} - -func TestRouteBuilder(t *testing.T) { - json := "application/json" - b := new(RouteBuilder) - b.To(dummy) - b.Path("/routes").Method("HEAD").Consumes(json).Produces(json) - r := b.Build() - if r.Path != "/routes" { - t.Error("path invalid") - } - if r.Produces[0] != json { - t.Error("produces invalid") - } - if r.Consumes[0] != json { - t.Error("consumes invalid") - } - if r.Operation != "dummy" { - t.Error("Operation not set") - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go deleted file mode 100644 index 6a104aff8ed..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/route_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package restful - -import ( - "testing" -) - -// accept should match produces -func TestMatchesAcceptPlainTextWhenProducePlainTextAsLast(t *testing.T) { - r := Route{Produces: []string{"application/json", "text/plain"}} - if !r.matchesAccept("text/plain") { - t.Errorf("accept should match text/plain") - } -} - -// accept should match produces -func TestMatchesAcceptStar(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("*/*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptIE(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if !r.matchesAccept("text/html, application/xhtml+xml, */*") { - t.Errorf("accept should match star") - } -} - -// accept should match produces -func TestMatchesAcceptXml(t *testing.T) { - r := Route{Produces: []string{"application/xml"}} - if r.matchesAccept("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// accept should match produces -func TestMatchesAcceptAny(t *testing.T) { - r := Route{Produces: []string{"*/*"}} - if !r.matchesAccept("application/json") { - t.Errorf("accept should match json") - } - if !r.matchesAccept("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeXml(t *testing.T) { - r := Route{Consumes: []string{"application/xml"}} - if r.matchesContentType("application/json") { - t.Errorf("accept should not match json") - } - if !r.matchesContentType("application/xml") { - t.Errorf("accept should match xml") - } -} - -// content type should match consumes -func TestMatchesContentTypeCharsetInformation(t *testing.T) { - r := Route{Consumes: []string{"application/json"}} - if !r.matchesContentType("application/json; charset=UTF-8") { - t.Errorf("matchesContentType should ignore charset information") - } -} - -func TestMatchesPath_OneParam(t *testing.T) { - params := doExtractParams("/from/{source}", 2, "/from/here", t) - if params["source"] != "here" { - t.Errorf("parameter mismatch here") - } -} - -func TestMatchesPath_Slash(t *testing.T) { - params := doExtractParams("/", 0, "/", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_SlashNonVar(t *testing.T) { - params := doExtractParams("/any", 1, "/any", t) - if len(params) != 0 { - t.Errorf("expected empty parameters") - } -} - -func TestMatchesPath_TwoVars(t *testing.T) { - params := doExtractParams("/from/{source}/to/{destination}", 4, "/from/AMS/to/NY", t) - if params["source"] != "AMS" { - t.Errorf("parameter mismatch AMS") - } -} - -func TestMatchesPath_VarOnFront(t *testing.T) { - params := doExtractParams("{what}/from/{source}/", 3, "who/from/SOS/", t) - if params["source"] != "SOS" { - t.Errorf("parameter mismatch SOS") - } -} - -func TestExtractParameters_EmptyValue(t *testing.T) { - params := doExtractParams("/fixed/{var}", 2, "/fixed/", t) - if params["var"] != "" { - t.Errorf("parameter mismatch var") - } -} - -func TestTokenizePath(t *testing.T) { - if len(tokenizePath("/")) != 0 { - t.Errorf("not empty path tokens") - } -} - -func doExtractParams(routePath string, size int, urlPath string, t *testing.T) map[string]string { - r := Route{Path: routePath} - r.postBuild() - if len(r.pathParts) != size { - t.Fatalf("len not %v %v, but %v", size, r.pathParts, len(r.pathParts)) - } - return r.extractParameters(urlPath) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go deleted file mode 100644 index 2f1eeeffff2..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_builder_test.go +++ /dev/null @@ -1,1111 +0,0 @@ -package swagger - -import ( - "testing" - "time" -) - -type YesNo bool - -func (y YesNo) MarshalJSON() ([]byte, error) { - if y { - return []byte("yes"), nil - } - return []byte("no"), nil -} - -// clear && go test -v -test.run TestRef_Issue190 ...swagger -func TestRef_Issue190(t *testing.T) { - type User struct { - items []string - } - testJsonFromStruct(t, User{}, `{ - "swagger.User": { - "id": "swagger.User", - "required": [ - "items" - ], - "properties": { - "items": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestCustomMarshaller_Issue96 ...swagger -func TestCustomMarshaller_Issue96(t *testing.T) { - type Vote struct { - What YesNo - } - testJsonFromStruct(t, Vote{}, `{ - "swagger.Vote": { - "id": "swagger.Vote", - "required": [ - "What" - ], - "properties": { - "What": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitiveTypes ...swagger -func TestPrimitiveTypes(t *testing.T) { - type Prims struct { - f float64 - t time.Time - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t" - ], - "properties": { - "f": { - "type": "number", - "format": "double" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestPrimitivePtrTypes ...swagger -func TestPrimitivePtrTypes(t *testing.T) { - type Prims struct { - f *float64 - t *time.Time - b *bool - s *string - i *int - } - testJsonFromStruct(t, Prims{}, `{ - "swagger.Prims": { - "id": "swagger.Prims", - "required": [ - "f", - "t", - "b", - "s", - "i" - ], - "properties": { - "b": { - "type": "boolean" - }, - "f": { - "type": "number", - "format": "double" - }, - "i": { - "type": "integer", - "format": "int32" - }, - "s": { - "type": "string" - }, - "t": { - "type": "string", - "format": "date-time" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS1 ...swagger -func TestS1(t *testing.T) { - type S1 struct { - Id string - } - testJsonFromStruct(t, S1{}, `{ - "swagger.S1": { - "id": "swagger.S1", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - } - }`) -} - -// clear && go test -v -test.run TestS2 ...swagger -func TestS2(t *testing.T) { - type S2 struct { - Ids []string - } - testJsonFromStruct(t, S2{}, `{ - "swagger.S2": { - "id": "swagger.S2", - "required": [ - "Ids" - ], - "properties": { - "Ids": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -// clear && go test -v -test.run TestS3 ...swagger -func TestS3(t *testing.T) { - type NestedS3 struct { - Id string - } - type S3 struct { - Nested NestedS3 - } - testJsonFromStruct(t, S3{}, `{ - "swagger.NestedS3": { - "id": "swagger.NestedS3", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "string" - } - } - }, - "swagger.S3": { - "id": "swagger.S3", - "required": [ - "Nested" - ], - "properties": { - "Nested": { - "$ref": "swagger.NestedS3" - } - } - } - }`) -} - -type sample struct { - id string `swagger:"required"` // TODO - items []item - rootItem item `json:"root" description:"root desc"` -} - -type item struct { - itemName string `json:"name"` -} - -// clear && go test -v -test.run TestSampleToModelAsJson ...swagger -func TestSampleToModelAsJson(t *testing.T) { - testJsonFromStruct(t, sample{items: []item{}}, `{ - "swagger.item": { - "id": "swagger.item", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - } - } - }, - "swagger.sample": { - "id": "swagger.sample", - "required": [ - "id", - "items", - "root" - ], - "properties": { - "id": { - "type": "string" - }, - "items": { - "type": "array", - "items": { - "$ref": "swagger.item" - } - }, - "root": { - "$ref": "swagger.item", - "description": "root desc" - } - } - } - }`) -} - -func TestJsonTags(t *testing.T) { - type X struct { - A string - B string `json:"-"` - C int `json:",string"` - D int `json:","` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A", - "C", - "D" - ], - "properties": { - "A": { - "type": "string" - }, - "C": { - "type": "string" - }, - "D": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagOmitempty(t *testing.T) { - type X struct { - A int `json:",omitempty"` - B int `json:"C,omitempty"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "properties": { - "A": { - "type": "integer", - "format": "int32" - }, - "C": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestJsonTagName(t *testing.T) { - type X struct { - A string `json:"B"` - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "string" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousStruct(t *testing.T) { - type X struct { - A struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrStruct(t *testing.T) { - type X struct { - A *struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "$ref": "swagger.X.A" - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousArrayStruct(t *testing.T) { - type X struct { - A []struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -func TestAnonymousPtrArrayStruct(t *testing.T) { - type X struct { - A *[]struct { - B int - } - } - - expected := `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "array", - "items": { - "$ref": "swagger.X.A" - } - } - } - }, - "swagger.X.A": { - "id": "swagger.X.A", - "required": [ - "B" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - } - } - } - }` - - testJsonFromStruct(t, X{}, expected) -} - -// go test -v -test.run TestEmbeddedStruct_Issue98 ...swagger -func TestEmbeddedStruct_Issue98(t *testing.T) { - type Y struct { - A int - } - type X struct { - Y - } - testJsonFromStruct(t, X{}, `{ - "swagger.X": { - "id": "swagger.X", - "required": [ - "A" - ], - "properties": { - "A": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type Dataset struct { - Names []string -} - -// clear && go test -v -test.run TestIssue85 ...swagger -func TestIssue85(t *testing.T) { - anon := struct{ Datasets []Dataset }{} - testJsonFromStruct(t, anon, `{ - "struct { Datasets ||swagger.Dataset }": { - "id": "struct { Datasets ||swagger.Dataset }", - "required": [ - "Datasets" - ], - "properties": { - "Datasets": { - "type": "array", - "items": { - "$ref": "swagger.Dataset" - } - } - } - }, - "swagger.Dataset": { - "id": "swagger.Dataset", - "required": [ - "Names" - ], - "properties": { - "Names": { - "type": "array", - "items": { - "type": "string" - } - } - } - } - }`) -} - -type File struct { - History []File - HistoryPtrs []*File -} - -// go test -v -test.run TestRecursiveStructure ...swagger -func TestRecursiveStructure(t *testing.T) { - testJsonFromStruct(t, File{}, `{ - "swagger.File": { - "id": "swagger.File", - "required": [ - "History", - "HistoryPtrs" - ], - "properties": { - "History": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - }, - "HistoryPtrs": { - "type": "array", - "items": { - "$ref": "swagger.File" - } - } - } - } - }`) -} - -type A1 struct { - B struct { - Id int - Comment string `json:"comment,omitempty"` - } -} - -// go test -v -test.run TestEmbeddedStructA1 ...swagger -func TestEmbeddedStructA1(t *testing.T) { - testJsonFromStruct(t, A1{}, `{ - "swagger.A1": { - "id": "swagger.A1", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.A1.B" - } - } - }, - "swagger.A1.B": { - "id": "swagger.A1.B", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - } - } - } - }`) -} - -type A2 struct { - C -} -type C struct { - Id int `json:"B"` - Comment string `json:"comment,omitempty"` - Secure bool `json:"secure"` -} - -// go test -v -test.run TestEmbeddedStructA2 ...swagger -func TestEmbeddedStructA2(t *testing.T) { - testJsonFromStruct(t, A2{}, `{ - "swagger.A2": { - "id": "swagger.A2", - "required": [ - "B", - "secure" - ], - "properties": { - "B": { - "type": "integer", - "format": "int32" - }, - "comment": { - "type": "string" - }, - "secure": { - "type": "boolean" - } - } - } - }`) -} - -type A3 struct { - B D -} - -type D struct { - Id int -} - -// clear && go test -v -test.run TestStructA3 ...swagger -func TestStructA3(t *testing.T) { - testJsonFromStruct(t, A3{}, `{ - "swagger.A3": { - "id": "swagger.A3", - "required": [ - "B" - ], - "properties": { - "B": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A4 struct { - D "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA4(t *testing.T) { - testJsonFromStruct(t, A4{}, `{ - "swagger.A4": { - "id": "swagger.A4", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type A5 struct { - D `json:"d"` -} - -// clear && go test -v -test.run TestStructA5 ...swagger -func TestEmbeddedStructA5(t *testing.T) { - testJsonFromStruct(t, A5{}, `{ - "swagger.A5": { - "id": "swagger.A5", - "required": [ - "d" - ], - "properties": { - "d": { - "$ref": "swagger.D" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type D2 struct { - id int - D []D -} - -type A6 struct { - D2 "json:,inline" -} - -// clear && go test -v -test.run TestStructA4 ...swagger -func TestEmbeddedStructA6(t *testing.T) { - testJsonFromStruct(t, A6{}, `{ - "swagger.A6": { - "id": "swagger.A6", - "required": [ - "id", - "D" - ], - "properties": { - "D": { - "type": "array", - "items": { - "$ref": "swagger.D" - } - }, - "id": { - "type": "integer", - "format": "int32" - } - } - }, - "swagger.D": { - "id": "swagger.D", - "required": [ - "Id" - ], - "properties": { - "Id": { - "type": "integer", - "format": "int32" - } - } - } - }`) -} - -type ObjectId []byte - -type Region struct { - Id ObjectId `bson:"_id" json:"id"` - Name string `bson:"name" json:"name"` - Type string `bson:"type" json:"type"` -} - -// clear && go test -v -test.run TestRegion_Issue113 ...swagger -func TestRegion_Issue113(t *testing.T) { - testJsonFromStruct(t, []Region{}, `{ - "integer": { - "id": "integer", - "properties": {} - }, - "swagger.Region": { - "id": "swagger.Region", - "required": [ - "id", - "name", - "type" - ], - "properties": { - "id": { - "type": "array", - "items": { - "$ref": "integer" - } - }, - "name": { - "type": "string" - }, - "type": { - "type": "string" - } - } - }, - "||swagger.Region": { - "id": "||swagger.Region", - "properties": {} - } - }`) -} - -// clear && go test -v -test.run TestIssue158 ...swagger -func TestIssue158(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - - type Customer struct { - Name string `json:"name"` - Address Address `json:"address"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "address" - ], - "properties": { - "address": { - "$ref": "swagger.Address" - }, - "name": { - "type": "string" - } - } - } - }` - testJsonFromStruct(t, Customer{}, expected) -} - -func TestSlices(t *testing.T) { - type Address struct { - Country string `json:"country,omitempty"` - } - expected := `{ - "swagger.Address": { - "id": "swagger.Address", - "properties": { - "country": { - "type": "string" - } - } - }, - "swagger.Customer": { - "id": "swagger.Customer", - "required": [ - "name", - "addresses" - ], - "properties": { - "addresses": { - "type": "array", - "items": { - "$ref": "swagger.Address" - } - }, - "name": { - "type": "string" - } - } - } - }` - // both slices (with pointer value and with type value) should have equal swagger representation - { - type Customer struct { - Name string `json:"name"` - Addresses []Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - { - type Customer struct { - Name string `json:"name"` - Addresses []*Address `json:"addresses"` - } - testJsonFromStruct(t, Customer{}, expected) - } - -} - -type Name struct { - Value string -} - -func (n Name) PostBuildModel(m *Model) *Model { - m.Description = "titles must be upcase" - return m -} - -type TOC struct { - Titles []Name -} - -type Discography struct { - Title Name - TOC -} - -// clear && go test -v -test.run TestEmbeddedStructPull204 ...swagger -func TestEmbeddedStructPull204(t *testing.T) { - b := Discography{} - testJsonFromStruct(t, b, ` -{ - "swagger.Discography": { - "id": "swagger.Discography", - "required": [ - "Title", - "Titles" - ], - "properties": { - "Title": { - "$ref": "swagger.Name" - }, - "Titles": { - "type": "array", - "items": { - "$ref": "swagger.Name" - } - } - } - }, - "swagger.Name": { - "id": "swagger.Name", - "required": [ - "Value" - ], - "properties": { - "Value": { - "type": "string" - } - } - } - } -`) -} - -type AddressWithMethod struct { - Country string `json:"country,omitempty"` - PostCode int `json:"postcode,omitempty"` -} - -func (AddressWithMethod) SwaggerDoc() map[string]string { - return map[string]string{ - "": "Address doc", - "country": "Country doc", - "postcode": "PostCode doc", - } -} - -func TestDocInMethodSwaggerDoc(t *testing.T) { - expected := `{ - "swagger.AddressWithMethod": { - "id": "swagger.AddressWithMethod", - "description": "Address doc", - "properties": { - "country": { - "type": "string", - "description": "Country doc" - }, - "postcode": { - "type": "integer", - "format": "int32", - "description": "PostCode doc" - } - } - } - }` - testJsonFromStruct(t, AddressWithMethod{}, expected) -} - -type RefDesc struct { - f1 *int64 `description:"desc"` -} - -func TestPtrDescription(t *testing.T) { - b := RefDesc{} - expected := `{ - "swagger.RefDesc": { - "id": "swagger.RefDesc", - "required": [ - "f1" - ], - "properties": { - "f1": { - "type": "integer", - "format": "int64", - "description": "desc" - } - } - } - }` - testJsonFromStruct(t, b, expected) -} - -type A struct { - B `json:",inline"` - C1 `json:"metadata,omitempty"` -} - -type B struct { - SB string -} - -type C1 struct { - SC string -} - -func (A) SwaggerDoc() map[string]string { - return map[string]string{ - "": "A struct", - "B": "B field", // We should not get anything from this - "metadata": "C1 field", - } -} - -func (B) SwaggerDoc() map[string]string { - return map[string]string{ - "": "B struct", - "SB": "SB field", - } -} - -func (C1) SwaggerDoc() map[string]string { - return map[string]string{ - "": "C1 struct", - "SC": "SC field", - } -} - -func TestNestedStructDescription(t *testing.T) { - expected := ` -{ - "swagger.A": { - "id": "swagger.A", - "description": "A struct", - "required": [ - "SB" - ], - "properties": { - "SB": { - "type": "string", - "description": "SB field" - }, - "metadata": { - "$ref": "swagger.C1", - "description": "C1 field" - } - } - }, - "swagger.C1": { - "id": "swagger.C1", - "description": "C1 struct", - "required": [ - "SC" - ], - "properties": { - "SC": { - "type": "string", - "description": "SC field" - } - } - } - } -` - testJsonFromStruct(t, A{}, expected) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go deleted file mode 100644 index 9a9ab919b48..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_list_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelList(t *testing.T) { - m := Model{} - m.Id = "m" - l := ModelList{} - l.Put("m", m) - k, ok := l.At("m") - if !ok { - t.Error("want model back") - } - if got, want := k.Id, "m"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Marshal(t *testing.T) { - l := ModelList{} - m := Model{Id: "myid"} - l.Put("myid", m) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"myid":{"id":"myid","properties":{}}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelList_Unmarshal(t *testing.T) { - data := `{"myid":{"id":"myid","properties":{}}}` - l := ModelList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("myid") - if !ok { - t.Error("expected myid") - } - if got, want := m.Id, "myid"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go deleted file mode 100644 index 3fb0748e374..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_ext_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package swagger - -import "testing" - -// clear && go test -v -test.run TestThatExtraTagsAreReadIntoModel ...swagger -func TestThatExtraTagsAreReadIntoModel(t *testing.T) { - type Anything struct { - Name string `description:"name" modelDescription:"a test"` - Size int `minimum:"0" maximum:"10"` - Stati string `enum:"off|on" default:"on" modelDescription:"more description"` - ID string `unique:"true"` - Password string - } - m := modelsFromStruct(Anything{}) - props, _ := m.At("swagger.Anything") - p1, _ := props.Properties.At("Name") - if got, want := p1.Description, "name"; got != want { - t.Errorf("got %v want %v", got, want) - } - p2, _ := props.Properties.At("Size") - if got, want := p2.Minimum, "0"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p2.Maximum, "10"; got != want { - t.Errorf("got %v want %v", got, want) - } - p3, _ := props.Properties.At("Stati") - if got, want := p3.Enum[0], "off"; got != want { - t.Errorf("got %v want %v", got, want) - } - if got, want := p3.Enum[1], "on"; got != want { - t.Errorf("got %v want %v", got, want) - } - p4, _ := props.Properties.At("ID") - if got, want := *p4.UniqueItems, true; got != want { - t.Errorf("got %v want %v", got, want) - } - p5, _ := props.Properties.At("Password") - if got, want := *p5.Type, "string"; got != want { - t.Errorf("got %v want %v", got, want) - } - - if got, want := props.Description, "a test\nmore description"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go deleted file mode 100644 index 2833ad8fdaa..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/model_property_list_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package swagger - -import ( - "encoding/json" - "testing" -) - -func TestModelPropertyList(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - q, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := q.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Marshal(t *testing.T) { - l := ModelPropertyList{} - p := ModelProperty{Description: "d"} - l.Put("p", p) - data, err := json.Marshal(l) - if err != nil { - t.Error(err) - } - if got, want := string(data), `{"p":{"description":"d"}}`; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -func TestModelPropertyList_Unmarshal(t *testing.T) { - data := `{"p":{"description":"d"}}` - l := ModelPropertyList{} - if err := json.Unmarshal([]byte(data), &l); err != nil { - t.Error(err) - } - m, ok := l.At("p") - if !ok { - t.Error("expected p") - } - if got, want := m.Description, "d"; got != want { - t.Errorf("got %v want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go deleted file mode 100644 index 964e7da05a1..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package swagger - -import ( - "testing" - - "github.com/emicklei/go-restful" -) - -// go test -v -test.run TestOrderedRouteMap ...swagger -func TestOrderedRouteMap(t *testing.T) { - m := newOrderedRouteMap() - r1 := restful.Route{Path: "/r1"} - r2 := restful.Route{Path: "/r2"} - m.Add("a", r1) - m.Add("b", r2) - m.Add("b", r1) - m.Add("d", r2) - m.Add("c", r2) - order := "" - m.Do(func(k string, routes []restful.Route) { - order += k - if len(routes) == 0 { - t.Fail() - } - }) - if order != "abdc" { - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go deleted file mode 100644 index 3e20d2f5b9d..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/postbuild_model_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package swagger - -import "testing" - -type Boat struct { - Length int `json:"-"` // on default, this makes the fields not required - Weight int `json:"-"` -} - -// PostBuildModel is from swagger.ModelBuildable -func (b Boat) PostBuildModel(m *Model) *Model { - // override required - m.Required = []string{"Length", "Weight"} - - // add model property (just to test is can be added; is this a real usecase?) - extraType := "string" - m.Properties.Put("extra", ModelProperty{ - Description: "extra description", - DataTypeFields: DataTypeFields{ - Type: &extraType, - }, - }) - return m -} - -func TestCustomPostModelBuilde(t *testing.T) { - testJsonFromStruct(t, Boat{}, `{ - "swagger.Boat": { - "id": "swagger.Boat", - "required": [ - "Length", - "Weight" - ], - "properties": { - "extra": { - "type": "string", - "description": "extra description" - } - } - } -}`) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go deleted file mode 100644 index 8b8632ae379..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/swagger_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package swagger - -import ( - "testing" - - "github.com/emicklei/go-restful" -) - -// go test -v -test.run TestThatMultiplePathsOnRootAreHandled ...swagger -func TestThatMultiplePathsOnRootAreHandled(t *testing.T) { - ws1 := new(restful.WebService) - ws1.Route(ws1.GET("/_ping").To(dummy)) - ws1.Route(ws1.GET("/version").To(dummy)) - - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws1}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws1, "/") - if got, want := len(decl.Apis), 2; got != want { - t.Errorf("got %v want %v", got, want) - } -} - -// go test -v -test.run TestServiceToApi ...swagger -func TestServiceToApi(t *testing.T) { - ws := new(restful.WebService) - ws.Path("/tests") - ws.Consumes(restful.MIME_JSON) - ws.Produces(restful.MIME_XML) - ws.Route(ws.GET("/a").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/b").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/c").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/d").To(dummy).Writes(sample{})) - - ws.Route(ws.GET("/d").To(dummy).Writes(sample{})) - ws.Route(ws.PUT("/c").To(dummy).Writes(sample{})) - ws.Route(ws.POST("/b").To(dummy).Writes(sample{})) - ws.Route(ws.DELETE("/a").To(dummy).Writes(sample{})) - ws.ApiVersion("1.2.3") - cfg := Config{ - WebServicesUrl: "http://here.com", - ApiPath: "/apipath", - WebServices: []*restful.WebService{ws}, - PostBuildHandler: func(in *ApiDeclarationList) {}, - } - sws := newSwaggerService(cfg) - decl := sws.composeDeclaration(ws, "/tests") - // checks - if decl.ApiVersion != "1.2.3" { - t.Errorf("got %v want %v", decl.ApiVersion, "1.2.3") - } - if decl.BasePath != "http://here.com" { - t.Errorf("got %v want %v", decl.BasePath, "http://here.com") - } - if len(decl.Apis) != 4 { - t.Errorf("got %v want %v", len(decl.Apis), 4) - } - pathOrder := "" - for _, each := range decl.Apis { - pathOrder += each.Path - for _, other := range each.Operations { - pathOrder += other.Method - } - } - if pathOrder != "/tests/aGETDELETE/tests/bPUTPOST/tests/cPOSTPUT/tests/dDELETEGET" { - t.Errorf("got %v want %v", pathOrder, "see test source") - } -} - -func dummy(i *restful.Request, o *restful.Response) {} - -// go test -v -test.run TestIssue78 ...swagger -type Response struct { - Code int - Users *[]User - Items *[]TestItem -} -type User struct { - Id, Name string -} -type TestItem struct { - Id, Name string -} - -// clear && go test -v -test.run TestComposeResponseMessages ...swagger -func TestComposeResponseMessages(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "swagger.TestItem" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -// clear && go test -v -test.run TestComposeResponseMessageArray ...swagger -func TestComposeResponseMessageArray(t *testing.T) { - responseErrors := map[int]restful.ResponseError{} - responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: []TestItem{}} - route := restful.Route{ResponseErrors: responseErrors} - decl := new(ApiDeclaration) - decl.Models = ModelList{} - msgs := composeResponseMessages(route, decl) - if msgs[0].ResponseModel != "array[swagger.TestItem]" { - t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) - } -} - -func TestIssue78(t *testing.T) { - sws := newSwaggerService(Config{}) - models := new(ModelList) - sws.addModelFromSampleTo(&Operation{}, true, Response{Items: &[]TestItem{}}, models) - model, ok := models.At("swagger.Response") - if !ok { - t.Fatal("missing response model") - } - if "swagger.Response" != model.Id { - t.Fatal("wrong model id:" + model.Id) - } - code, ok := model.Properties.At("Code") - if !ok { - t.Fatal("missing code") - } - if "integer" != *code.Type { - t.Fatal("wrong code type:" + *code.Type) - } - items, ok := model.Properties.At("Items") - if !ok { - t.Fatal("missing items") - } - if "array" != *items.Type { - t.Fatal("wrong items type:" + *items.Type) - } - items_items := items.Items - if items_items == nil { - t.Fatal("missing items->items") - } - ref := items_items.Ref - if ref == nil { - t.Fatal("missing $ref") - } - if *ref != "swagger.TestItem" { - t.Fatal("wrong $ref:" + *ref) - } -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go deleted file mode 100644 index 6799174db4f..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/swagger/utils_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package swagger - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - "testing" -) - -func testJsonFromStruct(t *testing.T, sample interface{}, expectedJson string) bool { - m := modelsFromStruct(sample) - data, _ := json.MarshalIndent(m, " ", " ") - return compareJson(t, string(data), expectedJson) -} - -func modelsFromStruct(sample interface{}) *ModelList { - models := new(ModelList) - builder := modelBuilder{models} - builder.addModelFrom(sample) - return models -} - -func compareJson(t *testing.T, actualJsonAsString string, expectedJsonAsString string) bool { - var actualMap map[string]interface{} - json.Unmarshal([]byte(actualJsonAsString), &actualMap) - var expectedMap map[string]interface{} - json.Unmarshal([]byte(expectedJsonAsString), &expectedMap) - if !reflect.DeepEqual(actualMap, expectedMap) { - t.Log("---- expected -----") - t.Log(withLineNumbers(expectedJsonAsString)) - t.Log("---- actual -----") - t.Log(withLineNumbers(actualJsonAsString)) - t.Log("---- raw -----") - t.Log(actualJsonAsString) - t.Error("there are differences") - return false - } - return true -} - -func indexOfNonMatchingLine(actual, expected string) int { - a := strings.Split(actual, "\n") - e := strings.Split(expected, "\n") - size := len(a) - if len(e) < len(a) { - size = len(e) - } - for i := 0; i < size; i++ { - if a[i] != e[i] { - return i - } - } - return -1 -} - -func withLineNumbers(content string) string { - var buffer bytes.Buffer - lines := strings.Split(content, "\n") - for i, each := range lines { - buffer.WriteString(fmt.Sprintf("%d:%s\n", i, each)) - } - return buffer.String() -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go deleted file mode 100644 index 60c1e9fc09d..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/tracer_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package restful - -import "testing" - -// Use like this: -// -// TraceLogger(testLogger{t}) -type testLogger struct { - t *testing.T -} - -func (l testLogger) Print(v ...interface{}) { - l.t.Log(v...) -} - -func (l testLogger) Printf(format string, v ...interface{}) { - l.t.Logf(format, v...) -} diff --git a/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go b/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go deleted file mode 100644 index d2e504c0ca2..00000000000 --- a/Godeps/_workspace/src/github.com/emicklei/go-restful/web_service_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package restful - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -const ( - pathGetFriends = "/get/{userId}/friends" -) - -func TestParameter(t *testing.T) { - p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} - p.AllowMultiple(true) - p.DataType("int") - p.Required(true) - values := map[string]string{"a": "b"} - p.AllowableValues(values) - p.bePath() - - ws := new(WebService) - ws.Param(p) - if ws.pathParameters[0].Data().Name != "name" { - t.Error("path parameter (or name) invalid") - } -} -func TestWebService_CanCreateParameterKinds(t *testing.T) { - ws := new(WebService) - if ws.BodyParameter("b", "b").Kind() != BodyParameterKind { - t.Error("body parameter expected") - } - if ws.PathParameter("p", "p").Kind() != PathParameterKind { - t.Error("path parameter expected") - } - if ws.QueryParameter("q", "q").Kind() != QueryParameterKind { - t.Error("query parameter expected") - } -} - -func TestCapturePanic(t *testing.T) { - tearDown() - Add(newPanicingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire") - } -} - -func TestCapturePanicWithEncoded(t *testing.T) { - tearDown() - Add(newPanicingService()) - DefaultContainer.EnableContentEncoding(true) - httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) - httpRequest.Header.Set("Accept", "*/*") - httpRequest.Header.Set("Accept-Encoding", "gzip") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 500 != httpWriter.Code { - t.Error("500 expected on fire, got", httpWriter.Code) - } -} - -func TestNotFound(t *testing.T) { - tearDown() - httpRequest, _ := http.NewRequest("GET", "http://here.com/missing", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 404 != httpWriter.Code { - t.Error("404 expected on missing") - } -} - -func TestMethodNotAllowed(t *testing.T) { - tearDown() - Add(newGetOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 405 != httpWriter.Code { - t.Error("405 expected method not allowed") - } -} - -func TestSelectedRoutePath_Issue100(t *testing.T) { - tearDown() - Add(newSelectedRouteTestingService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get/232452/friends", nil) - httpRequest.Header.Set("Accept", "*/*") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if http.StatusOK != httpWriter.Code { - t.Error(http.StatusOK, "expected,", httpWriter.Code, "received.") - } -} - -func TestContentType415_Issue170(t *testing.T) { - tearDown() - Add(newGetOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func TestContentType415_POST_Issue170(t *testing.T) { - tearDown() - Add(newPostOnlyJsonOnlyService()) - httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) - httpRequest.Header.Set("Content-Type", "application/json") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -// go test -v -test.run TestContentType406PlainJson ...restful -func TestContentType406PlainJson(t *testing.T) { - tearDown() - TraceLogger(testLogger{t}) - Add(newGetPlainTextOrJsonService()) - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Accept", "text/plain") - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if got, want := httpWriter.Code, 200; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -// go test -v -test.run TestContentTypeOctet_Issue170 ...restful -func TestContentTypeOctet_Issue170(t *testing.T) { - tearDown() - Add(newGetConsumingOctetStreamService()) - // with content-type - httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) - httpRequest.Header.Set("Content-Type", MIME_OCTET) - httpWriter := httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } - // without content-type - httpRequest, _ = http.NewRequest("GET", "http://here.com/get", nil) - httpWriter = httptest.NewRecorder() - DefaultContainer.dispatch(httpWriter, httpRequest) - if 200 != httpWriter.Code { - t.Errorf("Expected 200, got %d", httpWriter.Code) - } -} - -func newPanicingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/fire").To(doPanic)) - return ws -} - -func newGetOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET("/get").To(doPanic)) - return ws -} - -func newPostOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.POST("/post").To(doNothing)) - return ws -} - -func newGetOnlyJsonOnlyService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetPlainTextOrJsonService() *WebService { - ws := new(WebService).Path("") - ws.Produces("text/plain", "application/json") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newGetConsumingOctetStreamService() *WebService { - ws := new(WebService).Path("") - ws.Consumes("application/octet-stream") - ws.Route(ws.GET("/get").To(doNothing)) - return ws -} - -func newSelectedRouteTestingService() *WebService { - ws := new(WebService).Path("") - ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker)) - return ws -} - -func selectedRouteChecker(req *Request, resp *Response) { - if req.SelectedRoutePath() != pathGetFriends { - resp.InternalServerError() - } -} - -func doPanic(req *Request, resp *Response) { - println("lightning...") - panic("fire") -} - -func doNothing(req *Request, resp *Response) { -} diff --git a/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go b/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go deleted file mode 100644 index e9e68ceef72..00000000000 --- a/Godeps/_workspace/src/github.com/evanphx/json-patch/merge_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package jsonpatch - -import ( - "strings" - "testing" -) - -func mergePatch(doc, patch string) string { - out, err := MergePatch([]byte(doc), []byte(patch)) - - if err != nil { - panic(err) - } - - return string(out) -} - -func TestMergePatchReplaceKey(t *testing.T) { - doc := `{ "title": "hello" }` - pat := `{ "title": "goodbye" }` - - res := mergePatch(doc, pat) - - if !compareJSON(pat, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchIgnoresOtherValues(t *testing.T) { - doc := `{ "title": "hello", "age": 18 }` - pat := `{ "title": "goodbye" }` - - res := mergePatch(doc, pat) - - exp := `{ "title": "goodbye", "age": 18 }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchNilDoc(t *testing.T) { - doc := `{ "title": null }` - pat := `{ "title": {"foo": "bar"} }` - - res := mergePatch(doc, pat) - - exp := `{ "title": {"foo": "bar"} }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergePatchRecursesIntoObjects(t *testing.T) { - doc := `{ "person": { "title": "hello", "age": 18 } }` - pat := `{ "person": { "title": "goodbye" } }` - - res := mergePatch(doc, pat) - - exp := `{ "person": { "title": "goodbye", "age": 18 } }` - - if !compareJSON(exp, res) { - t.Fatalf("Key was not replaced") - } -} - -type nonObjectCases struct { - doc, pat, res string -} - -func TestMergePatchReplacesNonObjectsWholesale(t *testing.T) { - a1 := `[1]` - a2 := `[2]` - o1 := `{ "a": 1 }` - o2 := `{ "a": 2 }` - o3 := `{ "a": 1, "b": 1 }` - o4 := `{ "a": 2, "b": 1 }` - - cases := []nonObjectCases{ - {a1, a2, a2}, - {o1, a2, a2}, - {a1, o1, o1}, - {o3, o2, o4}, - } - - for _, c := range cases { - act := mergePatch(c.doc, c.pat) - - if !compareJSON(c.res, act) { - t.Errorf("whole object replacement failed") - } - } -} - -func TestMergePatchReturnsErrorOnBadJSON(t *testing.T) { - _, err := MergePatch([]byte(`[[[[`), []byte(`1`)) - - if err == nil { - t.Errorf("Did not return an error for bad json: %s", err) - } - - _, err = MergePatch([]byte(`1`), []byte(`[[[[`)) - - if err == nil { - t.Errorf("Did not return an error for bad json: %s", err) - } -} - -var rfcTests = []struct { - target string - patch string - expected string -}{ - // test cases from https://tools.ietf.org/html/rfc7386#appendix-A - {target: `{"a":"b"}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, - {target: `{"a":"b"}`, patch: `{"b":"c"}`, expected: `{"a":"b","b":"c"}`}, - {target: `{"a":"b"}`, patch: `{"a":null}`, expected: `{}`}, - {target: `{"a":"b","b":"c"}`, patch: `{"a":null}`, expected: `{"b":"c"}`}, - {target: `{"a":["b"]}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, - {target: `{"a":"c"}`, patch: `{"a":["b"]}`, expected: `{"a":["b"]}`}, - {target: `{"a":{"b": "c"}}`, patch: `{"a": {"b": "d","c": null}}`, expected: `{"a":{"b":"d"}}`}, - {target: `{"a":[{"b":"c"}]}`, patch: `{"a":[1]}`, expected: `{"a":[1]}`}, - {target: `["a","b"]`, patch: `["c","d"]`, expected: `["c","d"]`}, - {target: `{"a":"b"}`, patch: `["c"]`, expected: `["c"]`}, - // {target: `{"a":"foo"}`, patch: `null`, expected: `null`}, - // {target: `{"a":"foo"}`, patch: `"bar"`, expected: `"bar"`}, - {target: `{"e":null}`, patch: `{"a":1}`, expected: `{"a":1,"e":null}`}, - {target: `[1,2]`, patch: `{"a":"b","c":null}`, expected: `{"a":"b"}`}, - {target: `{}`, patch: `{"a":{"bb":{"ccc":null}}}`, expected: `{"a":{"bb":{}}}`}, -} - -func TestMergePatchRFCCases(t *testing.T) { - for i, c := range rfcTests { - out := mergePatch(c.target, c.patch) - - if !compareJSON(out, c.expected) { - t.Errorf("case[%d], patch '%s' did not apply properly to '%s'. expected:\n'%s'\ngot:\n'%s'", i, c.patch, c.target, c.expected, out) - } - } -} - -var rfcFailTests = ` - {"a":"foo"} | null - {"a":"foo"} | "bar" -` - -func TestMergePatchFailRFCCases(t *testing.T) { - tests := strings.Split(rfcFailTests, "\n") - - for _, c := range tests { - if strings.TrimSpace(c) == "" { - continue - } - - parts := strings.SplitN(c, "|", 2) - - doc := strings.TrimSpace(parts[0]) - pat := strings.TrimSpace(parts[1]) - - out, err := MergePatch([]byte(doc), []byte(pat)) - - if err != errBadJSONPatch { - t.Errorf("error not returned properly: %s, %s", err, string(out)) - } - } - -} - -func TestMergeReplaceKey(t *testing.T) { - doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` - pat := `{ "title": "goodbye", "nested": {"one": 2, "two": 2} }` - - exp := `{ "title": "goodbye", "nested": {"one": 2} }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Key was not replaced") - } -} - -func TestMergeGetArray(t *testing.T) { - doc := `{ "title": "hello", "array": ["one", "two"], "notmatch": [1, 2, 3] }` - pat := `{ "title": "hello", "array": ["one", "two", "three"], "notmatch": [1, 2, 3] }` - - exp := `{ "array": ["one", "two", "three"] }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Array was not added") - } -} - -func TestMergeGetObjArray(t *testing.T) { - doc := `{ "title": "hello", "array": [{"banana": true}, {"evil": false}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` - pat := `{ "title": "hello", "array": [{"banana": false}, {"evil": true}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` - - exp := `{ "array": [{"banana": false}, {"evil": true}] }` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(exp, string(res)) { - t.Fatalf("Object array was not added") - } -} - -func TestMergeDeleteKey(t *testing.T) { - doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` - pat := `{ "title": "hello", "nested": {"one": 1} }` - - exp := `{"nested":{"two":null}}` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Key was not removed") - } -} - -func TestMergeEmptyArray(t *testing.T) { - doc := `{ "array": null }` - pat := `{ "array": [] }` - - exp := `{"array":[]}` - - res, err := CreateMergePatch([]byte(doc), []byte(pat)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Key was not removed") - } -} - -func TestMergeObjArray(t *testing.T) { - doc := `{ "array": [ {"a": {"b": 2}}, {"a": {"b": 3}} ]}` - exp := `{}` - - res, err := CreateMergePatch([]byte(doc), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if exp != string(res) { - t.Fatalf("Array was not empty, was " + string(res)) - } -} - -func TestMergeComplexMatch(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - empty := `{}` - res, err := CreateMergePatch([]byte(doc), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - // We cannot use "compareJSON", since Equals does not report a difference if the value is null - if empty != string(res) { - t.Fatalf("Did not get empty result, was:%s", string(res)) - } -} - -func TestMergeComplexAddAll(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - empty := `{}` - res, err := CreateMergePatch([]byte(empty), []byte(doc)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if !compareJSON(doc, string(res)) { - t.Fatalf("Did not get everything as, it was:\n%s", string(res)) - } -} - -func TestMergeComplexRemoveAll(t *testing.T) { - doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` - exp := `{"a":null,"f":null,"hello":null,"i":null,"n":null,"nested":null,"pi":null,"t":null}` - empty := `{}` - res, err := CreateMergePatch([]byte(doc), []byte(empty)) - - if err != nil { - t.Errorf("Unexpected error: %s, %s", err, string(res)) - } - - if exp != string(res) { - t.Fatalf("Did not get result, was:%s", string(res)) - } - - // FIXME: Crashes if using compareJSON like this: - /* - if !compareJSON(doc, string(res)) { - t.Fatalf("Did not get everything as, it was:\n%s", string(res)) - } - */ -} diff --git a/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go b/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go deleted file mode 100644 index 493c4f165c1..00000000000 --- a/Godeps/_workspace/src/github.com/evanphx/json-patch/patch_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package jsonpatch - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "testing" -) - -func reformatJSON(j string) string { - buf := new(bytes.Buffer) - - json.Indent(buf, []byte(j), "", " ") - - return buf.String() -} - -func compareJSON(a, b string) bool { - // return Equal([]byte(a), []byte(b)) - - var obj_a, obj_b map[string]interface{} - json.Unmarshal([]byte(a), &obj_a) - json.Unmarshal([]byte(b), &obj_b) - - // fmt.Printf("Comparing %#v\nagainst %#v\n", obj_a, obj_b) - return reflect.DeepEqual(obj_a, obj_b) -} - -func applyPatch(doc, patch string) (string, error) { - obj, err := DecodePatch([]byte(patch)) - - if err != nil { - panic(err) - } - - out, err := obj.Apply([]byte(doc)) - - if err != nil { - return "", err - } - - return string(out), nil -} - -type Case struct { - doc, patch, result string -} - -var Cases = []Case{ - { - `{ "foo": "bar"}`, - `[ - { "op": "add", "path": "/baz", "value": "qux" } - ]`, - `{ - "baz": "qux", - "foo": "bar" - }`, - }, - { - `{ "foo": [ "bar", "baz" ] }`, - `[ - { "op": "add", "path": "/foo/1", "value": "qux" } - ]`, - `{ "foo": [ "bar", "qux", "baz" ] }`, - }, - { - `{ "baz": "qux", "foo": "bar" }`, - `[ { "op": "remove", "path": "/baz" } ]`, - `{ "foo": "bar" }`, - }, - { - `{ "foo": [ "bar", "qux", "baz" ] }`, - `[ { "op": "remove", "path": "/foo/1" } ]`, - `{ "foo": [ "bar", "baz" ] }`, - }, - { - `{ "baz": "qux", "foo": "bar" }`, - `[ { "op": "replace", "path": "/baz", "value": "boo" } ]`, - `{ "baz": "boo", "foo": "bar" }`, - }, - { - `{ - "foo": { - "bar": "baz", - "waldo": "fred" - }, - "qux": { - "corge": "grault" - } - }`, - `[ { "op": "move", "from": "/foo/waldo", "path": "/qux/thud" } ]`, - `{ - "foo": { - "bar": "baz" - }, - "qux": { - "corge": "grault", - "thud": "fred" - } - }`, - }, - { - `{ "foo": [ "all", "grass", "cows", "eat" ] }`, - `[ { "op": "move", "from": "/foo/1", "path": "/foo/3" } ]`, - `{ "foo": [ "all", "cows", "eat", "grass" ] }`, - }, - { - `{ "foo": "bar" }`, - `[ { "op": "add", "path": "/child", "value": { "grandchild": { } } } ]`, - `{ "foo": "bar", "child": { "grandchild": { } } }`, - }, - { - `{ "foo": ["bar"] }`, - `[ { "op": "add", "path": "/foo/-", "value": ["abc", "def"] } ]`, - `{ "foo": ["bar", ["abc", "def"]] }`, - }, - { - `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, - `[ { "op": "remove", "path": "/qux/bar" } ]`, - `{ "foo": "bar", "qux": { "baz": 1 } }`, - }, -} - -type BadCase struct { - doc, patch string -} - -var MutationTestCases = []BadCase{ - { - `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, - `[ { "op": "remove", "path": "/qux/bar" } ]`, - }, -} - -var BadCases = []BadCase{ - { - `{ "foo": "bar" }`, - `[ { "op": "add", "path": "/baz/bat", "value": "qux" } ]`, - }, -} - -func TestAllCases(t *testing.T) { - for _, c := range Cases { - out, err := applyPatch(c.doc, c.patch) - - if err != nil { - t.Errorf("Unable to apply patch: %s", err) - } - - if !compareJSON(out, c.result) { - t.Errorf("Patch did not apply. Expected:\n%s\n\nActual:\n%s", - reformatJSON(c.result), reformatJSON(out)) - } - } - - for _, c := range MutationTestCases { - out, err := applyPatch(c.doc, c.patch) - - if err != nil { - t.Errorf("Unable to apply patch: %s", err) - } - - if compareJSON(out, c.doc) { - t.Errorf("Patch did not apply. Original:\n%s\n\nPatched:\n%s", - reformatJSON(c.doc), reformatJSON(out)) - } - } - - for _, c := range BadCases { - _, err := applyPatch(c.doc, c.patch) - - if err == nil { - t.Errorf("Patch should have failed to apply but it did not") - } - } -} - -type TestCase struct { - doc, patch string - result bool - failedPath string -} - -var TestCases = []TestCase{ - { - `{ - "baz": "qux", - "foo": [ "a", 2, "c" ] - }`, - `[ - { "op": "test", "path": "/baz", "value": "qux" }, - { "op": "test", "path": "/foo/1", "value": 2 } - ]`, - true, - "", - }, - { - `{ "baz": "qux" }`, - `[ { "op": "test", "path": "/baz", "value": "bar" } ]`, - false, - "/baz", - }, - { - `{ - "baz": "qux", - "foo": ["a", 2, "c"] - }`, - `[ - { "op": "test", "path": "/baz", "value": "qux" }, - { "op": "test", "path": "/foo/1", "value": "c" } - ]`, - false, - "/foo/1", - }, -} - -func TestAllTest(t *testing.T) { - for _, c := range TestCases { - _, err := applyPatch(c.doc, c.patch) - - if c.result && err != nil { - t.Errorf("Testing failed when it should have passed: %s", err) - } else if !c.result && err == nil { - t.Errorf("Testing passed when it should have faild: %s", err) - } else if !c.result { - expected := fmt.Sprintf("Testing value %s failed", c.failedPath) - if err.Error() != expected { - t.Errorf("Testing failed as expected but invalid message: expected [%s], got [%s]", expected, err) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go deleted file mode 100644 index b3d4f8fc86a..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/auth_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "encoding/base64" - "fmt" - "net/http" - "strings" - "testing" -) - -func TestAuthLegacyConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("user:pass")) - read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != nil { - t.Error(err) - } - c, ok := ac.Configs["docker.io"] - if !ok { - t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") - } - if got, want := c.Email, "user@example.com"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Username, "user"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Password, "pass"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.ServerAddress, "docker.io"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) - } -} - -func TestAuthBadConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("userpass")) - read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != ErrCannotParseDockercfg { - t.Errorf("Incorrect error returned %v\n", err) - } - if ac != nil { - t.Errorf("Invalid auth configuration returned, should be nil %v\n", ac) - } -} - -func TestAuthConfig(t *testing.T) { - auth := base64.StdEncoding.EncodeToString([]byte("user:pass")) - read := strings.NewReader(fmt.Sprintf(`{"auths":{"docker.io":{"auth":"%s","email":"user@example.com"}}}`, auth)) - ac, err := NewAuthConfigurations(read) - if err != nil { - t.Error(err) - } - c, ok := ac.Configs["docker.io"] - if !ok { - t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") - } - if got, want := c.Email, "user@example.com"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Username, "user"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.Password, "pass"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) - } - if got, want := c.ServerAddress, "docker.io"; got != want { - t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) - } -} - -func TestAuthCheck(t *testing.T) { - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - if err := client.AuthCheck(nil); err == nil { - t.Fatalf("expected error on nil auth config") - } - // test good auth - if err := client.AuthCheck(&AuthConfiguration{}); err != nil { - t.Fatal(err) - } - *fakeRT = FakeRoundTripper{status: http.StatusUnauthorized} - if err := client.AuthCheck(&AuthConfiguration{}); err == nil { - t.Fatal("expected failure from unauthorized auth") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go deleted file mode 100644 index c9640f20571..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/build_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package docker - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" - "os" - "reflect" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" -) - -func TestBuildImageMultipleContextsError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - InputStream: &buf, - OutputStream: &buf, - ContextDir: "testing/data", - } - err := client.BuildImage(opts) - if err != ErrMultipleContexts { - t.Errorf("BuildImage: providing both InputStream and ContextDir should produce an error") - } -} - -func TestBuildImageContextDirDockerignoreParsing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - - if err := os.Symlink("doesnotexist", "testing/data/symlink"); err != nil { - t.Errorf("error creating symlink on demand: %s", err) - } - defer func() { - if err := os.Remove("testing/data/symlink"); err != nil { - t.Errorf("error removing symlink on demand: %s", err) - } - }() - - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - OutputStream: &buf, - ContextDir: "testing/data", - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - reqBody := fakeRT.requests[0].Body - tmpdir, err := unpackBodyTarball(reqBody) - if err != nil { - t.Fatal(err) - } - - defer func() { - if err := os.RemoveAll(tmpdir); err != nil { - t.Fatal(err) - } - }() - - files, err := ioutil.ReadDir(tmpdir) - if err != nil { - t.Fatal(err) - } - - foundFiles := []string{} - for _, file := range files { - foundFiles = append(foundFiles, file.Name()) - } - - expectedFiles := []string{ - ".dockerignore", - "Dockerfile", - "barfile", - "ca.pem", - "cert.pem", - "key.pem", - "server.pem", - "serverkey.pem", - "symlink", - } - - if !reflect.DeepEqual(expectedFiles, foundFiles) { - t.Errorf( - "BuildImage: incorrect files sent in tarball to docker server\nexpected %+v, found %+v", - expectedFiles, foundFiles, - ) - } -} - -func TestBuildImageSendXRegistryConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - OutputStream: &buf, - ContextDir: "testing/data", - AuthConfigs: AuthConfigurations{ - Configs: map[string]AuthConfiguration{ - "quay.io": { - Username: "foo", - Password: "bar", - Email: "baz", - ServerAddress: "quay.io", - }, - }, - }, - } - - encodedConfig := "eyJjb25maWdzIjp7InF1YXkuaW8iOnsidXNlcm5hbWUiOiJmb28iLCJwYXNzd29yZCI6ImJhciIsImVtYWlsIjoiYmF6Iiwic2VydmVyYWRkcmVzcyI6InF1YXkuaW8ifX19Cg==" - - if err := client.BuildImage(opts); err != nil { - t.Fatal(err) - } - - xRegistryConfig := fakeRT.requests[0].Header["X-Registry-Config"][0] - if xRegistryConfig != encodedConfig { - t.Errorf( - "BuildImage: X-Registry-Config not set currectly: expected %q, got %q", - encodedConfig, - xRegistryConfig, - ) - } -} - -func unpackBodyTarball(req io.ReadCloser) (tmpdir string, err error) { - tmpdir, err = ioutil.TempDir("", "go-dockerclient-test") - if err != nil { - return - } - err = archive.Untar(req, tmpdir, &archive.TarOptions{ - Compression: archive.Uncompressed, - NoLchown: true, - }) - return -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go deleted file mode 100644 index 7c2ec30f7b9..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/change_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 go-dockerclient 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 docker - -import ( - "testing" -) - -func TestChangeString(t *testing.T) { - var tests = []struct { - change Change - expected string - }{ - {Change{"/etc/passwd", ChangeModify}, "C /etc/passwd"}, - {Change{"/etc/passwd", ChangeAdd}, "A /etc/passwd"}, - {Change{"/etc/passwd", ChangeDelete}, "D /etc/passwd"}, - {Change{"/etc/passwd", 33}, " /etc/passwd"}, - } - for _, tt := range tests { - if got := tt.change.String(); got != tt.expected { - t.Errorf("Change.String(): want %q. Got %q.", tt.expected, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go deleted file mode 100644 index 67230a4e15c..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/client_test.go +++ /dev/null @@ -1,460 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "testing" - "time" -) - -func TestNewAPIClient(t *testing.T) { - endpoint := "http://localhost:4243" - client, err := NewClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if client.HTTPClient != http.DefaultClient { - t.Errorf("Expected http.Client %#v. Got %#v.", http.DefaultClient, client.HTTPClient) - } - // test unix socket endpoints - endpoint = "unix:///var/run/docker.sock" - client, err = NewClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if !client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be true, got false") - } - if client.requestedAPIVersion != nil { - t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) - } -} - -func newTLSClient(endpoint string) (*Client, error) { - return NewTLSClient(endpoint, - "testing/data/cert.pem", - "testing/data/key.pem", - "testing/data/ca.pem") -} - -func TestNewTSLAPIClient(t *testing.T) { - endpoint := "https://localhost:4243" - client, err := newTLSClient(endpoint) - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if !client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be true, got false") - } - if client.requestedAPIVersion != nil { - t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) - } -} - -func TestNewVersionedClient(t *testing.T) { - endpoint := "http://localhost:4243" - client, err := NewVersionedClient(endpoint, "1.12") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if client.HTTPClient != http.DefaultClient { - t.Errorf("Expected http.Client %#v. Got %#v.", http.DefaultClient, client.HTTPClient) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewTLSVersionedClient(t *testing.T) { - certPath := "testing/data/cert.pem" - keyPath := "testing/data/key.pem" - caPath := "testing/data/ca.pem" - endpoint := "https://localhost:4243" - client, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") - if err != nil { - t.Fatal(err) - } - if client.endpoint != endpoint { - t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) - } - if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.14" { - t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.14", reqVersion) - } - if client.SkipServerVersionCheck { - t.Error("Expected SkipServerVersionCheck to be false, got true") - } -} - -func TestNewTLSVersionedClientInvalidCA(t *testing.T) { - certPath := "testing/data/cert.pem" - keyPath := "testing/data/key.pem" - caPath := "testing/data/key.pem" - endpoint := "https://localhost:4243" - _, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") - if err == nil { - t.Errorf("Expected invalid ca at %s", caPath) - } -} - -func TestNewClientInvalidEndpoint(t *testing.T) { - cases := []string{ - "htp://localhost:3243", "http://localhost:a", "localhost:8080", - "", "localhost", "http://localhost:8080:8383", "http://localhost:65536", - "https://localhost:-20", - } - for _, c := range cases { - client, err := NewClient(c) - if client != nil { - t.Errorf("Want client for invalid endpoint, got %#v.", client) - } - if !reflect.DeepEqual(err, ErrInvalidEndpoint) { - t.Errorf("NewClient(%q): Got invalid error for invalid endpoint. Want %#v. Got %#v.", c, ErrInvalidEndpoint, err) - } - } -} - -func TestNewTLSClient(t *testing.T) { - var tests = []struct { - endpoint string - expected string - }{ - {"tcp://localhost:2376", "https"}, - {"tcp://localhost:2375", "https"}, - {"tcp://localhost:4000", "https"}, - {"http://localhost:4000", "https"}, - } - - for _, tt := range tests { - client, err := newTLSClient(tt.endpoint) - if err != nil { - t.Error(err) - } - got := client.endpointURL.Scheme - if got != tt.expected { - t.Errorf("endpointURL.Scheme: Got %s. Want %s.", got, tt.expected) - } - } -} - -func TestEndpoint(t *testing.T) { - client, err := NewVersionedClient("http://localhost:4243", "1.12") - if err != nil { - t.Fatal(err) - } - if endpoint := client.Endpoint(); endpoint != client.endpoint { - t.Errorf("Client.Endpoint(): want %q. Got %q", client.endpoint, endpoint) - } -} - -func TestGetURL(t *testing.T) { - var tests = []struct { - endpoint string - path string - expected string - }{ - {"http://localhost:4243/", "/", "http://localhost:4243/"}, - {"http://localhost:4243", "/", "http://localhost:4243/"}, - {"http://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, - {"tcp://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, - {"http://localhost:4243/////", "/", "http://localhost:4243/"}, - {"unix:///var/run/docker.socket", "/containers", "/containers"}, - } - for _, tt := range tests { - client, _ := NewClient(tt.endpoint) - client.endpoint = tt.endpoint - client.SkipServerVersionCheck = true - got := client.getURL(tt.path) - if got != tt.expected { - t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) - } - } -} - -func TestGetFakeUnixURL(t *testing.T) { - var tests = []struct { - endpoint string - path string - expected string - }{ - {"unix://var/run/docker.sock", "/", "http://unix.sock/"}, - {"unix://var/run/docker.socket", "/", "http://unix.sock/"}, - {"unix://var/run/docker.sock", "/containers/ps", "http://unix.sock/containers/ps"}, - } - for _, tt := range tests { - client, _ := NewClient(tt.endpoint) - client.endpoint = tt.endpoint - client.SkipServerVersionCheck = true - got := client.getFakeUnixURL(tt.path) - if got != tt.expected { - t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) - } - } -} - -func TestError(t *testing.T) { - fakeBody := ioutil.NopCloser(bytes.NewBufferString("bad parameter")) - resp := &http.Response{ - StatusCode: 400, - Body: fakeBody, - } - err := newError(resp) - expected := Error{Status: 400, Message: "bad parameter"} - if !reflect.DeepEqual(expected, *err) { - t.Errorf("Wrong error type. Want %#v. Got %#v.", expected, *err) - } - message := "API error (400): bad parameter" - if err.Error() != message { - t.Errorf("Wrong error message. Want %q. Got %q.", message, err.Error()) - } -} - -func TestQueryString(t *testing.T) { - v := float32(2.4) - f32QueryString := fmt.Sprintf("w=%s&x=10&y=10.35", strconv.FormatFloat(float64(v), 'f', -1, 64)) - jsonPerson := url.QueryEscape(`{"Name":"gopher","age":4}`) - var tests = []struct { - input interface{} - want string - }{ - {&ListContainersOptions{All: true}, "all=1"}, - {ListContainersOptions{All: true}, "all=1"}, - {ListContainersOptions{Before: "something"}, "before=something"}, - {ListContainersOptions{Before: "something", Since: "other"}, "before=something&since=other"}, - {ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, "filters=%7B%22status%22%3A%5B%22paused%22%2C%22running%22%5D%7D"}, - {dumb{X: 10, Y: 10.35000}, "x=10&y=10.35"}, - {dumb{W: v, X: 10, Y: 10.35000}, f32QueryString}, - {dumb{X: 10, Y: 10.35000, Z: 10}, "x=10&y=10.35&zee=10"}, - {dumb{v: 4, X: 10, Y: 10.35000}, "x=10&y=10.35"}, - {dumb{T: 10, Y: 10.35000}, "y=10.35"}, - {dumb{Person: &person{Name: "gopher", Age: 4}}, "p=" + jsonPerson}, - {nil, ""}, - {10, ""}, - {"not_a_struct", ""}, - } - for _, tt := range tests { - got := queryString(tt.input) - if got != tt.want { - t.Errorf("queryString(%v). Want %q. Got %q.", tt.input, tt.want, got) - } - } -} - -func TestNewAPIVersionFailures(t *testing.T) { - var tests = []struct { - input string - expectedError string - }{ - {"1-0", `Unable to parse version "1-0"`}, - {"1.0-beta", `Unable to parse version "1.0-beta": "0-beta" is not an integer`}, - } - for _, tt := range tests { - v, err := NewAPIVersion(tt.input) - if v != nil { - t.Errorf("Expected version, got %v.", v) - } - if err.Error() != tt.expectedError { - t.Errorf("NewAPIVersion(%q): wrong error. Want %q. Got %q", tt.input, tt.expectedError, err.Error()) - } - } -} - -func TestAPIVersions(t *testing.T) { - var tests = []struct { - a string - b string - expectedALessThanB bool - expectedALessThanOrEqualToB bool - expectedAGreaterThanB bool - expectedAGreaterThanOrEqualToB bool - }{ - {"1.11", "1.11", false, true, false, true}, - {"1.10", "1.11", true, true, false, false}, - {"1.11", "1.10", false, false, true, true}, - - {"1.9", "1.11", true, true, false, false}, - {"1.11", "1.9", false, false, true, true}, - - {"1.1.1", "1.1", false, false, true, true}, - {"1.1", "1.1.1", true, true, false, false}, - - {"2.1", "1.1.1", false, false, true, true}, - {"2.1", "1.3.1", false, false, true, true}, - {"1.1.1", "2.1", true, true, false, false}, - {"1.3.1", "2.1", true, true, false, false}, - } - - for _, tt := range tests { - a, _ := NewAPIVersion(tt.a) - b, _ := NewAPIVersion(tt.b) - - if tt.expectedALessThanB && !a.LessThan(b) { - t.Errorf("Expected %#v < %#v", a, b) - } - if tt.expectedALessThanOrEqualToB && !a.LessThanOrEqualTo(b) { - t.Errorf("Expected %#v <= %#v", a, b) - } - if tt.expectedAGreaterThanB && !a.GreaterThan(b) { - t.Errorf("Expected %#v > %#v", a, b) - } - if tt.expectedAGreaterThanOrEqualToB && !a.GreaterThanOrEqualTo(b) { - t.Errorf("Expected %#v >= %#v", a, b) - } - } -} - -func TestPing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - err := client.Ping() - if err != nil { - t.Fatal(err) - } -} - -func TestPingFailing(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } - expectedErrMsg := "API error (500): " - if err.Error() != expectedErrMsg { - t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) - } -} - -func TestPingFailingWrongStatus(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusAccepted} - client := newTestClient(fakeRT) - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } - expectedErrMsg := "API error (202): " - if err.Error() != expectedErrMsg { - t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) - } -} - -func TestPingErrorWithUnixSocket(t *testing.T) { - go func() { - li, err := net.Listen("unix", "/tmp/echo.sock") - if err != nil { - t.Fatal(err) - } - defer li.Close() - if err != nil { - t.Fatalf("Expected to get listener, but failed: %#v", err) - } - - fd, err := li.Accept() - if err != nil { - t.Fatalf("Expected to accept connection, but failed: %#v", err) - } - - buf := make([]byte, 512) - nr, err := fd.Read(buf) - - // Create invalid response message to trigger error. - data := buf[0:nr] - for i := 0; i < 10; i++ { - data[i] = 63 - } - - _, err = fd.Write(data) - if err != nil { - t.Fatalf("Expected to write to socket, but failed: %#v", err) - } - - return - }() - - // Wait for unix socket to listen - time.Sleep(10 * time.Millisecond) - - endpoint := "unix:///tmp/echo.sock" - u, _ := parseEndpoint(endpoint, false) - client := Client{ - HTTPClient: http.DefaultClient, - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - } - - err := client.Ping() - if err == nil { - t.Fatal("Expected non nil error, got nil") - } -} - -type FakeRoundTripper struct { - message string - status int - header map[string]string - requests []*http.Request -} - -func (rt *FakeRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - body := strings.NewReader(rt.message) - rt.requests = append(rt.requests, r) - res := &http.Response{ - StatusCode: rt.status, - Body: ioutil.NopCloser(body), - Header: make(http.Header), - } - for k, v := range rt.header { - res.Header.Set(k, v) - } - return res, nil -} - -func (rt *FakeRoundTripper) Reset() { - rt.requests = nil -} - -type person struct { - Name string - Age int `json:"age"` -} - -type dumb struct { - T int `qs:"-"` - v int - W float32 - X int - Y float64 - Z int `qs:"zee"` - Person *person `qs:"p"` -} - -type fakeEndpointURL struct { - Scheme string -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go deleted file mode 100644 index ea7fad2f6f7..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/container_test.go +++ /dev/null @@ -1,1982 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -func TestStateString(t *testing.T) { - started := time.Now().Add(-3 * time.Hour) - var tests = []struct { - input State - expected string - }{ - {State{Running: true, Paused: true}, "^paused$"}, - {State{Running: true, StartedAt: started}, "^Up 3h.*$"}, - {State{Running: false, ExitCode: 7}, "^Exit 7$"}, - } - for _, tt := range tests { - re := regexp.MustCompile(tt.expected) - if got := tt.input.String(); !re.MatchString(got) { - t.Errorf("State.String(): wrong result. Want %q. Got %q.", tt.expected, got) - } - } -} - -func TestListContainers(t *testing.T) { - jsonContainers := `[ - { - "Id": "8dfafdbc3a40", - "Image": "base:latest", - "Command": "echo 1", - "Created": 1367854155, - "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "9cd87474be90", - "Image": "base:latest", - "Command": "echo 222222", - "Created": 1367854155, - "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "3176a2479c92", - "Image": "base:latest", - "Command": "echo 3333333333333333", - "Created": 1367854154, - "Ports":[{"PrivatePort": 2221, "PublicPort": 3331, "Type": "tcp"}], - "Status": "Exit 0" - }, - { - "Id": "4cb07b47f9fb", - "Image": "base:latest", - "Command": "echo 444444444444444444444444444444444", - "Ports":[{"PrivatePort": 2223, "PublicPort": 3332, "Type": "tcp"}], - "Created": 1367854152, - "Status": "Exit 0" - } -]` - var expected []APIContainers - err := json.Unmarshal([]byte(jsonContainers), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: jsonContainers, status: http.StatusOK}) - containers, err := client.ListContainers(ListContainersOptions{}) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(containers, expected) { - t.Errorf("ListContainers: Expected %#v. Got %#v.", expected, containers) - } -} - -func TestListContainersParams(t *testing.T) { - var tests = []struct { - input ListContainersOptions - params map[string][]string - }{ - {ListContainersOptions{}, map[string][]string{}}, - {ListContainersOptions{All: true}, map[string][]string{"all": {"1"}}}, - {ListContainersOptions{All: true, Limit: 10}, map[string][]string{"all": {"1"}, "limit": {"10"}}}, - { - ListContainersOptions{All: true, Limit: 10, Since: "adf9983", Before: "abdeef"}, - map[string][]string{"all": {"1"}, "limit": {"10"}, "since": {"adf9983"}, "before": {"abdeef"}}, - }, - { - ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, - map[string][]string{"filters": {"{\"status\":[\"paused\",\"running\"]}"}}, - }, - { - ListContainersOptions{All: true, Filters: map[string][]string{"exited": {"0"}, "status": {"exited"}}}, - map[string][]string{"all": {"1"}, "filters": {"{\"exited\":[\"0\"],\"status\":[\"exited\"]}"}}, - }, - } - fakeRT := &FakeRoundTripper{message: "[]", status: http.StatusOK} - client := newTestClient(fakeRT) - u, _ := url.Parse(client.getURL("/containers/json")) - for _, tt := range tests { - if _, err := client.ListContainers(tt.input); err != nil { - t.Error(err) - } - got := map[string][]string(fakeRT.requests[0].URL.Query()) - if !reflect.DeepEqual(got, tt.params) { - t.Errorf("Expected %#v, got %#v.", tt.params, got) - } - if path := fakeRT.requests[0].URL.Path; path != u.Path { - t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) - } - if meth := fakeRT.requests[0].Method; meth != "GET" { - t.Errorf("Wrong HTTP method. Want GET. Got %s.", meth) - } - fakeRT.Reset() - } -} - -func TestListContainersFailure(t *testing.T) { - var tests = []struct { - status int - message string - }{ - {400, "bad parameter"}, - {500, "internal server error"}, - } - for _, tt := range tests { - client := newTestClient(&FakeRoundTripper{message: tt.message, status: tt.status}) - expected := Error{Status: tt.status, Message: tt.message} - containers, err := client.ListContainers(ListContainersOptions{}) - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("Wrong error in ListContainers. Want %#v. Got %#v.", expected, err) - } - if len(containers) > 0 { - t.Errorf("ListContainers failure. Expected empty list. Got %#v.", containers) - } - } -} - -func TestInspectContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "AppArmorProfile": "Profile", - "Created": "2013-05-07T14:51:42.087658+02:00", - "Path": "date", - "Args": [], - "Config": { - "Hostname": "4fa6e0f0c678", - "User": "", - "Memory": 17179869184, - "MemorySwap": 34359738368, - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "PortSpecs": null, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": [ - "date" - ], - "Image": "base", - "Volumes": {}, - "VolumesFrom": "", - "SecurityOpt": [ - "label:user:USER" - ], - "Ulimits": [ - { "Name": "nofile", "Soft": 1024, "Hard": 2048 } - ] - }, - "State": { - "Running": false, - "Pid": 0, - "ExitCode": 0, - "StartedAt": "2013-05-07T14:51:42.087658+02:00", - "Ghost": false - }, - "Node": { - "ID": "4I4E:QR4I:Z733:QEZK:5X44:Q4T7:W2DD:JRDY:KB2O:PODO:Z5SR:XRB6", - "IP": "192.168.99.105", - "Addra": "192.168.99.105:2376", - "Name": "node-01", - "Cpus": 4, - "Memory": 1048436736, - "Labels": { - "executiondriver": "native-0.2", - "kernelversion": "3.18.5-tinycore64", - "operatingsystem": "Boot2Docker 1.5.0 (TCL 5.4); master : a66bce5 - Tue Feb 10 23:31:27 UTC 2015", - "provider": "virtualbox", - "storagedriver": "aufs" - } - }, - "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "NetworkSettings": { - "IpAddress": "", - "IpPrefixLen": 0, - "Gateway": "", - "Bridge": "", - "PortMapping": null - }, - "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", - "ResolvConfPath": "/etc/resolv.conf", - "Volumes": {}, - "HostConfig": { - "Binds": null, - "ContainerIDFile": "", - "LxcConf": [], - "Privileged": false, - "PortBindings": { - "80/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49153" - } - ] - }, - "Links": null, - "PublishAllPorts": false, - "CgroupParent": "/mesos", - "Memory": 17179869184, - "MemorySwap": 34359738368, - "GroupAdd": ["fake", "12345"] - } -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - container, err := client.InspectContainer(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*container, expected) { - t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestInspectContainerNegativeSwap(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Created": "2013-05-07T14:51:42.087658+02:00", - "Path": "date", - "Args": [], - "Config": { - "Hostname": "4fa6e0f0c678", - "User": "", - "Memory": 17179869184, - "MemorySwap": -1, - "AttachStdin": false, - "AttachStdout": true, - "AttachStderr": true, - "PortSpecs": null, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": null, - "Cmd": [ - "date" - ], - "Image": "base", - "Volumes": {}, - "VolumesFrom": "" - }, - "State": { - "Running": false, - "Pid": 0, - "ExitCode": 0, - "StartedAt": "2013-05-07T14:51:42.087658+02:00", - "Ghost": false - }, - "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "NetworkSettings": { - "IpAddress": "", - "IpPrefixLen": 0, - "Gateway": "", - "Bridge": "", - "PortMapping": null - }, - "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", - "ResolvConfPath": "/etc/resolv.conf", - "Volumes": {}, - "HostConfig": { - "Binds": null, - "ContainerIDFile": "", - "LxcConf": [], - "Privileged": false, - "PortBindings": { - "80/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49153" - } - ] - }, - "Links": null, - "PublishAllPorts": false - } -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - container, err := client.InspectContainer(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*container, expected) { - t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestInspectContainerFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) - expected := Error{Status: 500, Message: "server error"} - container, err := client.InspectContainer("abe033") - if container != nil { - t.Errorf("InspectContainer: Expected container, got %#v", container) - } - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestInspectContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) - container, err := client.InspectContainer("abe033") - if container != nil { - t.Errorf("InspectContainer: Expected container, got %#v", container) - } - expected := &NoSuchContainer{ID: "abe033"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestContainerChanges(t *testing.T) { - jsonChanges := `[ - { - "Path":"/dev", - "Kind":0 - }, - { - "Path":"/dev/kmsg", - "Kind":1 - }, - { - "Path":"/test", - "Kind":1 - } -]` - var expected []Change - err := json.Unmarshal([]byte(jsonChanges), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonChanges, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c678" - changes, err := client.ContainerChanges(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(changes, expected) { - t.Errorf("ContainerChanges(%q): Expected %#v. Got %#v.", id, expected, changes) - } - expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/changes")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("ContainerChanges(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestContainerChangesFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) - expected := Error{Status: 500, Message: "server error"} - changes, err := client.ContainerChanges("abe033") - if changes != nil { - t.Errorf("ContainerChanges: Expected changes, got %#v", changes) - } - if !reflect.DeepEqual(expected, *err.(*Error)) { - t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestContainerChangesNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) - changes, err := client.ContainerChanges("abe033") - if changes != nil { - t.Errorf("ContainerChanges: Expected changes, got %#v", changes) - } - expected := &NoSuchContainer{ID: "abe033"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) - } -} - -func TestCreateContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Warnings": [] -}` - var expected Container - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{AttachStdout: true, AttachStdin: true} - opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} - container, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - if container.ID != id { - t.Errorf("CreateContainer: wrong ID. Want %q. Got %q.", id, container.ID) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("CreateContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/create")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("CreateContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - var gotBody Config - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } -} - -func TestCreateContainerImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusNotFound}) - config := Config{AttachStdout: true, AttachStdin: true} - container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) - if container != nil { - t.Errorf("CreateContainer: expected container, got %#v.", container) - } - if !reflect.DeepEqual(err, ErrNoSuchImage) { - t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestCreateContainerDuplicateName(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusConflict}) - config := Config{AttachStdout: true, AttachStdin: true} - container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) - if container != nil { - t.Errorf("CreateContainer: expected container, got %#v.", container) - } - if err != ErrContainerAlreadyExists { - t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrContainerAlreadyExists, err) - } -} - -func TestCreateContainerWithHostConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{} - hostConfig := HostConfig{PublishAllPorts: true} - opts := CreateContainerOptions{Name: "TestCreateContainerWithHostConfig", Config: &config, HostConfig: &hostConfig} - _, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - var gotBody map[string]interface{} - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } - if _, ok := gotBody["HostConfig"]; !ok { - t.Errorf("CreateContainer: wrong body. HostConfig was not serialized") - } -} - -func TestStartContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StartContainer(id, &HostConfig{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - expectedContentType := "application/json" - if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { - t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) - } -} - -func TestStartContainerNilHostConfig(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StartContainer(id, nil) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - expectedContentType := "application/json" - if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { - t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) - } - var buf [4]byte - req.Body.Read(buf[:]) - if string(buf[:]) != "null" { - t.Errorf("Startcontainer(%q): Wrong body. Want null. Got %s", id, buf[:]) - } -} - -func TestStartContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.StartContainer("a2344", &HostConfig{}) - expected := &NoSuchContainer{ID: "a2344", Err: err.(*NoSuchContainer).Err} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStartContainerAlreadyRunning(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "container already running", status: http.StatusNotModified}) - err := client.StartContainer("a2334", &HostConfig{}) - expected := &ContainerAlreadyRunning{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStopContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.StopContainer(id, 10) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("StopContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/stop")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("StopContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestStopContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.StopContainer("a2334", 10) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestStopContainerNotRunning(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "container not running", status: http.StatusNotModified}) - err := client.StopContainer("a2334", 10) - expected := &ContainerNotRunning{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRestartContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.RestartContainer(id, 10) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("RestartContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/restart")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RestartContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestRestartContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.RestartContainer("a2334", 10) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("RestartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestPauseContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.PauseContainer(id) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/pause")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestPauseContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.PauseContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestUnpauseContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.UnpauseContainer(id) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/unpause")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestUnpauseContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.UnpauseContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestKillContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.KillContainer(KillContainerOptions{ID: id}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/kill")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("KillContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestKillContainerSignal(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.KillContainer(KillContainerOptions{ID: id, Signal: SIGTERM}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - if signal := req.URL.Query().Get("signal"); signal != "15" { - t.Errorf("KillContainer(%q): Wrong query string in request. Want %q. Got %q.", id, "15", signal) - } -} - -func TestKillContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.KillContainer(KillContainerOptions{ID: "a2334"}) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("KillContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRemoveContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := RemoveContainerOptions{ID: id} - err := client.RemoveContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "DELETE" { - t.Errorf("RemoveContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "DELETE", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id)) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RemoveContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestRemoveContainerRemoveVolumes(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := RemoveContainerOptions{ID: id, RemoveVolumes: true} - err := client.RemoveContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - params := map[string][]string(req.URL.Query()) - expected := map[string][]string{"v": {"1"}} - if !reflect.DeepEqual(params, expected) { - t.Errorf("RemoveContainer(%q): wrong parameters. Want %#v. Got %#v.", id, expected, params) - } -} - -func TestRemoveContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - err := client.RemoveContainer(RemoveContainerOptions{ID: "a2334"}) - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("RemoveContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestResizeContainerTTY(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - err := client.ResizeContainerTTY(id, 40, 80) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ResizeContainerTTY(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/resize")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ResizeContainerTTY(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } - got := map[string][]string(req.URL.Query()) - expectedParams := map[string][]string{ - "w": {"80"}, - "h": {"40"}, - } - if !reflect.DeepEqual(got, expectedParams) { - t.Errorf("Expected %#v, got %#v.", expectedParams, got) - } -} - -func TestWaitContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: `{"StatusCode": 56}`, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - status, err := client.WaitContainer(id) - if err != nil { - t.Fatal(err) - } - if status != 56 { - t.Errorf("WaitContainer(%q): wrong return. Want 56. Got %d.", id, status) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("WaitContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/wait")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("WaitContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestWaitContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.WaitContainer("a2334") - expected := &NoSuchContainer{ID: "a2334"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("WaitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestCommitContainer(t *testing.T) { - response := `{"Id":"596069db4bf5"}` - client := newTestClient(&FakeRoundTripper{message: response, status: http.StatusOK}) - id := "596069db4bf5" - image, err := client.CommitContainer(CommitContainerOptions{}) - if err != nil { - t.Fatal(err) - } - if image.ID != id { - t.Errorf("CommitContainer: Wrong image id. Want %q. Got %q.", id, image.ID) - } -} - -func TestCommitContainerParams(t *testing.T) { - cfg := Config{Memory: 67108864} - json, _ := json.Marshal(&cfg) - var tests = []struct { - input CommitContainerOptions - params map[string][]string - body []byte - }{ - {CommitContainerOptions{}, map[string][]string{}, nil}, - {CommitContainerOptions{Container: "44c004db4b17"}, map[string][]string{"container": {"44c004db4b17"}}, nil}, - { - CommitContainerOptions{Container: "44c004db4b17", Repository: "tsuru/python", Message: "something"}, - map[string][]string{"container": {"44c004db4b17"}, "repo": {"tsuru/python"}, "m": {"something"}}, - nil, - }, - { - CommitContainerOptions{Container: "44c004db4b17", Run: &cfg}, - map[string][]string{"container": {"44c004db4b17"}}, - json, - }, - } - fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} - client := newTestClient(fakeRT) - u, _ := url.Parse(client.getURL("/commit")) - for _, tt := range tests { - if _, err := client.CommitContainer(tt.input); err != nil { - t.Error(err) - } - got := map[string][]string(fakeRT.requests[0].URL.Query()) - if !reflect.DeepEqual(got, tt.params) { - t.Errorf("Expected %#v, got %#v.", tt.params, got) - } - if path := fakeRT.requests[0].URL.Path; path != u.Path { - t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) - } - if meth := fakeRT.requests[0].Method; meth != "POST" { - t.Errorf("Wrong HTTP method. Want POST. Got %s.", meth) - } - if tt.body != nil { - if requestBody, err := ioutil.ReadAll(fakeRT.requests[0].Body); err == nil { - if bytes.Compare(requestBody, tt.body) != 0 { - t.Errorf("Expected body %#v, got %#v", tt.body, requestBody) - } - } else { - t.Errorf("Error reading request body: %#v", err) - } - } - fakeRT.Reset() - } -} - -func TestCommitContainerFailure(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusInternalServerError}) - _, err := client.CommitContainer(CommitContainerOptions{}) - if err == nil { - t.Error("Expected non-nil error, got .") - } -} - -func TestCommitContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.CommitContainer(CommitContainerOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("CommitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestAttachToContainerLogs(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 19}) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &buf, - Stdout: true, - Stderr: true, - Logs: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("AttachToContainer for logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "POST" { - t.Errorf("AttachToContainer: wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/attach")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "logs": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestAttachToContainer(t *testing.T) { - var reader = strings.NewReader("send value") - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } - expected := map[string][]string{ - "stdin": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "stream": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestAttachToContainerSentinel(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - success := make(chan struct{}) - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - Success: success, - } - go func() { - if err := client.AttachToContainer(opts); err != nil { - t.Error(err) - } - }() - success <- <-success -} - -func TestAttachToContainerNilStdout(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: nil, - ErrorStream: &stderr, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestAttachToContainerNilStderr(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - InputStream: reader, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: true, - } - err := client.AttachToContainer(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestAttachToContainerRawTerminalFalse(t *testing.T) { - input := strings.NewReader("send value") - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - req = *r - w.WriteHeader(http.StatusOK) - hj, ok := w.(http.Hijacker) - if !ok { - t.Fatal("cannot hijack server connection") - } - conn, _, err := hj.Hijack() - if err != nil { - t.Fatal(err) - } - conn.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - conn.Write([]byte("hello")) - conn.Write([]byte{2, 0, 0, 0, 0, 0, 0, 6}) - conn.Write([]byte("hello!")) - conn.Close() - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - opts := AttachToContainerOptions{ - Container: "a123456", - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: input, - Stdin: true, - Stdout: true, - Stderr: true, - Stream: true, - RawTerminal: false, - } - client.AttachToContainer(opts) - expected := map[string][]string{ - "stdin": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "stream": {"1"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) - } - if stdout.String() != "hello" { - t.Errorf("AttachToContainer: wrong content written to stdout. Want %q. Got %q.", "hello", stdout.String()) - } - if stderr.String() != "hello!" { - t.Errorf("AttachToContainer: wrong content written to stderr. Want %q. Got %q.", "hello!", stderr.String()) - } -} - -func TestAttachToContainerWithoutContainer(t *testing.T) { - var client Client - err := client.AttachToContainer(AttachToContainerOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) - } -} - -func TestLogs(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "GET" { - t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/logs")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "follow": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "timestamps": {"1"}, - "tail": {"all"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestLogsNilStdoutDoesntFail(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - opts := LogsOptions{ - Container: "a123456", - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestLogsNilStderrDoesntFail(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{2, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - opts := LogsOptions{ - Container: "a123456", - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } -} - -func TestLogsSpecifyingTail(t *testing.T) { - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} - w.Write(prefix) - w.Write([]byte("something happened!")) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - Stdout: true, - Stderr: true, - Timestamps: true, - Tail: "100", - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } - if req.Method != "GET" { - t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/a123456/logs")) - if req.URL.Path != u.Path { - t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQs := map[string][]string{ - "follow": {"1"}, - "stdout": {"1"}, - "stderr": {"1"}, - "timestamps": {"1"}, - "tail": {"100"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expectedQs) { - t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) - } -} - -func TestLogsRawTerminal(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("something happened!")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var buf bytes.Buffer - opts := LogsOptions{ - Container: "a123456", - OutputStream: &buf, - Follow: true, - RawTerminal: true, - Stdout: true, - Stderr: true, - Timestamps: true, - Tail: "100", - } - err := client.Logs(opts) - if err != nil { - t.Fatal(err) - } - expected := "something happened!" - if buf.String() != expected { - t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) - } -} - -func TestLogsNoContainer(t *testing.T) { - var client Client - err := client.Logs(LogsOptions{}) - expected := &NoSuchContainer{ID: ""} - if !reflect.DeepEqual(err, expected) { - t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) - } -} - -func TestNoSuchContainerError(t *testing.T) { - var err = &NoSuchContainer{ID: "i345"} - expected := "No such container: i345" - if got := err.Error(); got != expected { - t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) - } -} - -func TestNoSuchContainerErrorMessage(t *testing.T) { - var err = &NoSuchContainer{ID: "i345", Err: errors.New("some advanced error info")} - expected := "some advanced error info" - if got := err.Error(); got != expected { - t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) - } -} - -func TestExportContainer(t *testing.T) { - content := "exported container tar content" - out := stdoutMock{bytes.NewBufferString(content)} - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} - err := client.ExportContainer(opts) - if err != nil { - t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func TestExportContainerViaUnixSocket(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip(fmt.Sprintf("skipping test on %s", runtime.GOOS)) - } - content := "exported container tar content" - var buf []byte - out := bytes.NewBuffer(buf) - tempSocket := tempfile("export_socket") - defer os.Remove(tempSocket) - endpoint := "unix://" + tempSocket - u, _ := parseEndpoint(endpoint, false) - client := Client{ - HTTPClient: http.DefaultClient, - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - } - listening := make(chan string) - done := make(chan int) - go runStreamConnServer(t, "unix", tempSocket, listening, done) - <-listening // wait for server to start - opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} - err := client.ExportContainer(opts) - <-done // make sure server stopped - if err != nil { - t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func runStreamConnServer(t *testing.T, network, laddr string, listening chan<- string, done chan<- int) { - defer close(done) - l, err := net.Listen(network, laddr) - if err != nil { - t.Errorf("Listen(%q, %q) failed: %v", network, laddr, err) - listening <- "" - return - } - defer l.Close() - listening <- l.Addr().String() - c, err := l.Accept() - if err != nil { - t.Logf("Accept failed: %v", err) - return - } - c.Write([]byte("HTTP/1.1 200 OK\n\nexported container tar content")) - c.Close() -} - -func tempfile(filename string) string { - return os.TempDir() + "/" + filename + "." + strconv.Itoa(os.Getpid()) -} - -func TestExportContainerNoId(t *testing.T) { - client := Client{} - out := stdoutMock{bytes.NewBufferString("")} - err := client.ExportContainer(ExportContainerOptions{OutputStream: out}) - e, ok := err.(*NoSuchContainer) - if !ok { - t.Errorf("ExportContainer: wrong error. Want NoSuchContainer. Got %#v.", e) - } - if e.ID != "" { - t.Errorf("ExportContainer: wrong ID. Want %q. Got %q", "", e.ID) - } -} - -func TestUploadToContainer(t *testing.T) { - content := "File content" - in := stdinMock{bytes.NewBufferString(content)} - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - opts := UploadToContainerOptions{ - Path: "abc", - InputStream: in, - } - err := client.UploadToContainer("a123456", opts) - if err != nil { - t.Errorf("UploadToContainer: caught error %#v while uploading archive to container, expected nil", err) - } - - req := fakeRT.requests[0] - - if req.Method != "PUT" { - t.Errorf("UploadToContainer{Path:abc}: Wrong HTTP method. Want PUT. Got %s", req.Method) - } - - if pathParam := req.URL.Query().Get("path"); pathParam != "abc" { - t.Errorf("ListImages({Path:abc}): Wrong parameter. Want path=abc. Got path=%s", pathParam) - } - -} - -func TestDownloadFromContainer(t *testing.T) { - filecontent := "File content" - client := newTestClient(&FakeRoundTripper{message: filecontent, status: http.StatusOK}) - - var out bytes.Buffer - opts := DownloadFromContainerOptions{ - OutputStream: &out, - } - err := client.DownloadFromContainer("a123456", opts) - if err != nil { - t.Errorf("DownloadFromContainer: caught error %#v while downloading from container, expected nil", err.Error()) - } - if out.String() != filecontent { - t.Errorf("DownloadFromContainer: wrong stdout. Want %#v. Got %#v.", filecontent, out.String()) - } -} - -func TestCopyFromContainer(t *testing.T) { - content := "File content" - out := stdoutMock{bytes.NewBufferString(content)} - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - opts := CopyFromContainerOptions{ - Container: "a123456", - OutputStream: &out, - } - err := client.CopyFromContainer(opts) - if err != nil { - t.Errorf("CopyFromContainer: caught error %#v while copying from container, expected nil", err.Error()) - } - if out.String() != content { - t.Errorf("CopyFromContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) - } -} - -func TestCopyFromContainerEmptyContainer(t *testing.T) { - client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) - err := client.CopyFromContainer(CopyFromContainerOptions{}) - _, ok := err.(*NoSuchContainer) - if !ok { - t.Errorf("CopyFromContainer: invalid error returned. Want NoSuchContainer, got %#v.", err) - } -} - -func TestPassingNameOptToCreateContainerReturnsItInContainer(t *testing.T) { - jsonContainer := `{ - "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", - "Warnings": [] -}` - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := Config{AttachStdout: true, AttachStdin: true} - opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} - container, err := client.CreateContainer(opts) - if err != nil { - t.Fatal(err) - } - if container.Name != "TestCreateContainer" { - t.Errorf("Container name expected to be TestCreateContainer, was %s", container.Name) - } -} - -func TestAlwaysRestart(t *testing.T) { - policy := AlwaysRestart() - if policy.Name != "always" { - t.Errorf("AlwaysRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) - } - if policy.MaximumRetryCount != 0 { - t.Errorf("AlwaysRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) - } -} - -func TestRestartOnFailure(t *testing.T) { - const retry = 5 - policy := RestartOnFailure(retry) - if policy.Name != "on-failure" { - t.Errorf("RestartOnFailure(%d): wrong policy name. Want %q. Got %q", retry, "on-failure", policy.Name) - } - if policy.MaximumRetryCount != retry { - t.Errorf("RestartOnFailure(%d): wrong MaximumRetryCount. Want %d. Got %d", retry, retry, policy.MaximumRetryCount) - } -} - -func TestNeverRestart(t *testing.T) { - policy := NeverRestart() - if policy.Name != "no" { - t.Errorf("NeverRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) - } - if policy.MaximumRetryCount != 0 { - t.Errorf("NeverRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) - } -} - -func TestTopContainer(t *testing.T) { - jsonTop := `{ - "Processes": [ - [ - "ubuntu", - "3087", - "815", - "0", - "01:44", - "?", - "00:00:00", - "cmd1" - ], - [ - "root", - "3158", - "3087", - "0", - "01:44", - "?", - "00:00:01", - "cmd2" - ] - ], - "Titles": [ - "UID", - "PID", - "PPID", - "C", - "STIME", - "TTY", - "TIME", - "CMD" - ] -}` - var expected TopResult - err := json.Unmarshal([]byte(jsonTop), &expected) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0" - fakeRT := &FakeRoundTripper{message: jsonTop, status: http.StatusOK} - client := newTestClient(fakeRT) - processes, err := client.TopContainer(id, "") - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(processes, expected) { - t.Errorf("TopContainer: Expected %#v. Got %#v.", expected, processes) - } - if len(processes.Processes) != 2 || len(processes.Processes[0]) != 8 || - processes.Processes[0][7] != "cmd1" { - t.Errorf("TopContainer: Process list to include cmd1. Got %#v.", processes) - } - expectedURI := "/containers/" + id + "/top" - if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { - t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) - } -} - -func TestTopContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - _, err := client.TopContainer("abef348", "") - expected := &NoSuchContainer{ID: "abef348"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestTopContainerWithPsArgs(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "no such container", status: http.StatusNotFound} - client := newTestClient(fakeRT) - expectedErr := &NoSuchContainer{ID: "abef348"} - if _, err := client.TopContainer("abef348", "aux"); !reflect.DeepEqual(expectedErr, err) { - t.Errorf("TopContainer: Expected %v. Got %v.", expectedErr, err) - } - expectedURI := "/containers/abef348/top?ps_args=aux" - if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { - t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) - } -} - -func TestStatsTimeout(t *testing.T) { - l, err := net.Listen("unix", "/tmp/docker_test.sock") - if err != nil { - t.Fatal(err) - } - received := false - defer l.Close() - go func() { - l.Accept() - received = true - time.Sleep(time.Second) - }() - client, _ := NewClient("unix:///tmp/docker_test.sock") - client.SkipServerVersionCheck = true - errC := make(chan error, 1) - statsC := make(chan *Stats) - done := make(chan bool) - go func() { - errC <- client.Stats(StatsOptions{"c", statsC, true, done, time.Millisecond * 100}) - close(errC) - }() - err = <-errC - e, ok := err.(net.Error) - if !ok || !e.Timeout() { - t.Error("Failed to receive timeout exception") - } - if !received { - t.Fatal("Failed to receive message") - } -} - -func TestStats(t *testing.T) { - jsonStats1 := `{ - "read" : "2015-01-08T22:57:31.547920715Z", - "network" : { - "rx_dropped" : 0, - "rx_bytes" : 648, - "rx_errors" : 0, - "tx_packets" : 8, - "tx_dropped" : 0, - "rx_packets" : 8, - "tx_errors" : 0, - "tx_bytes" : 648 - }, - "memory_stats" : { - "stats" : { - "total_pgmajfault" : 0, - "cache" : 0, - "mapped_file" : 0, - "total_inactive_file" : 0, - "pgpgout" : 414, - "rss" : 6537216, - "total_mapped_file" : 0, - "writeback" : 0, - "unevictable" : 0, - "pgpgin" : 477, - "total_unevictable" : 0, - "pgmajfault" : 0, - "total_rss" : 6537216, - "total_rss_huge" : 6291456, - "total_writeback" : 0, - "total_inactive_anon" : 0, - "rss_huge" : 6291456, - "hierarchical_memory_limit": 189204833, - "total_pgfault" : 964, - "total_active_file" : 0, - "active_anon" : 6537216, - "total_active_anon" : 6537216, - "total_pgpgout" : 414, - "total_cache" : 0, - "inactive_anon" : 0, - "active_file" : 0, - "pgfault" : 964, - "inactive_file" : 0, - "total_pgpgin" : 477 - }, - "max_usage" : 6651904, - "usage" : 6537216, - "failcnt" : 0, - "limit" : 67108864 - }, - "blkio_stats": { - "io_service_bytes_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 428795731968 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 388177920 - } - ], - "io_serviced_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 25994442 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 1734 - } - ], - "io_queue_recursive": [], - "io_service_time_recursive": [], - "io_wait_time_recursive": [], - "io_merged_recursive": [], - "io_time_recursive": [], - "sectors_recursive": [] - }, - "cpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - }, - "precpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - } - }` - // 1 second later, cache is 100 - jsonStats2 := `{ - "read" : "2015-01-08T22:57:32.547920715Z", - "network" : { - "rx_dropped" : 0, - "rx_bytes" : 648, - "rx_errors" : 0, - "tx_packets" : 8, - "tx_dropped" : 0, - "rx_packets" : 8, - "tx_errors" : 0, - "tx_bytes" : 648 - }, - "memory_stats" : { - "stats" : { - "total_pgmajfault" : 0, - "cache" : 100, - "mapped_file" : 0, - "total_inactive_file" : 0, - "pgpgout" : 414, - "rss" : 6537216, - "total_mapped_file" : 0, - "writeback" : 0, - "unevictable" : 0, - "pgpgin" : 477, - "total_unevictable" : 0, - "pgmajfault" : 0, - "total_rss" : 6537216, - "total_rss_huge" : 6291456, - "total_writeback" : 0, - "total_inactive_anon" : 0, - "rss_huge" : 6291456, - "total_pgfault" : 964, - "total_active_file" : 0, - "active_anon" : 6537216, - "total_active_anon" : 6537216, - "total_pgpgout" : 414, - "total_cache" : 0, - "inactive_anon" : 0, - "active_file" : 0, - "pgfault" : 964, - "inactive_file" : 0, - "total_pgpgin" : 477 - }, - "max_usage" : 6651904, - "usage" : 6537216, - "failcnt" : 0, - "limit" : 67108864 - }, - "blkio_stats": { - "io_service_bytes_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 428795731968 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 388177920 - } - ], - "io_serviced_recursive": [ - { - "major": 8, - "minor": 0, - "op": "Read", - "value": 25994442 - }, - { - "major": 8, - "minor": 0, - "op": "Write", - "value": 1734 - } - ], - "io_queue_recursive": [], - "io_service_time_recursive": [], - "io_wait_time_recursive": [], - "io_merged_recursive": [], - "io_time_recursive": [], - "sectors_recursive": [] - }, - "cpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - }, - "precpu_stats" : { - "cpu_usage" : { - "percpu_usage" : [ - 16970827, - 1839451, - 7107380, - 10571290 - ], - "usage_in_usermode" : 10000000, - "total_usage" : 36488948, - "usage_in_kernelmode" : 20000000 - }, - "system_cpu_usage" : 20091722000000000 - } - }` - var expected1 Stats - var expected2 Stats - err := json.Unmarshal([]byte(jsonStats1), &expected1) - if err != nil { - t.Fatal(err) - } - err = json.Unmarshal([]byte(jsonStats2), &expected2) - if err != nil { - t.Fatal(err) - } - id := "4fa6e0f0" - - var req http.Request - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(jsonStats1)) - w.Write([]byte(jsonStats2)) - req = *r - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - errC := make(chan error, 1) - statsC := make(chan *Stats) - done := make(chan bool) - go func() { - errC <- client.Stats(StatsOptions{id, statsC, true, done, 0}) - close(errC) - }() - var resultStats []*Stats - for { - stats, ok := <-statsC - if !ok { - break - } - resultStats = append(resultStats, stats) - } - err = <-errC - if err != nil { - t.Fatal(err) - } - if len(resultStats) != 2 { - t.Fatalf("Stats: Expected 2 results. Got %d.", len(resultStats)) - } - if !reflect.DeepEqual(resultStats[0], &expected1) { - t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected1, resultStats[0]) - } - if !reflect.DeepEqual(resultStats[1], &expected2) { - t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected2, resultStats[1]) - } - if req.Method != "GET" { - t.Errorf("Stats: wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/containers/" + id + "/stats")) - if req.URL.Path != u.Path { - t.Errorf("Stats: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestStatsContainerNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) - statsC := make(chan *Stats) - done := make(chan bool) - err := client.Stats(StatsOptions{"abef348", statsC, true, done, 0}) - expected := &NoSuchContainer{ID: "abef348"} - if !reflect.DeepEqual(err, expected) { - t.Errorf("Stats: Wrong error returned. Want %#v. Got %#v.", expected, err) - } -} - -func TestRenameContainer(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := RenameContainerOptions{ID: "something_old", Name: "something_new"} - err := client.RenameContainer(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("RenameContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/something_old/rename?name=something_new")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("RenameContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - expectedValues := expectedURL.Query()["name"] - actualValues := req.URL.Query()["name"] - if len(actualValues) != 1 || expectedValues[0] != actualValues[0] { - t.Errorf("RenameContainer: Wrong params in request. Want %q. Got %q.", expectedValues, actualValues) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go deleted file mode 100644 index df5169d06ba..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/env_test.go +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright 2014 go-dockerclient authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the DOCKER-LICENSE file. - -package docker - -import ( - "bytes" - "errors" - "reflect" - "sort" - "testing" -) - -func TestGet(t *testing.T) { - var tests = []struct { - input []string - query string - expected string - }{ - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PATH", "/usr/bin:/bin"}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", "/usr/local"}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", ""}, - {[]string{"WAT="}, "WAT", ""}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Get(tt.query) - if got != tt.expected { - t.Errorf("Env.Get(%q): wrong result. Want %q. Got %q", tt.query, tt.expected, got) - } - } -} - -func TestExists(t *testing.T) { - var tests = []struct { - input []string - query string - expected bool - }{ - {[]string{"WAT=", "PYTHONPATH=/usr/local"}, "WAT", true}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", true}, - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", false}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Exists(tt.query) - if got != tt.expected { - t.Errorf("Env.Exists(%q): wrong result. Want %v. Got %v", tt.query, tt.expected, got) - } - } -} - -func TestGetBool(t *testing.T) { - var tests = []struct { - input string - expected bool - }{ - {"EMTPY_VAR", false}, {"ZERO_VAR", false}, {"NO_VAR", false}, - {"FALSE_VAR", false}, {"NONE_VAR", false}, {"TRUE_VAR", true}, - {"WAT", true}, {"PATH", true}, {"ONE_VAR", true}, {"NO_VAR_TAB", false}, - } - env := Env([]string{ - "EMPTY_VAR=", "ZERO_VAR=0", "NO_VAR=no", "FALSE_VAR=false", - "NONE_VAR=none", "TRUE_VAR=true", "WAT=wat", "PATH=/usr/bin:/bin", - "ONE_VAR=1", "NO_VAR_TAB=0 \t\t\t", - }) - for _, tt := range tests { - got := env.GetBool(tt.input) - if got != tt.expected { - t.Errorf("Env.GetBool(%q): wrong result. Want %v. Got %v.", tt.input, tt.expected, got) - } - } -} - -func TestSetBool(t *testing.T) { - var tests = []struct { - input bool - expected string - }{ - {true, "1"}, {false, "0"}, - } - for _, tt := range tests { - var env Env - env.SetBool("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetInt(t *testing.T) { - var tests = []struct { - input string - expected int - }{ - {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, - } - env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) - for _, tt := range tests { - got := env.GetInt(tt.input) - if got != tt.expected { - t.Errorf("Env.GetInt(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) - } - } -} - -func TestSetInt(t *testing.T) { - var tests = []struct { - input int - expected string - }{ - {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, - {0, "0"}, {-34, "-34"}, - } - for _, tt := range tests { - var env Env - env.SetInt("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetInt64(t *testing.T) { - var tests = []struct { - input string - expected int64 - }{ - {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, - } - env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) - for _, tt := range tests { - got := env.GetInt64(tt.input) - if got != tt.expected { - t.Errorf("Env.GetInt64(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) - } - } -} - -func TestSetInt64(t *testing.T) { - var tests = []struct { - input int64 - expected string - }{ - {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, - {0, "0"}, {-34, "-34"}, - } - for _, tt := range tests { - var env Env - env.SetInt64("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestGetJSON(t *testing.T) { - var p struct { - Name string `json:"name"` - Age int `json:"age"` - } - var env Env - env.Set("person", `{"name":"Gopher","age":5}`) - err := env.GetJSON("person", &p) - if err != nil { - t.Error(err) - } - if p.Name != "Gopher" { - t.Errorf("Env.GetJSON(%q): wrong name. Want %q. Got %q", "person", "Gopher", p.Name) - } - if p.Age != 5 { - t.Errorf("Env.GetJSON(%q): wrong age. Want %d. Got %d", "person", 5, p.Age) - } -} - -func TestGetJSONAbsent(t *testing.T) { - var l []string - var env Env - err := env.GetJSON("person", &l) - if err != nil { - t.Error(err) - } - if l != nil { - t.Errorf("Env.GetJSON(): get unexpected list %v", l) - } -} - -func TestGetJSONFailure(t *testing.T) { - var p []string - var env Env - env.Set("list-person", `{"name":"Gopher","age":5}`) - err := env.GetJSON("list-person", &p) - if err == nil { - t.Errorf("Env.GetJSON(%q): got unexpected error.", "list-person") - } -} - -func TestSetJSON(t *testing.T) { - var p1 = struct { - Name string `json:"name"` - Age int `json:"age"` - }{Name: "Gopher", Age: 5} - var env Env - err := env.SetJSON("person", p1) - if err != nil { - t.Error(err) - } - var p2 struct { - Name string `json:"name"` - Age int `json:"age"` - } - err = env.GetJSON("person", &p2) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(p1, p2) { - t.Errorf("Env.SetJSON(%q): wrong result. Want %v. Got %v", "person", p1, p2) - } -} - -func TestSetJSONFailure(t *testing.T) { - var env Env - err := env.SetJSON("person", unmarshable{}) - if err == nil { - t.Error("Env.SetJSON(): got unexpected error") - } - if env.Exists("person") { - t.Errorf("Env.SetJSON(): should not define the key %q, but did", "person") - } -} - -func TestGetList(t *testing.T) { - var tests = []struct { - input string - expected []string - }{ - {"WAT=wat", []string{"wat"}}, - {`WAT=["wat","wet","wit","wot","wut"]`, []string{"wat", "wet", "wit", "wot", "wut"}}, - {"WAT=", nil}, - } - for _, tt := range tests { - env := Env([]string{tt.input}) - got := env.GetList("WAT") - if !reflect.DeepEqual(got, tt.expected) { - t.Errorf("Env.GetList(%q): wrong result. Want %v. Got %v", "WAT", tt.expected, got) - } - } -} - -func TestSetList(t *testing.T) { - list := []string{"a", "b", "c"} - var env Env - if err := env.SetList("SOME", list); err != nil { - t.Error(err) - } - if got := env.GetList("SOME"); !reflect.DeepEqual(got, list) { - t.Errorf("Env.SetList(%v): wrong result. Got %v", list, got) - } -} - -func TestSet(t *testing.T) { - var env Env - env.Set("PATH", "/home/bin:/bin") - env.Set("SOMETHING", "/usr/bin") - env.Set("PATH", "/bin") - if expected, got := "/usr/bin", env.Get("SOMETHING"); got != expected { - t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) - } - if expected, got := "/bin", env.Get("PATH"); got != expected { - t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) - } -} - -func TestDecode(t *testing.T) { - var tests = []struct { - input string - expectedOut []string - expectedErr string - }{ - { - `{"PATH":"/usr/bin:/bin","containers":54,"wat":["123","345"]}`, - []string{"PATH=/usr/bin:/bin", "containers=54", `wat=["123","345"]`}, - "", - }, - {"}}", nil, "invalid character '}' looking for beginning of value"}, - {`{}`, nil, ""}, - } - for _, tt := range tests { - var env Env - err := env.Decode(bytes.NewBufferString(tt.input)) - if tt.expectedErr == "" { - if err != nil { - t.Error(err) - } - } else if tt.expectedErr != err.Error() { - t.Errorf("Env.Decode(): invalid error. Want %q. Got %q.", tt.expectedErr, err) - } - got := []string(env) - sort.Strings(got) - sort.Strings(tt.expectedOut) - if !reflect.DeepEqual(got, tt.expectedOut) { - t.Errorf("Env.Decode(): wrong result. Want %v. Got %v.", tt.expectedOut, got) - } - } -} - -func TestSetAuto(t *testing.T) { - buf := bytes.NewBufferString("oi") - var tests = []struct { - input interface{} - expected string - }{ - {10, "10"}, - {10.3, "10"}, - {"oi", "oi"}, - {buf, "{}"}, - {unmarshable{}, "{}"}, - } - for _, tt := range tests { - var env Env - env.SetAuto("SOME", tt.input) - if got := env.Get("SOME"); got != tt.expected { - t.Errorf("Env.SetAuto(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) - } - } -} - -func TestMap(t *testing.T) { - var tests = []struct { - input []string - expected map[string]string - }{ - {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, map[string]string{"PATH": "/usr/bin:/bin", "PYTHONPATH": "/usr/local"}}, - {nil, nil}, - } - for _, tt := range tests { - env := Env(tt.input) - got := env.Map() - if !reflect.DeepEqual(got, tt.expected) { - t.Errorf("Env.Map(): wrong result. Want %v. Got %v", tt.expected, got) - } - } -} - -type unmarshable struct { -} - -func (unmarshable) MarshalJSON() ([]byte, error) { - return nil, errors.New("cannot marshal") -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go deleted file mode 100644 index a308538ccd5..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/event_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2014 go-dockerclient 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 docker - -import ( - "bufio" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" -) - -func TestEventListeners(t *testing.T) { - testEventListeners("TestEventListeners", t, httptest.NewServer, NewClient) -} - -func TestTLSEventListeners(t *testing.T) { - testEventListeners("TestTLSEventListeners", t, func(handler http.Handler) *httptest.Server { - server := httptest.NewUnstartedServer(handler) - - cert, err := tls.LoadX509KeyPair("testing/data/server.pem", "testing/data/serverkey.pem") - if err != nil { - t.Fatalf("Error loading server key pair: %s", err) - } - - caCert, err := ioutil.ReadFile("testing/data/ca.pem") - if err != nil { - t.Fatalf("Error loading ca certificate: %s", err) - } - caPool := x509.NewCertPool() - if !caPool.AppendCertsFromPEM(caCert) { - t.Fatalf("Could not add ca certificate") - } - - server.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: caPool, - } - server.StartTLS() - return server - }, func(url string) (*Client, error) { - return NewTLSClient(url, "testing/data/cert.pem", "testing/data/key.pem", "testing/data/ca.pem") - }) -} - -func testEventListeners(testName string, t *testing.T, buildServer func(http.Handler) *httptest.Server, buildClient func(string) (*Client, error)) { - response := `{"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924} -{"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924} -{"status":"stop","id":"dfdf82bd3881","from":"base:latest","time":1374067966} -{"status":"destroy","id":"dfdf82bd3881","from":"base:latest","time":1374067970} -` - - server := buildServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rsc := bufio.NewScanner(strings.NewReader(response)) - for rsc.Scan() { - w.Write([]byte(rsc.Text())) - w.(http.Flusher).Flush() - time.Sleep(10 * time.Millisecond) - } - })) - defer server.Close() - - client, err := buildClient(server.URL) - if err != nil { - t.Errorf("Failed to create client: %s", err) - } - client.SkipServerVersionCheck = true - - listener := make(chan *APIEvents, 10) - defer func() { - time.Sleep(10 * time.Millisecond) - if err := client.RemoveEventListener(listener); err != nil { - t.Error(err) - } - }() - - err = client.AddEventListener(listener) - if err != nil { - t.Errorf("Failed to add event listener: %s", err) - } - - timeout := time.After(1 * time.Second) - var count int - - for { - select { - case msg := <-listener: - t.Logf("Received: %v", *msg) - count++ - err = checkEvent(count, msg) - if err != nil { - t.Fatalf("Check event failed: %s", err) - } - if count == 4 { - return - } - case <-timeout: - t.Fatalf("%s timed out waiting on events", testName) - } - } -} - -func checkEvent(index int, event *APIEvents) error { - if event.ID != "dfdf82bd3881" { - return fmt.Errorf("event ID did not match. Expected dfdf82bd3881 got %s", event.ID) - } - if event.From != "base:latest" { - return fmt.Errorf("event from did not match. Expected base:latest got %s", event.From) - } - var status string - switch index { - case 1: - status = "create" - case 2: - status = "start" - case 3: - status = "stop" - case 4: - status = "destroy" - } - if event.Status != status { - return fmt.Errorf("event status did not match. Expected %s got %s", status, event.Status) - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go deleted file mode 100644 index 8c2c719e6e8..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/example_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2014 go-dockerclient 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 docker_test - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "log" - "time" - - "github.com/fsouza/go-dockerclient" -) - -func ExampleClient_AttachToContainer() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - client.SkipServerVersionCheck = true - // Reading logs from container a84849 and sending them to buf. - var buf bytes.Buffer - err = client.AttachToContainer(docker.AttachToContainerOptions{ - Container: "a84849", - OutputStream: &buf, - Logs: true, - Stdout: true, - Stderr: true, - }) - if err != nil { - log.Fatal(err) - } - log.Println(buf.String()) - buf.Reset() - err = client.AttachToContainer(docker.AttachToContainerOptions{ - Container: "a84849", - OutputStream: &buf, - Stdout: true, - Stream: true, - }) - if err != nil { - log.Fatal(err) - } - log.Println(buf.String()) -} - -func ExampleClient_CopyFromContainer() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - cid := "a84849" - var buf bytes.Buffer - filename := "/tmp/output.txt" - err = client.CopyFromContainer(docker.CopyFromContainerOptions{ - Container: cid, - Resource: filename, - OutputStream: &buf, - }) - if err != nil { - log.Fatalf("Error while copying from %s: %s\n", cid, err) - } - content := new(bytes.Buffer) - r := bytes.NewReader(buf.Bytes()) - tr := tar.NewReader(r) - tr.Next() - if err != nil && err != io.EOF { - log.Fatal(err) - } - if _, err := io.Copy(content, tr); err != nil { - log.Fatal(err) - } - log.Println(buf.String()) -} - -func ExampleClient_BuildImage() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - - t := time.Now() - inputbuf, outputbuf := bytes.NewBuffer(nil), bytes.NewBuffer(nil) - tr := tar.NewWriter(inputbuf) - tr.WriteHeader(&tar.Header{Name: "Dockerfile", Size: 10, ModTime: t, AccessTime: t, ChangeTime: t}) - tr.Write([]byte("FROM base\n")) - tr.Close() - opts := docker.BuildImageOptions{ - Name: "test", - InputStream: inputbuf, - OutputStream: outputbuf, - } - if err := client.BuildImage(opts); err != nil { - log.Fatal(err) - } -} - -func ExampleClient_ListenEvents() { - client, err := docker.NewClient("http://localhost:4243") - if err != nil { - log.Fatal(err) - } - - listener := make(chan *docker.APIEvents) - err = client.AddEventListener(listener) - if err != nil { - log.Fatal(err) - } - - defer func() { - - err = client.RemoveEventListener(listener) - if err != nil { - log.Fatal(err) - } - - }() - - timeout := time.After(1 * time.Second) - - for { - select { - case msg := <-listener: - log.Println(msg) - case <-timeout: - break - } - } - -} - -func ExampleEnv_Map() { - e := docker.Env([]string{"A=1", "B=2", "C=3"}) - envs := e.Map() - for k, v := range envs { - fmt.Printf("%s=%q\n", k, v) - } -} - -func ExampleEnv_SetJSON() { - type Person struct { - Name string - Age int - } - p := Person{Name: "Gopher", Age: 4} - var e docker.Env - err := e.SetJSON("person", p) - if err != nil { - log.Fatal(err) - } -} - -func ExampleEnv_GetJSON() { - type Person struct { - Name string - Age int - } - p := Person{Name: "Gopher", Age: 4} - var e docker.Env - e.Set("person", `{"name":"Gopher","age":4}`) - err := e.GetJSON("person", &p) - if err != nil { - log.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go deleted file mode 100644 index 2dc8d2100c6..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/exec_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strings" - "testing" -) - -func TestExecCreate(t *testing.T) { - jsonContainer := `{"Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2"}` - var expected struct{ ID string } - err := json.Unmarshal([]byte(jsonContainer), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} - client := newTestClient(fakeRT) - config := CreateExecOptions{ - Container: "test", - AttachStdin: true, - AttachStdout: true, - AttachStderr: false, - Tty: false, - Cmd: []string{"touch", "/tmp/file"}, - User: "a-user", - } - execObj, err := client.CreateExec(config) - if err != nil { - t.Fatal(err) - } - expectedID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - if execObj.ID != expectedID { - t.Errorf("ExecCreate: wrong ID. Want %q. Got %q.", expectedID, execObj.ID) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecCreate: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/containers/test/exec")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - var gotBody struct{ ID string } - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } -} - -func TestExecStartDetached(t *testing.T) { - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - config := StartExecOptions{ - Detach: true, - } - err := client.StartExec(execID, config) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/start")) - if gotPath := req.URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } - t.Log(req.Body) - var gotBody struct{ Detach bool } - err = json.NewDecoder(req.Body).Decode(&gotBody) - if err != nil { - t.Fatal(err) - } - if !gotBody.Detach { - t.Fatal("Expected Detach in StartExecOptions to be true") - } -} - -func TestExecStartAndAttach(t *testing.T) { - var reader = strings.NewReader("send value") - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) - w.Write([]byte("hello")) - })) - defer server.Close() - client, _ := NewClient(server.URL) - client.SkipServerVersionCheck = true - var stdout, stderr bytes.Buffer - success := make(chan struct{}) - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - opts := StartExecOptions{ - OutputStream: &stdout, - ErrorStream: &stderr, - InputStream: reader, - RawTerminal: true, - Success: success, - } - go func() { - if err := client.StartExec(execID, opts); err != nil { - t.Error(err) - } - }() - <-success -} - -func TestExecResize(t *testing.T) { - execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" - fakeRT := &FakeRoundTripper{status: http.StatusOK} - client := newTestClient(fakeRT) - err := client.ResizeExecTTY(execID, 10, 20) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/resize?h=10&w=20")) - if gotPath := req.URL.RequestURI(); gotPath != expectedURL.RequestURI() { - t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } -} - -func TestExecInspect(t *testing.T) { - jsonExec := `{ - "ID": "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e", - "Running": true, - "ExitCode": 0, - "ProcessConfig": { - "privileged": false, - "user": "", - "tty": true, - "entrypoint": "bash", - "arguments": [] - }, - "OpenStdin": true, - "OpenStderr": true, - "OpenStdout": true, - "Container": { - "State": { - "Running": true, - "Paused": false, - "Restarting": false, - "OOMKilled": false, - "Pid": 29392, - "ExitCode": 0, - "Error": "", - "StartedAt": "2015-01-21T17:08:59.634662178Z", - "FinishedAt": "0001-01-01T00:00:00Z" - }, - "ID": "922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521", - "Created": "2015-01-21T17:08:59.46407212Z", - "Path": "/bin/bash", - "Args": [ - "-lc", - "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" - ], - "Config": { - "Hostname": "922cd0568714", - "Domainname": "", - "User": "ubuntu", - "Memory": 0, - "MemorySwap": 0, - "CpuShares": 100, - "Cpuset": "", - "AttachStdin": false, - "AttachStdout": false, - "AttachStderr": false, - "PortSpecs": null, - "ExposedPorts": { - "8888/tcp": {} - }, - "Tty": false, - "OpenStdin": false, - "StdinOnce": false, - "Env": [ - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - ], - "Cmd": [ - "/bin/bash", - "-lc", - "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" - ], - "Image": "tsuru/app-gtest", - "Volumes": null, - "WorkingDir": "", - "Entrypoint": null, - "NetworkDisabled": false, - "MacAddress": "", - "OnBuild": null - }, - "Image": "a88060b8b54fde0f7168c86742d0ce83b80f3f10925d85c98fdad9ed00bef544", - "NetworkSettings": { - "IPAddress": "172.17.0.8", - "IPPrefixLen": 16, - "MacAddress": "02:42:ac:11:00:08", - "LinkLocalIPv6Address": "fe80::42:acff:fe11:8", - "LinkLocalIPv6PrefixLen": 64, - "GlobalIPv6Address": "", - "GlobalIPv6PrefixLen": 0, - "Gateway": "172.17.42.1", - "IPv6Gateway": "", - "Bridge": "docker0", - "PortMapping": null, - "Ports": { - "8888/tcp": [ - { - "HostIp": "0.0.0.0", - "HostPort": "49156" - } - ] - } - }, - "ResolvConfPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/resolv.conf", - "HostnamePath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hostname", - "HostsPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hosts", - "Name": "/c7e43b72288ee9d0270a", - "Driver": "aufs", - "ExecDriver": "native-0.2", - "MountLabel": "", - "ProcessLabel": "", - "AppArmorProfile": "", - "RestartCount": 0, - "UpdateDns": false, - "Volumes": {}, - "VolumesRW": {} - } - }` - var expected ExecInspect - err := json.Unmarshal([]byte(jsonExec), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonExec, status: http.StatusOK} - client := newTestClient(fakeRT) - expectedID := "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e" - execObj, err := client.InspectExec(expectedID) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*execObj, expected) { - t.Errorf("ExecInspect: Expected %#v. Got %#v.", expected, *execObj) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExecInspect: wrong HTTP method. Want %q. Got %q.", "GET", req.Method) - } - expectedURL, _ := url.Parse(client.getURL("/exec/" + expectedID + "/json")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("ExecInspect: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go deleted file mode 100644 index cd90aa7dc64..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index c6d290c77f0..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package logrus - -import ( - "fmt" - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -var errorFields = Fields{ - "foo": fmt.Errorf("bar"), - "baz": fmt.Errorf("qux"), -} - -func BenchmarkErrorTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go deleted file mode 100644 index 938b9749564..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go deleted file mode 100644 index 1d70873254d..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package logrus - -import ( - "encoding/json" - "errors" - - "testing" -) - -func TestErrorNotLost(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["omg"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestFieldClashWithTime(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("time", "right now!")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.time"] != "right now!" { - t.Fatal("fields.time not set to original time field") - } - - if entry["time"] != "0001-01-01T00:00:00Z" { - t.Fatal("time field not set to current time, was: ", entry["time"]) - } -} - -func TestFieldClashWithMsg(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("msg", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.msg"] != "something" { - t.Fatal("fields.msg not set to original msg field") - } -} - -func TestFieldClashWithLevel(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.level"] != "something" { - t.Fatal("fields.level not set to original level field") - } -} - -func TestJSONEntryEndsWithNewline(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - if b[len(b)-1] != '\n' { - t.Fatal("Expected JSON log entry to end with a newline") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go deleted file mode 100644 index e8719b090db..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "sync" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} - -func TestGetSetLevelRace(t *testing.T) { - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i%2 == 0 { - SetLevel(InfoLevel) - } else { - GetLevel() - } - }(i) - - } - wg.Wait() -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index e25a44f67bf..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - "testing" - "time" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(false, "1234567890") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} - -func TestTimestampFormat(t *testing.T) { - checkTimeStr := func(format string) { - customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} - customStr, _ := customFormatter.Format(WithField("test", "test")) - timeStart := bytes.Index(customStr, ([]byte)("time=")) - timeEnd := bytes.Index(customStr, ([]byte)("level=")) - timeStr := customStr[timeStart+5 : timeEnd-1] - if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' { - timeStr = timeStr[1 : len(timeStr)-1] - } - if format == "" { - format = time.RFC3339 - } - _, e := time.Parse(format, (string)(timeStr)) - if e != nil { - t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) - } - } - - checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") - checkTimeStr("Mon Jan _2 15:04:05 2006") - checkTimeStr("") -} - -// TODO add tests for sorting etc., this requires a parser for the text -// formatter output. diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go deleted file mode 100644 index cd0ca8f3259..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package opts - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" -) - -func tmpFileWithContent(content string, t *testing.T) string { - tmpFile, err := ioutil.TempFile("", "envfile-test") - if err != nil { - t.Fatal(err) - } - defer tmpFile.Close() - - tmpFile.WriteString(content) - return tmpFile.Name() -} - -// Test ParseEnvFile for a file with a few well formatted lines -func TestParseEnvFileGoodFile(t *testing.T) { - content := `foo=bar - baz=quux -# comment - -_foobar=foobaz -` - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - lines, err := ParseEnvFile(tmpFile) - if err != nil { - t.Fatal(err) - } - - expectedLines := []string{ - "foo=bar", - "baz=quux", - "_foobar=foobaz", - } - - if !reflect.DeepEqual(lines, expectedLines) { - t.Fatal("lines not equal to expected_lines") - } -} - -// Test ParseEnvFile for an empty file -func TestParseEnvFileEmptyFile(t *testing.T) { - tmpFile := tmpFileWithContent("", t) - defer os.Remove(tmpFile) - - lines, err := ParseEnvFile(tmpFile) - if err != nil { - t.Fatal(err) - } - - if len(lines) != 0 { - t.Fatal("lines not empty; expected empty") - } -} - -// Test ParseEnvFile for a non existent file -func TestParseEnvFileNonExistentFile(t *testing.T) { - _, err := ParseEnvFile("foo_bar_baz") - if err == nil { - t.Fatal("ParseEnvFile succeeded; expected failure") - } - if _, ok := err.(*os.PathError); !ok { - t.Fatalf("Expected a PathError, got [%v]", err) - } -} - -// Test ParseEnvFile for a badly formatted file -func TestParseEnvFileBadlyFormattedFile(t *testing.T) { - content := `foo=bar - f =quux -` - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - if err == nil { - t.Fatalf("Expected a ErrBadEnvVariable, got nothing") - } - if _, ok := err.(ErrBadEnvVariable); !ok { - t.Fatalf("Expected a ErrBadEnvVariable, got [%v]", err) - } - expectedMessage := "poorly formatted environment: variable 'f ' is not a valid environment variable" - if err.Error() != expectedMessage { - t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) - } -} - -// Test ParseEnvFile for a file with a line exeeding bufio.MaxScanTokenSize -func TestParseEnvFileLineTooLongFile(t *testing.T) { - content := strings.Repeat("a", bufio.MaxScanTokenSize+42) - content = fmt.Sprint("foo=", content) - - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - if err == nil { - t.Fatal("ParseEnvFile succeeded; expected failure") - } -} - -// ParseEnvFile with a random file, pass through -func TestParseEnvFileRandomFile(t *testing.T) { - content := `first line -another invalid line` - tmpFile := tmpFileWithContent(content, t) - defer os.Remove(tmpFile) - - _, err := ParseEnvFile(tmpFile) - - if err == nil { - t.Fatalf("Expected a ErrBadEnvVariable, got nothing") - } - if _, ok := err.(ErrBadEnvVariable); !ok { - t.Fatalf("Expected a ErrBadEnvvariable, got [%v]", err) - } - expectedMessage := "poorly formatted environment: variable 'first line' is not a valid environment variable" - if err.Error() != expectedMessage { - t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go deleted file mode 100644 index b6b526a578b..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package opts - -import ( - "net" - "testing" -) - -func TestIpOptString(t *testing.T) { - addresses := []string{"", "0.0.0.0"} - var ip net.IP - - for _, address := range addresses { - stringAddress := NewIpOpt(&ip, address).String() - if stringAddress != address { - t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress) - } - } -} - -func TestNewIpOptInvalidDefaultVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - defaultVal := "Not an ip" - - ipOpt := NewIpOpt(&ip, defaultVal) - - expected := "127.0.0.1" - if ipOpt.String() != expected { - t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) - } -} - -func TestNewIpOptValidDefaultVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - defaultVal := "192.168.1.1" - - ipOpt := NewIpOpt(&ip, defaultVal) - - expected := "192.168.1.1" - if ipOpt.String() != expected { - t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) - } -} - -func TestIpOptSetInvalidVal(t *testing.T) { - ip := net.IPv4(127, 0, 0, 1) - ipOpt := &IpOpt{IP: &ip} - - invalidIp := "invalid ip" - expectedError := "invalid ip is not an ip address" - err := ipOpt.Set(invalidIp) - if err == nil || err.Error() != expectedError { - t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error()) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go deleted file mode 100644 index f08df30be63..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go +++ /dev/null @@ -1,479 +0,0 @@ -package opts - -import ( - "fmt" - "os" - "strings" - "testing" -) - -func TestValidateIPAddress(t *testing.T) { - if ret, err := ValidateIPAddress(`1.2.3.4`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`1.2.3.4`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`127.0.0.1`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`127.0.0.1`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`::1`); err != nil || ret == "" { - t.Fatalf("ValidateIPAddress(`::1`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`127`); err == nil || ret != "" { - t.Fatalf("ValidateIPAddress(`127`) got %s %s", ret, err) - } - - if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" { - t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) - } - -} - -func TestMapOpts(t *testing.T) { - tmpMap := make(map[string]string) - o := NewMapOpts(tmpMap, logOptsValidator) - o.Set("max-size=1") - if o.String() != "map[max-size:1]" { - t.Errorf("%s != [map[max-size:1]", o.String()) - } - - o.Set("max-file=2") - if len(tmpMap) != 2 { - t.Errorf("map length %d != 2", len(tmpMap)) - } - - if tmpMap["max-file"] != "2" { - t.Errorf("max-file = %s != 2", tmpMap["max-file"]) - } - - if tmpMap["max-size"] != "1" { - t.Errorf("max-size = %s != 1", tmpMap["max-size"]) - } - if o.Set("dummy-val=3") == nil { - t.Errorf("validator is not being called") - } -} - -func TestValidateMACAddress(t *testing.T) { - if _, err := ValidateMACAddress(`92:d0:c6:0a:29:33`); err != nil { - t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:29:33`) got %s", err) - } - - if _, err := ValidateMACAddress(`92:d0:c6:0a:33`); err == nil { - t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:33`) succeeded; expected failure on invalid MAC") - } - - if _, err := ValidateMACAddress(`random invalid string`); err == nil { - t.Fatalf("ValidateMACAddress(`random invalid string`) succeeded; expected failure on invalid MAC") - } -} - -func TestListOptsWithoutValidator(t *testing.T) { - o := NewListOpts(nil) - o.Set("foo") - if o.String() != "[foo]" { - t.Errorf("%s != [foo]", o.String()) - } - o.Set("bar") - if o.Len() != 2 { - t.Errorf("%d != 2", o.Len()) - } - o.Set("bar") - if o.Len() != 3 { - t.Errorf("%d != 3", o.Len()) - } - if !o.Get("bar") { - t.Error("o.Get(\"bar\") == false") - } - if o.Get("baz") { - t.Error("o.Get(\"baz\") == true") - } - o.Delete("foo") - if o.String() != "[bar bar]" { - t.Errorf("%s != [bar bar]", o.String()) - } - listOpts := o.GetAll() - if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" { - t.Errorf("Expected [[bar bar]], got [%v]", listOpts) - } - mapListOpts := o.GetMap() - if len(mapListOpts) != 1 { - t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) - } - -} - -func TestListOptsWithValidator(t *testing.T) { - // Re-using logOptsvalidator (used by MapOpts) - o := NewListOpts(logOptsValidator) - o.Set("foo") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } - o.Set("foo=bar") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } - o.Set("max-file=2") - if o.Len() != 1 { - t.Errorf("%d != 1", o.Len()) - } - if !o.Get("max-file=2") { - t.Error("o.Get(\"max-file=2\") == false") - } - if o.Get("baz") { - t.Error("o.Get(\"baz\") == true") - } - o.Delete("max-file=2") - if o.String() != "[]" { - t.Errorf("%s != []", o.String()) - } -} - -func TestValidateDNSSearch(t *testing.T) { - valid := []string{ - `.`, - `a`, - `a.`, - `1.foo`, - `17.foo`, - `foo.bar`, - `foo.bar.baz`, - `foo.bar.`, - `foo.bar.baz`, - `foo1.bar2`, - `foo1.bar2.baz`, - `1foo.2bar.`, - `1foo.2bar.baz`, - `foo-1.bar-2`, - `foo-1.bar-2.baz`, - `foo-1.bar-2.`, - `foo-1.bar-2.baz`, - `1-foo.2-bar`, - `1-foo.2-bar.baz`, - `1-foo.2-bar.`, - `1-foo.2-bar.baz`, - } - - invalid := []string{ - ``, - ` `, - ` `, - `17`, - `17.`, - `.17`, - `17-.`, - `17-.foo`, - `.foo`, - `foo-.bar`, - `-foo.bar`, - `foo.bar-`, - `foo.bar-.baz`, - `foo.-bar`, - `foo.-bar.baz`, - `foo.bar.baz.this.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbe`, - } - - for _, domain := range valid { - if ret, err := ValidateDNSSearch(domain); err != nil || ret == "" { - t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) - } - } - - for _, domain := range invalid { - if ret, err := ValidateDNSSearch(domain); err == nil || ret != "" { - t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) - } - } -} - -func TestValidateExtraHosts(t *testing.T) { - valid := []string{ - `myhost:192.168.0.1`, - `thathost:10.0.2.1`, - `anipv6host:2003:ab34:e::1`, - `ipv6local:::1`, - } - - invalid := map[string]string{ - `myhost:192.notanipaddress.1`: `invalid IP`, - `thathost-nosemicolon10.0.0.1`: `bad format`, - `anipv6host:::::1`: `invalid IP`, - `ipv6local:::0::`: `invalid IP`, - } - - for _, extrahost := range valid { - if _, err := ValidateExtraHost(extrahost); err != nil { - t.Fatalf("ValidateExtraHost(`"+extrahost+"`) should succeed: error %v", err) - } - } - - for extraHost, expectedError := range invalid { - if _, err := ValidateExtraHost(extraHost); err == nil { - t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost) - } else { - if !strings.Contains(err.Error(), expectedError) { - t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError) - } - } - } -} - -func TestValidateAttach(t *testing.T) { - valid := []string{ - "stdin", - "stdout", - "stderr", - "STDIN", - "STDOUT", - "STDERR", - } - if _, err := ValidateAttach("invalid"); err == nil { - t.Fatalf("Expected error with [valid streams are STDIN, STDOUT and STDERR], got nothing") - } - - for _, attach := range valid { - value, err := ValidateAttach(attach) - if err != nil { - t.Fatal(err) - } - if value != strings.ToLower(attach) { - t.Fatalf("Expected [%v], got [%v]", attach, value) - } - } -} - -func TestValidateLink(t *testing.T) { - valid := []string{ - "name", - "dcdfbe62ecd0:alias", - "7a67485460b7642516a4ad82ecefe7f57d0c4916f530561b71a50a3f9c4e33da", - "angry_torvalds:linus", - } - invalid := map[string]string{ - "": "empty string specified for links", - "too:much:of:it": "bad format for links: too:much:of:it", - } - - for _, link := range valid { - if _, err := ValidateLink(link); err != nil { - t.Fatalf("ValidateLink(`%q`) should succeed: error %q", link, err) - } - } - - for link, expectedError := range invalid { - if _, err := ValidateLink(link); err == nil { - t.Fatalf("ValidateLink(`%q`) should have failed validation", link) - } else { - if !strings.Contains(err.Error(), expectedError) { - t.Fatalf("ValidateLink(`%q`) error should contain %q", link, expectedError) - } - } - } -} - -func TestValidatePath(t *testing.T) { - valid := []string{ - "/home", - "/home:/home", - "/home:/something/else", - "/with space", - "/home:/with space", - "relative:/absolute-path", - "hostPath:/containerPath:ro", - "/hostPath:/containerPath:rw", - "/rw:/ro", - "/path:rw", - "/path:ro", - "/rw:rw", - } - invalid := map[string]string{ - "": "bad format for volumes: ", - "./": "./ is not an absolute path", - "../": "../ is not an absolute path", - "/:../": "../ is not an absolute path", - "/:path": "path is not an absolute path", - ":": "bad format for volumes: :", - "/tmp:": " is not an absolute path", - ":test": "bad format for volumes: :test", - ":/test": "bad format for volumes: :/test", - "tmp:": " is not an absolute path", - ":test:": "bad format for volumes: :test:", - "::": "bad format for volumes: ::", - ":::": "bad format for volumes: :::", - "/tmp:::": "bad format for volumes: /tmp:::", - ":/tmp::": "bad format for volumes: :/tmp::", - "path:ro": "path is not an absolute path", - "/path:/path:sw": "bad mount mode specified : sw", - "/path:/path:rwz": "bad mount mode specified : rwz", - } - - for _, path := range valid { - if _, err := ValidatePath(path); err != nil { - t.Fatalf("ValidatePath(`%q`) should succeed: error %q", path, err) - } - } - - for path, expectedError := range invalid { - if _, err := ValidatePath(path); err == nil { - t.Fatalf("ValidatePath(`%q`) should have failed validation", path) - } else { - if err.Error() != expectedError { - t.Fatalf("ValidatePath(`%q`) error should contain %q, got %q", path, expectedError, err.Error()) - } - } - } -} -func TestValidateDevice(t *testing.T) { - valid := []string{ - "/home", - "/home:/home", - "/home:/something/else", - "/with space", - "/home:/with space", - "relative:/absolute-path", - "hostPath:/containerPath:ro", - "/hostPath:/containerPath:rw", - "/hostPath:/containerPath:mrw", - } - invalid := map[string]string{ - "": "bad format for volumes: ", - "./": "./ is not an absolute path", - "../": "../ is not an absolute path", - "/:../": "../ is not an absolute path", - "/:path": "path is not an absolute path", - ":": "bad format for volumes: :", - "/tmp:": " is not an absolute path", - ":test": "bad format for volumes: :test", - ":/test": "bad format for volumes: :/test", - "tmp:": " is not an absolute path", - ":test:": "bad format for volumes: :test:", - "::": "bad format for volumes: ::", - ":::": "bad format for volumes: :::", - "/tmp:::": "bad format for volumes: /tmp:::", - ":/tmp::": "bad format for volumes: :/tmp::", - "path:ro": "ro is not an absolute path", - } - - for _, path := range valid { - if _, err := ValidateDevice(path); err != nil { - t.Fatalf("ValidateDevice(`%q`) should succeed: error %q", path, err) - } - } - - for path, expectedError := range invalid { - if _, err := ValidateDevice(path); err == nil { - t.Fatalf("ValidateDevice(`%q`) should have failed validation", path) - } else { - if err.Error() != expectedError { - t.Fatalf("ValidateDevice(`%q`) error should contain %q, got %q", path, expectedError, err.Error()) - } - } - } -} - -func TestValidateEnv(t *testing.T) { - invalids := map[string]string{ - "some spaces": "poorly formatted environment: variable 'some spaces' is not a valid environment variable", - "asd!qwe": "poorly formatted environment: variable 'asd!qwe' is not a valid environment variable", - "1asd": "poorly formatted environment: variable '1asd' is not a valid environment variable", - "123": "poorly formatted environment: variable '123' is not a valid environment variable", - } - valids := map[string]string{ - "a": "a", - "something": "something", - "_=a": "_=a", - "env1=value1": "env1=value1", - "_env1=value1": "_env1=value1", - "env2=value2=value3": "env2=value2=value3", - "env3=abc!qwe": "env3=abc!qwe", - "env_4=value 4": "env_4=value 4", - "PATH": fmt.Sprintf("PATH=%v", os.Getenv("PATH")), - "PATH=something": "PATH=something", - } - for value, expectedError := range invalids { - _, err := ValidateEnv(value) - if err == nil { - t.Fatalf("Expected ErrBadEnvVariable, got nothing") - } - if _, ok := err.(ErrBadEnvVariable); !ok { - t.Fatalf("Expected ErrBadEnvVariable, got [%s]", err) - } - if err.Error() != expectedError { - t.Fatalf("Expected ErrBadEnvVariable with message [%s], got [%s]", expectedError, err.Error()) - } - } - for value, expected := range valids { - actual, err := ValidateEnv(value) - if err != nil { - t.Fatal(err) - } - if actual != expected { - t.Fatalf("Expected [%v], got [%v]", expected, actual) - } - } -} - -func TestValidateLabel(t *testing.T) { - if _, err := ValidateLabel("label"); err == nil || err.Error() != "bad attribute format: label" { - t.Fatalf("Expected an error [bad attribute format: label], go %v", err) - } - if actual, err := ValidateLabel("key1=value1"); err != nil || actual != "key1=value1" { - t.Fatalf("Expected [key1=value1], got [%v,%v]", actual, err) - } - // Validate it's working with more than one = - if actual, err := ValidateLabel("key1=value1=value2"); err != nil { - t.Fatalf("Expected [key1=value1=value2], got [%v,%v]", actual, err) - } - // Validate it's working with one more - if actual, err := ValidateLabel("key1=value1=value2=value3"); err != nil { - t.Fatalf("Expected [key1=value1=value2=value2], got [%v,%v]", actual, err) - } -} - -func TestValidateHost(t *testing.T) { - invalid := map[string]string{ - "anything": "Invalid bind address format: anything", - "something with spaces": "Invalid bind address format: something with spaces", - "://": "Invalid bind address format: ://", - "unknown://": "Invalid bind address format: unknown://", - "tcp://": "Invalid proto, expected tcp: ", - "tcp://:port": "Invalid bind address format: :port", - "tcp://invalid": "Invalid bind address format: invalid", - "tcp://invalid:port": "Invalid bind address format: invalid:port", - } - valid := map[string]string{ - "fd://": "fd://", - "fd://something": "fd://something", - "tcp://:2375": "tcp://127.0.0.1:2375", // default ip address - "tcp://:2376": "tcp://127.0.0.1:2376", // default ip address - "tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080", - "tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000", - "tcp://192.168:8080": "tcp://192.168:8080", - "tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P - "tcp://docker.com:2375": "tcp://docker.com:2375", - "unix://": "unix:///var/run/docker.sock", // default unix:// value - "unix://path/to/socket": "unix://path/to/socket", - } - - for value, errorMessage := range invalid { - if _, err := ValidateHost(value); err == nil || err.Error() != errorMessage { - t.Fatalf("Expected an error for %v with [%v], got [%v]", value, errorMessage, err) - } - } - for value, expected := range valid { - if actual, err := ValidateHost(value); err != nil || actual != expected { - t.Fatalf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err) - } - } -} - -func logOptsValidator(val string) (string, error) { - allowedKeys := map[string]string{"max-size": "1", "max-file": "2"} - vals := strings.Split(val, "=") - if allowedKeys[vals[0]] != "" { - return val, nil - } - return "", fmt.Errorf("invalid key %s", vals[0]) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ulimit_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ulimit_test.go deleted file mode 100644 index ad284e7545b..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ulimit_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package opts - -import ( - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit" -) - -func TestUlimitOpt(t *testing.T) { - ulimitMap := map[string]*ulimit.Ulimit{ - "nofile": {"nofile", 1024, 512}, - } - - ulimitOpt := NewUlimitOpt(&ulimitMap) - - expected := "[nofile=512:1024]" - if ulimitOpt.String() != expected { - t.Fatalf("Expected %v, got %v", expected, ulimitOpt) - } - - // Valid ulimit append to opts - if err := ulimitOpt.Set("core=1024:1024"); err != nil { - t.Fatal(err) - } - - // Invalid ulimit type returns an error and do not append to opts - if err := ulimitOpt.Set("notavalidtype=1024:1024"); err == nil { - t.Fatalf("Expected error on invalid ulimit type") - } - expected = "[nofile=512:1024 core=1024:1024]" - expected2 := "[core=1024:1024 nofile=512:1024]" - result := ulimitOpt.String() - if result != expected && result != expected2 { - t.Fatalf("Expected %v or %v, got %v", expected, expected2, ulimitOpt) - } - - // And test GetList - ulimits := ulimitOpt.GetList() - if len(ulimits) != 2 { - t.Fatalf("Expected a ulimit list of 2, got %v", ulimits) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go deleted file mode 100644 index 4bb4f6ff5d1..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go +++ /dev/null @@ -1,1204 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "syscall" - "testing" - "time" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" -) - -func TestIsArchiveNilHeader(t *testing.T) { - out := IsArchive(nil) - if out { - t.Fatalf("isArchive should return false as nil is not a valid archive header") - } -} - -func TestIsArchiveInvalidHeader(t *testing.T) { - header := []byte{0x00, 0x01, 0x02} - out := IsArchive(header) - if out { - t.Fatalf("isArchive should return false as %s is not a valid archive header", header) - } -} - -func TestIsArchiveBzip2(t *testing.T) { - header := []byte{0x42, 0x5A, 0x68} - out := IsArchive(header) - if !out { - t.Fatalf("isArchive should return true as %s is a bz2 header", header) - } -} - -func TestIsArchive7zip(t *testing.T) { - header := []byte{0x50, 0x4b, 0x03, 0x04} - out := IsArchive(header) - if out { - t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header) - } -} - -func TestDecompressStreamGzip(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.gz") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a gzip file.") - } -} - -func TestDecompressStreamBzip2(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.bz2") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a bzip2 file.") - } -} - -func TestDecompressStreamXz(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && xz -f /tmp/archive") - output, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("Fail to create an archive file for test : %s.", output) - } - archive, err := os.Open("/tmp/archive.xz") - _, err = DecompressStream(archive) - if err != nil { - t.Fatalf("Failed to decompress a xz file.") - } -} - -func TestCompressStreamXzUnsuported(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, Xz) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestCompressStreamBzip2Unsupported(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, Xz) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestCompressStreamInvalid(t *testing.T) { - dest, err := os.Create("/tmp/dest") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - _, err = CompressStream(dest, -1) - if err == nil { - t.Fatalf("Should fail as xz is unsupported for compression format.") - } -} - -func TestExtensionInvalid(t *testing.T) { - compression := Compression(-1) - output := compression.Extension() - if output != "" { - t.Fatalf("The extension of an invalid compression should be an empty string.") - } -} - -func TestExtensionUncompressed(t *testing.T) { - compression := Uncompressed - output := compression.Extension() - if output != "tar" { - t.Fatalf("The extension of a uncompressed archive should be 'tar'.") - } -} -func TestExtensionBzip2(t *testing.T) { - compression := Bzip2 - output := compression.Extension() - if output != "tar.bz2" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") - } -} -func TestExtensionGzip(t *testing.T) { - compression := Gzip - output := compression.Extension() - if output != "tar.gz" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") - } -} -func TestExtensionXz(t *testing.T) { - compression := Xz - output := compression.Extension() - if output != "tar.xz" { - t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'") - } -} - -func TestCmdStreamLargeStderr(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello") - out, err := CmdStream(cmd, nil) - if err != nil { - t.Fatalf("Failed to start command: %s", err) - } - errCh := make(chan error) - go func() { - _, err := io.Copy(ioutil.Discard, out) - errCh <- err - }() - select { - case err := <-errCh: - if err != nil { - t.Fatalf("Command should not have failed (err=%.100s...)", err) - } - case <-time.After(5 * time.Second): - t.Fatalf("Command did not complete in 5 seconds; probable deadlock") - } -} - -func TestCmdStreamBad(t *testing.T) { - badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1") - out, err := CmdStream(badCmd, nil) - if err != nil { - t.Fatalf("Failed to start command: %s", err) - } - if output, err := ioutil.ReadAll(out); err == nil { - t.Fatalf("Command should have failed") - } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" { - t.Fatalf("Wrong error value (%s)", err) - } else if s := string(output); s != "hello\n" { - t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) - } -} - -func TestCmdStreamGood(t *testing.T) { - cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0") - out, err := CmdStream(cmd, nil) - if err != nil { - t.Fatal(err) - } - if output, err := ioutil.ReadAll(out); err != nil { - t.Fatalf("Command should not have failed (err=%s)", err) - } else if s := string(output); s != "hello\n" { - t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) - } -} - -func TestUntarPathWithInvalidDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - invalidDestFolder := path.Join(tempFolder, "invalidDest") - // Create a src file - srcFile := path.Join(tempFolder, "src") - _, err = os.Create(srcFile) - if err != nil { - t.Fatalf("Fail to create the source file") - } - err = UntarPath(srcFile, invalidDestFolder) - if err == nil { - t.Fatalf("UntarPath with invalid destination path should throw an error.") - } -} - -func TestUntarPathWithInvalidSrc(t *testing.T) { - dest, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatalf("Fail to create the destination file") - } - defer os.RemoveAll(dest) - err = UntarPath("/invalid/path", dest) - if err == nil { - t.Fatalf("UntarPath with invalid src path should throw an error.") - } -} - -func TestUntarPath(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(path.Join(tmpFolder, "src")) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFolder := path.Join(tmpFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatalf("Fail to create the destination file") - } - err = UntarPath(tarFile, destFolder) - if err != nil { - t.Fatalf("UntarPath shouldn't throw an error, %s.", err) - } - expectedFile := path.Join(destFolder, srcFile) - _, err = os.Stat(expectedFile) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -// Do the same test as above but with the destination as file, it should fail -func TestUntarPathWithDestinationFile(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(path.Join(tmpFolder, "src")) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFile := path.Join(tmpFolder, "dest") - _, err = os.Create(destFile) - if err != nil { - t.Fatalf("Fail to create the destination file") - } - err = UntarPath(tarFile, destFile) - if err == nil { - t.Fatalf("UntarPath should throw an error if the destination if a file") - } -} - -// Do the same test as above but with the destination folder already exists -// and the destination file is a directory -// It's working, see https://github.com/docker/docker/issues/10040 -func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) { - tmpFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpFolder) - srcFile := path.Join(tmpFolder, "src") - tarFile := path.Join(tmpFolder, "src.tar") - os.Create(srcFile) - cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) - _, err = cmd.CombinedOutput() - if err != nil { - t.Fatal(err) - } - destFolder := path.Join(tmpFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatalf("Fail to create the destination folder") - } - // Let's create a folder that will has the same path as the extracted file (from tar) - destSrcFileAsFolder := path.Join(destFolder, srcFile) - err = os.MkdirAll(destSrcFileAsFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = UntarPath(tarFile, destFolder) - if err != nil { - t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder") - } -} - -func TestCopyWithTarInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - destFolder := path.Join(tempFolder, "dest") - invalidSrc := path.Join(tempFolder, "doesnotexists") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyWithTar(invalidSrc, destFolder) - if err == nil { - t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") - } -} - -func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - srcFolder := path.Join(tempFolder, "src") - inexistentDestFolder := path.Join(tempFolder, "doesnotexists") - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyWithTar(srcFolder, inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") - } - _, err = os.Stat(inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder should create it.") - } -} - -// Test CopyWithTar with a file as src -func TestCopyWithTarSrcFile(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - srcFolder := path.Join(folder, "src") - src := path.Join(folder, path.Join("src", "src")) - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(src, []byte("content"), 0777) - err = CopyWithTar(src, dest) - if err != nil { - t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - // FIXME Check the content - if err != nil { - t.Fatalf("Destination file should be the same as the source.") - } -} - -// Test CopyWithTar with a folder as src -func TestCopyWithTarSrcFolder(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - src := path.Join(folder, path.Join("src", "folder")) - err = os.MkdirAll(src, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(path.Join(src, "file"), []byte("content"), 0777) - err = CopyWithTar(src, dest) - if err != nil { - t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - // FIXME Check the content (the file inside) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -func TestCopyFileWithTarInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - destFolder := path.Join(tempFolder, "dest") - err = os.MkdirAll(destFolder, 0740) - if err != nil { - t.Fatal(err) - } - invalidFile := path.Join(tempFolder, "doesnotexists") - err = CopyFileWithTar(invalidFile, destFolder) - if err == nil { - t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") - } -} - -func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(nil) - } - defer os.RemoveAll(tempFolder) - srcFile := path.Join(tempFolder, "src") - inexistentDestFolder := path.Join(tempFolder, "doesnotexists") - _, err = os.Create(srcFile) - if err != nil { - t.Fatal(err) - } - err = CopyFileWithTar(srcFile, inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") - } - _, err = os.Stat(inexistentDestFolder) - if err != nil { - t.Fatalf("CopyWithTar with an inexistent folder should create it.") - } - // FIXME Test the src file and content -} - -func TestCopyFileWithTarSrcFolder(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - src := path.Join(folder, "srcfolder") - err = os.MkdirAll(src, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - err = CopyFileWithTar(src, dest) - if err == nil { - t.Fatalf("CopyFileWithTar should throw an error with a folder.") - } -} - -func TestCopyFileWithTarSrcFile(t *testing.T) { - folder, err := ioutil.TempDir("", "docker-archive-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(folder) - dest := path.Join(folder, "dest") - srcFolder := path.Join(folder, "src") - src := path.Join(folder, path.Join("src", "src")) - err = os.MkdirAll(srcFolder, 0740) - if err != nil { - t.Fatal(err) - } - err = os.MkdirAll(dest, 0740) - if err != nil { - t.Fatal(err) - } - ioutil.WriteFile(src, []byte("content"), 0777) - err = CopyWithTar(src, dest+"/") - if err != nil { - t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err) - } - _, err = os.Stat(dest) - if err != nil { - t.Fatalf("Destination folder should contain the source file but did not.") - } -} - -func TestTarFiles(t *testing.T) { - // try without hardlinks - if err := checkNoChanges(1000, false); err != nil { - t.Fatal(err) - } - // try with hardlinks - if err := checkNoChanges(1000, true); err != nil { - t.Fatal(err) - } -} - -func checkNoChanges(fileNum int, hardlinks bool) error { - srcDir, err := ioutil.TempDir("", "docker-test-srcDir") - if err != nil { - return err - } - defer os.RemoveAll(srcDir) - - destDir, err := ioutil.TempDir("", "docker-test-destDir") - if err != nil { - return err - } - defer os.RemoveAll(destDir) - - _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks) - if err != nil { - return err - } - - err = TarUntar(srcDir, destDir) - if err != nil { - return err - } - - changes, err := ChangesDirs(destDir, srcDir) - if err != nil { - return err - } - if len(changes) > 0 { - return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes)) - } - return nil -} - -func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) { - archive, err := TarWithOptions(origin, options) - if err != nil { - t.Fatal(err) - } - defer archive.Close() - - buf := make([]byte, 10) - if _, err := archive.Read(buf); err != nil { - return nil, err - } - wrap := io.MultiReader(bytes.NewReader(buf), archive) - - detectedCompression := DetectCompression(buf) - compression := options.Compression - if detectedCompression.Extension() != compression.Extension() { - return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension()) - } - - tmp, err := ioutil.TempDir("", "docker-test-untar") - if err != nil { - return nil, err - } - defer os.RemoveAll(tmp) - if err := Untar(wrap, tmp, nil); err != nil { - return nil, err - } - if _, err := os.Stat(tmp); err != nil { - return nil, err - } - - return ChangesDirs(origin, tmp) -} - -func TestTarUntar(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { - t.Fatal(err) - } - - for _, c := range []Compression{ - Uncompressed, - Gzip, - } { - changes, err := tarUntar(t, origin, &TarOptions{ - Compression: c, - ExcludePatterns: []string{"3"}, - }) - - if err != nil { - t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) - } - - if len(changes) != 1 || changes[0].Path != "/3" { - t.Fatalf("Unexpected differences after tarUntar: %v", changes) - } - } -} - -func TestTarUntarWithXattr(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { - t.Fatal(err) - } - if err := system.Lsetxattr(path.Join(origin, "2"), "security.capability", []byte{0x00}, 0); err != nil { - t.Fatal(err) - } - - for _, c := range []Compression{ - Uncompressed, - Gzip, - } { - changes, err := tarUntar(t, origin, &TarOptions{ - Compression: c, - ExcludePatterns: []string{"3"}, - }) - - if err != nil { - t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) - } - - if len(changes) != 1 || changes[0].Path != "/3" { - t.Fatalf("Unexpected differences after tarUntar: %v", changes) - } - capability, _ := system.Lgetxattr(path.Join(origin, "2"), "security.capability") - if capability == nil && capability[0] != 0x00 { - t.Fatalf("Untar should have kept the 'security.capability' xattr.") - } - } -} - -func TestTarWithOptions(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - t.Fatal(err) - } - if _, err := ioutil.TempDir(origin, "folder"); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { - t.Fatal(err) - } - - cases := []struct { - opts *TarOptions - numChanges int - }{ - {&TarOptions{IncludeFiles: []string{"1"}}, 2}, - {&TarOptions{ExcludePatterns: []string{"2"}}, 1}, - {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2}, - {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2}, - {&TarOptions{Name: "test", IncludeFiles: []string{"1"}}, 4}, - } - for _, testCase := range cases { - changes, err := tarUntar(t, origin, testCase.opts) - if err != nil { - t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err) - } - if len(changes) != testCase.numChanges { - t.Errorf("Expected %d changes, got %d for %+v:", - testCase.numChanges, len(changes), testCase.opts) - } - } -} - -// Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz -// use PAX Global Extended Headers. -// Failing prevents the archives from being uncompressed during ADD -func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) { - hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader} - tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tmpDir) - err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil) - if err != nil { - t.Fatal(err) - } -} - -// Some tar have both GNU specific (huge uid) and Ustar specific (long name) things. -// Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work. -func TestUntarUstarGnuConflict(t *testing.T) { - f, err := os.Open("testdata/broken.tar") - if err != nil { - t.Fatal(err) - } - found := false - tr := tar.NewReader(f) - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - t.Fatal(err) - } - if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" { - found = true - break - } - } - if !found { - t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm") - } -} - -func TestTarWithBlockCharFifo(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "2"), syscall.S_IFBLK, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "3"), syscall.S_IFCHR, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - if err := system.Mknod(path.Join(origin, "4"), syscall.S_IFIFO, int(system.Mkdev(int64(12), int64(5)))); err != nil { - t.Fatal(err) - } - - dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - - // we'll do this in two steps to separate failure - fh, err := Tar(origin, Uncompressed) - if err != nil { - t.Fatal(err) - } - - // ensure we can read the whole thing with no error, before writing back out - buf, err := ioutil.ReadAll(fh) - if err != nil { - t.Fatal(err) - } - - bRdr := bytes.NewReader(buf) - err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) - if err != nil { - t.Fatal(err) - } - - changes, err := ChangesDirs(origin, dest) - if err != nil { - t.Fatal(err) - } - if len(changes) > 0 { - t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %v", changes) - } -} - -func TestTarWithHardLink(t *testing.T) { - origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(origin) - if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { - t.Fatal(err) - } - if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil { - t.Fatal(err) - } - - var i1, i2 uint64 - if i1, err = getNlink(path.Join(origin, "1")); err != nil { - t.Fatal(err) - } - // sanity check that we can hardlink - if i1 != 2 { - t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1) - } - - dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - - // we'll do this in two steps to separate failure - fh, err := Tar(origin, Uncompressed) - if err != nil { - t.Fatal(err) - } - - // ensure we can read the whole thing with no error, before writing back out - buf, err := ioutil.ReadAll(fh) - if err != nil { - t.Fatal(err) - } - - bRdr := bytes.NewReader(buf) - err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) - if err != nil { - t.Fatal(err) - } - - if i1, err = getInode(path.Join(dest, "1")); err != nil { - t.Fatal(err) - } - if i2, err = getInode(path.Join(dest, "2")); err != nil { - t.Fatal(err) - } - - if i1 != i2 { - t.Errorf("expected matching inodes, but got %d and %d", i1, i2) - } -} - -func getNlink(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - statT, ok := stat.Sys().(*syscall.Stat_t) - if !ok { - return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) - } - // We need this conversion on ARM64 - return uint64(statT.Nlink), nil -} - -func getInode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - statT, ok := stat.Sys().(*syscall.Stat_t) - if !ok { - return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) - } - return statT.Ino, nil -} - -func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { - fileData := []byte("fooo") - for n := 0; n < numberOfFiles; n++ { - fileName := fmt.Sprintf("file-%d", n) - if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { - return 0, err - } - if makeLinks { - if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { - return 0, err - } - } - } - totalSize := numberOfFiles * len(fileData) - return totalSize, nil -} - -func BenchmarkTarUntar(b *testing.B) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - b.Fatal(err) - } - tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") - if err != nil { - b.Fatal(err) - } - target := path.Join(tempDir, "dest") - n, err := prepareUntarSourceDirectory(100, origin, false) - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(origin) - defer os.RemoveAll(tempDir) - - b.ResetTimer() - b.SetBytes(int64(n)) - for n := 0; n < b.N; n++ { - err := TarUntar(origin, target) - if err != nil { - b.Fatal(err) - } - os.RemoveAll(target) - } -} - -func BenchmarkTarUntarWithLinks(b *testing.B) { - origin, err := ioutil.TempDir("", "docker-test-untar-origin") - if err != nil { - b.Fatal(err) - } - tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") - if err != nil { - b.Fatal(err) - } - target := path.Join(tempDir, "dest") - n, err := prepareUntarSourceDirectory(100, origin, true) - if err != nil { - b.Fatal(err) - } - defer os.RemoveAll(origin) - defer os.RemoveAll(tempDir) - - b.ResetTimer() - b.SetBytes(int64(n)) - for n := 0; n < b.N; n++ { - err := TarUntar(origin, target) - if err != nil { - b.Fatal(err) - } - os.RemoveAll(target) - } -} - -func TestUntarInvalidFilenames(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "../victim/dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { - { - // Note the leading slash - Name: "/../victim/slash-dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarHardlinkToSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "symlink1", - Typeflag: tar.TypeSymlink, - Linkname: "regfile", - Mode: 0644, - }, - { - Name: "symlink2", - Typeflag: tar.TypeLink, - Linkname: "symlink1", - Mode: 0644, - }, - { - Name: "regfile", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarInvalidHardlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeLink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeLink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (hardlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try reading victim/hello (hardlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try removing victim directory (hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestUntarInvalidSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeSymlink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeSymlink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try removing victim directory (symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try writing to victim/newdir/newfile with a symlink in the path - { - // this header needs to be before the next one, or else there is an error - Name: "dir/loophole", - Typeflag: tar.TypeSymlink, - Linkname: "../../victim", - Mode: 0755, - }, - { - Name: "dir/loophole/newdir/newfile", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestTempArchiveCloseMultipleTimes(t *testing.T) { - reader := ioutil.NopCloser(strings.NewReader("hello")) - tempArchive, err := NewTempArchive(reader, "") - buf := make([]byte, 10) - n, err := tempArchive.Read(buf) - if n != 5 { - t.Fatalf("Expected to read 5 bytes. Read %d instead", n) - } - for i := 0; i < 3; i++ { - if err = tempArchive.Close(); err != nil { - t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go deleted file mode 100644 index 18f45c480f1..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build !windows - -package archive - -import ( - "os" - "testing" -) - -func TestCanonicalTarNameForPath(t *testing.T) { - cases := []struct{ in, expected string }{ - {"foo", "foo"}, - {"foo/bar", "foo/bar"}, - {"foo/dir/", "foo/dir/"}, - } - for _, v := range cases { - if out, err := CanonicalTarNameForPath(v.in); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestCanonicalTarName(t *testing.T) { - cases := []struct { - in string - isDir bool - expected string - }{ - {"foo", false, "foo"}, - {"foo", true, "foo/"}, - {"foo/bar", false, "foo/bar"}, - {"foo/bar", true, "foo/bar/"}, - } - for _, v := range cases { - if out, err := canonicalTarName(v.in, v.isDir); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestChmodTarEntry(t *testing.T) { - cases := []struct { - in, expected os.FileMode - }{ - {0000, 0000}, - {0777, 0777}, - {0644, 0644}, - {0755, 0755}, - {0444, 0444}, - } - for _, v := range cases { - if out := chmodTarEntry(v.in); out != v.expected { - t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go deleted file mode 100644 index 72bc71e06b4..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build windows - -package archive - -import ( - "os" - "testing" -) - -func TestCanonicalTarNameForPath(t *testing.T) { - cases := []struct { - in, expected string - shouldFail bool - }{ - {"foo", "foo", false}, - {"foo/bar", "___", true}, // unix-styled windows path must fail - {`foo\bar`, "foo/bar", false}, - } - for _, v := range cases { - if out, err := CanonicalTarNameForPath(v.in); err != nil && !v.shouldFail { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if v.shouldFail && err == nil { - t.Fatalf("canonical path call should have failed with error. in=%s out=%s", v.in, out) - } else if !v.shouldFail && out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestCanonicalTarName(t *testing.T) { - cases := []struct { - in string - isDir bool - expected string - }{ - {"foo", false, "foo"}, - {"foo", true, "foo/"}, - {`foo\bar`, false, "foo/bar"}, - {`foo\bar`, true, "foo/bar/"}, - } - for _, v := range cases { - if out, err := canonicalTarName(v.in, v.isDir); err != nil { - t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) - } else if out != v.expected { - t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) - } - } -} - -func TestChmodTarEntry(t *testing.T) { - cases := []struct { - in, expected os.FileMode - }{ - {0000, 0111}, - {0777, 0755}, - {0644, 0755}, - {0755, 0755}, - {0444, 0555}, - } - for _, v := range cases { - if out := chmodTarEntry(v.in); out != v.expected { - t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go deleted file mode 100644 index 9d528e614c4..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package archive - -import ( - "archive/tar" - "fmt" - "io" - "io/ioutil" - "os" - "path" - "sort" - "testing" -) - -func TestHardLinkOrder(t *testing.T) { - names := []string{"file1.txt", "file2.txt", "file3.txt"} - msg := []byte("Hey y'all") - - // Create dir - src, err := ioutil.TempDir("", "docker-hardlink-test-src-") - if err != nil { - t.Fatal(err) - } - //defer os.RemoveAll(src) - for _, name := range names { - func() { - fh, err := os.Create(path.Join(src, name)) - if err != nil { - t.Fatal(err) - } - defer fh.Close() - if _, err = fh.Write(msg); err != nil { - t.Fatal(err) - } - }() - } - // Create dest, with changes that includes hardlinks - dest, err := ioutil.TempDir("", "docker-hardlink-test-dest-") - if err != nil { - t.Fatal(err) - } - os.RemoveAll(dest) // we just want the name, at first - if err := copyDir(src, dest); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dest) - for _, name := range names { - for i := 0; i < 5; i++ { - if err := os.Link(path.Join(dest, name), path.Join(dest, fmt.Sprintf("%s.link%d", name, i))); err != nil { - t.Fatal(err) - } - } - } - - // get changes - changes, err := ChangesDirs(dest, src) - if err != nil { - t.Fatal(err) - } - - // sort - sort.Sort(changesByPath(changes)) - - // ExportChanges - ar, err := ExportChanges(dest, changes) - if err != nil { - t.Fatal(err) - } - hdrs, err := walkHeaders(ar) - if err != nil { - t.Fatal(err) - } - - // reverse sort - sort.Sort(sort.Reverse(changesByPath(changes))) - // ExportChanges - arRev, err := ExportChanges(dest, changes) - if err != nil { - t.Fatal(err) - } - hdrsRev, err := walkHeaders(arRev) - if err != nil { - t.Fatal(err) - } - - // line up the two sets - sort.Sort(tarHeaders(hdrs)) - sort.Sort(tarHeaders(hdrsRev)) - - // compare Size and LinkName - for i := range hdrs { - if hdrs[i].Name != hdrsRev[i].Name { - t.Errorf("headers - expected name %q; but got %q", hdrs[i].Name, hdrsRev[i].Name) - } - if hdrs[i].Size != hdrsRev[i].Size { - t.Errorf("headers - %q expected size %d; but got %d", hdrs[i].Name, hdrs[i].Size, hdrsRev[i].Size) - } - if hdrs[i].Typeflag != hdrsRev[i].Typeflag { - t.Errorf("headers - %q expected type %d; but got %d", hdrs[i].Name, hdrs[i].Typeflag, hdrsRev[i].Typeflag) - } - if hdrs[i].Linkname != hdrsRev[i].Linkname { - t.Errorf("headers - %q expected linkname %q; but got %q", hdrs[i].Name, hdrs[i].Linkname, hdrsRev[i].Linkname) - } - } - -} - -type tarHeaders []tar.Header - -func (th tarHeaders) Len() int { return len(th) } -func (th tarHeaders) Swap(i, j int) { th[j], th[i] = th[i], th[j] } -func (th tarHeaders) Less(i, j int) bool { return th[i].Name < th[j].Name } - -func walkHeaders(r io.Reader) ([]tar.Header, error) { - t := tar.NewReader(r) - headers := []tar.Header{} - for { - hdr, err := t.Next() - if err != nil { - if err == io.EOF { - break - } - return headers, err - } - headers = append(headers, *hdr) - } - return headers, nil -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go deleted file mode 100644 index 509bdb2e6d6..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go +++ /dev/null @@ -1,495 +0,0 @@ -package archive - -import ( - "io/ioutil" - "os" - "os/exec" - "path" - "sort" - "testing" - "time" -) - -func max(x, y int) int { - if x >= y { - return x - } - return y -} - -func copyDir(src, dst string) error { - cmd := exec.Command("cp", "-a", src, dst) - if err := cmd.Run(); err != nil { - return err - } - return nil -} - -type FileType uint32 - -const ( - Regular FileType = iota - Dir - Symlink -) - -type FileData struct { - filetype FileType - path string - contents string - permissions os.FileMode -} - -func createSampleDir(t *testing.T, root string) { - files := []FileData{ - {Regular, "file1", "file1\n", 0600}, - {Regular, "file2", "file2\n", 0666}, - {Regular, "file3", "file3\n", 0404}, - {Regular, "file4", "file4\n", 0600}, - {Regular, "file5", "file5\n", 0600}, - {Regular, "file6", "file6\n", 0600}, - {Regular, "file7", "file7\n", 0600}, - {Dir, "dir1", "", 0740}, - {Regular, "dir1/file1-1", "file1-1\n", 01444}, - {Regular, "dir1/file1-2", "file1-2\n", 0666}, - {Dir, "dir2", "", 0700}, - {Regular, "dir2/file2-1", "file2-1\n", 0666}, - {Regular, "dir2/file2-2", "file2-2\n", 0666}, - {Dir, "dir3", "", 0700}, - {Regular, "dir3/file3-1", "file3-1\n", 0666}, - {Regular, "dir3/file3-2", "file3-2\n", 0666}, - {Dir, "dir4", "", 0700}, - {Regular, "dir4/file3-1", "file4-1\n", 0666}, - {Regular, "dir4/file3-2", "file4-2\n", 0666}, - {Symlink, "symlink1", "target1", 0666}, - {Symlink, "symlink2", "target2", 0666}, - } - - now := time.Now() - for _, info := range files { - p := path.Join(root, info.path) - if info.filetype == Dir { - if err := os.MkdirAll(p, info.permissions); err != nil { - t.Fatal(err) - } - } else if info.filetype == Regular { - if err := ioutil.WriteFile(p, []byte(info.contents), info.permissions); err != nil { - t.Fatal(err) - } - } else if info.filetype == Symlink { - if err := os.Symlink(info.contents, p); err != nil { - t.Fatal(err) - } - } - - if info.filetype != Symlink { - // Set a consistent ctime, atime for all files and dirs - if err := os.Chtimes(p, now, now); err != nil { - t.Fatal(err) - } - } - } -} - -func TestChangeString(t *testing.T) { - modifiyChange := Change{"change", ChangeModify} - toString := modifiyChange.String() - if toString != "C change" { - t.Fatalf("String() of a change with ChangeModifiy Kind should have been %s but was %s", "C change", toString) - } - addChange := Change{"change", ChangeAdd} - toString = addChange.String() - if toString != "A change" { - t.Fatalf("String() of a change with ChangeAdd Kind should have been %s but was %s", "A change", toString) - } - deleteChange := Change{"change", ChangeDelete} - toString = deleteChange.String() - if toString != "D change" { - t.Fatalf("String() of a change with ChangeDelete Kind should have been %s but was %s", "D change", toString) - } -} - -func TestChangesWithNoChanges(t *testing.T) { - rwLayer, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(rwLayer) - layer, err := ioutil.TempDir("", "docker-changes-test-layer") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(layer) - createSampleDir(t, layer) - changes, err := Changes([]string{layer}, rwLayer) - if err != nil { - t.Fatal(err) - } - if len(changes) != 0 { - t.Fatalf("Changes with no difference should have detect no changes, but detected %d", len(changes)) - } -} - -func TestChangesWithChanges(t *testing.T) { - // Mock the readonly layer - layer, err := ioutil.TempDir("", "docker-changes-test-layer") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(layer) - createSampleDir(t, layer) - os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740) - - // Mock the RW layer - rwLayer, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(rwLayer) - - // Create a folder in RW layer - dir1 := path.Join(rwLayer, "dir1") - os.MkdirAll(dir1, 0740) - deletedFile := path.Join(dir1, ".wh.file1-2") - ioutil.WriteFile(deletedFile, []byte{}, 0600) - modifiedFile := path.Join(dir1, "file1-1") - ioutil.WriteFile(modifiedFile, []byte{0x00}, 01444) - // Let's add a subfolder for a newFile - subfolder := path.Join(dir1, "subfolder") - os.MkdirAll(subfolder, 0740) - newFile := path.Join(subfolder, "newFile") - ioutil.WriteFile(newFile, []byte{}, 0740) - - changes, err := Changes([]string{layer}, rwLayer) - if err != nil { - t.Fatal(err) - } - - expectedChanges := []Change{ - {"/dir1", ChangeModify}, - {"/dir1/file1-1", ChangeModify}, - {"/dir1/file1-2", ChangeDelete}, - {"/dir1/subfolder", ChangeModify}, - {"/dir1/subfolder/newFile", ChangeAdd}, - } - checkChanges(expectedChanges, changes, t) -} - -// See https://github.com/docker/docker/pull/13590 -func TestChangesWithChangesGH13590(t *testing.T) { - baseLayer, err := ioutil.TempDir("", "docker-changes-test.") - defer os.RemoveAll(baseLayer) - - dir3 := path.Join(baseLayer, "dir1/dir2/dir3") - os.MkdirAll(dir3, 07400) - - file := path.Join(dir3, "file.txt") - ioutil.WriteFile(file, []byte("hello"), 0666) - - layer, err := ioutil.TempDir("", "docker-changes-test2.") - defer os.RemoveAll(layer) - - // Test creating a new file - if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { - t.Fatalf("Cmd failed: %q", err) - } - - os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt")) - file = path.Join(layer, "dir1/dir2/dir3/file1.txt") - ioutil.WriteFile(file, []byte("bye"), 0666) - - changes, err := Changes([]string{baseLayer}, layer) - if err != nil { - t.Fatal(err) - } - - expectedChanges := []Change{ - {"/dir1/dir2/dir3", ChangeModify}, - {"/dir1/dir2/dir3/file1.txt", ChangeAdd}, - } - checkChanges(expectedChanges, changes, t) - - // Now test changing a file - layer, err = ioutil.TempDir("", "docker-changes-test3.") - defer os.RemoveAll(layer) - - if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { - t.Fatalf("Cmd failed: %q", err) - } - - file = path.Join(layer, "dir1/dir2/dir3/file.txt") - ioutil.WriteFile(file, []byte("bye"), 0666) - - changes, err = Changes([]string{baseLayer}, layer) - if err != nil { - t.Fatal(err) - } - - expectedChanges = []Change{ - {"/dir1/dir2/dir3/file.txt", ChangeModify}, - } - checkChanges(expectedChanges, changes, t) -} - -// Create an directory, copy it, make sure we report no changes between the two -func TestChangesDirsEmpty(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(src) - createSampleDir(t, src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(dst) - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - if len(changes) != 0 { - t.Fatalf("Reported changes for identical dirs: %v", changes) - } - os.RemoveAll(src) - os.RemoveAll(dst) -} - -func mutateSampleDir(t *testing.T, root string) { - // Remove a regular file - if err := os.RemoveAll(path.Join(root, "file1")); err != nil { - t.Fatal(err) - } - - // Remove a directory - if err := os.RemoveAll(path.Join(root, "dir1")); err != nil { - t.Fatal(err) - } - - // Remove a symlink - if err := os.RemoveAll(path.Join(root, "symlink1")); err != nil { - t.Fatal(err) - } - - // Rewrite a file - if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777); err != nil { - t.Fatal(err) - } - - // Replace a file - if err := os.RemoveAll(path.Join(root, "file3")); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404); err != nil { - t.Fatal(err) - } - - // Touch file - if err := os.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { - t.Fatal(err) - } - - // Replace file with dir - if err := os.RemoveAll(path.Join(root, "file5")); err != nil { - t.Fatal(err) - } - if err := os.MkdirAll(path.Join(root, "file5"), 0666); err != nil { - t.Fatal(err) - } - - // Create new file - if err := ioutil.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777); err != nil { - t.Fatal(err) - } - - // Create new dir - if err := os.MkdirAll(path.Join(root, "dirnew"), 0766); err != nil { - t.Fatal(err) - } - - // Create a new symlink - if err := os.Symlink("targetnew", path.Join(root, "symlinknew")); err != nil { - t.Fatal(err) - } - - // Change a symlink - if err := os.RemoveAll(path.Join(root, "symlink2")); err != nil { - t.Fatal(err) - } - if err := os.Symlink("target2change", path.Join(root, "symlink2")); err != nil { - t.Fatal(err) - } - - // Replace dir with file - if err := os.RemoveAll(path.Join(root, "dir2")); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777); err != nil { - t.Fatal(err) - } - - // Touch dir - if err := os.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { - t.Fatal(err) - } -} - -func TestChangesDirsMutated(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - createSampleDir(t, src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - defer os.RemoveAll(src) - defer os.RemoveAll(dst) - - mutateSampleDir(t, dst) - - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - sort.Sort(changesByPath(changes)) - - expectedChanges := []Change{ - {"/dir1", ChangeDelete}, - {"/dir2", ChangeModify}, - {"/dirnew", ChangeAdd}, - {"/file1", ChangeDelete}, - {"/file2", ChangeModify}, - {"/file3", ChangeModify}, - {"/file4", ChangeModify}, - {"/file5", ChangeModify}, - {"/filenew", ChangeAdd}, - {"/symlink1", ChangeDelete}, - {"/symlink2", ChangeModify}, - {"/symlinknew", ChangeAdd}, - } - - for i := 0; i < max(len(changes), len(expectedChanges)); i++ { - if i >= len(expectedChanges) { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } - if i >= len(changes) { - t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) - } - if changes[i].Path == expectedChanges[i].Path { - if changes[i] != expectedChanges[i] { - t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) - } - } else if changes[i].Path < expectedChanges[i].Path { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } else { - t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) - } - } -} - -func TestApplyLayer(t *testing.T) { - src, err := ioutil.TempDir("", "docker-changes-test") - if err != nil { - t.Fatal(err) - } - createSampleDir(t, src) - defer os.RemoveAll(src) - dst := src + "-copy" - if err := copyDir(src, dst); err != nil { - t.Fatal(err) - } - mutateSampleDir(t, dst) - defer os.RemoveAll(dst) - - changes, err := ChangesDirs(dst, src) - if err != nil { - t.Fatal(err) - } - - layer, err := ExportChanges(dst, changes) - if err != nil { - t.Fatal(err) - } - - layerCopy, err := NewTempArchive(layer, "") - if err != nil { - t.Fatal(err) - } - - if _, err := ApplyLayer(src, layerCopy); err != nil { - t.Fatal(err) - } - - changes2, err := ChangesDirs(src, dst) - if err != nil { - t.Fatal(err) - } - - if len(changes2) != 0 { - t.Fatalf("Unexpected differences after reapplying mutation: %v", changes2) - } -} - -func TestChangesSizeWithNoChanges(t *testing.T) { - size := ChangesSize("/tmp", nil) - if size != 0 { - t.Fatalf("ChangesSizes with no changes should be 0, was %d", size) - } -} - -func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) { - changes := []Change{ - {Path: "deletedPath", Kind: ChangeDelete}, - } - size := ChangesSize("/tmp", changes) - if size != 0 { - t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) - } -} - -func TestChangesSize(t *testing.T) { - parentPath, err := ioutil.TempDir("", "docker-changes-test") - defer os.RemoveAll(parentPath) - addition := path.Join(parentPath, "addition") - if err := ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744); err != nil { - t.Fatal(err) - } - modification := path.Join(parentPath, "modification") - if err = ioutil.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744); err != nil { - t.Fatal(err) - } - changes := []Change{ - {Path: "addition", Kind: ChangeAdd}, - {Path: "modification", Kind: ChangeModify}, - } - size := ChangesSize(parentPath, changes) - if size != 6 { - t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) - } -} - -func checkChanges(expectedChanges, changes []Change, t *testing.T) { - sort.Sort(changesByPath(expectedChanges)) - sort.Sort(changesByPath(changes)) - for i := 0; i < max(len(changes), len(expectedChanges)); i++ { - if i >= len(expectedChanges) { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } - if i >= len(changes) { - t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) - } - if changes[i].Path == expectedChanges[i].Path { - if changes[i] != expectedChanges[i] { - t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) - } - } else if changes[i].Path < expectedChanges[i].Path { - t.Fatalf("unexpected change %s\n", changes[i].String()) - } else { - t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go deleted file mode 100644 index dd0b3236266..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go +++ /dev/null @@ -1,637 +0,0 @@ -package archive - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" -) - -func removeAllPaths(paths ...string) { - for _, path := range paths { - os.RemoveAll(path) - } -} - -func getTestTempDirs(t *testing.T) (tmpDirA, tmpDirB string) { - var err error - - if tmpDirA, err = ioutil.TempDir("", "archive-copy-test"); err != nil { - t.Fatal(err) - } - - if tmpDirB, err = ioutil.TempDir("", "archive-copy-test"); err != nil { - t.Fatal(err) - } - - return -} - -func isNotDir(err error) bool { - return strings.Contains(err.Error(), "not a directory") -} - -func joinTrailingSep(pathElements ...string) string { - joined := filepath.Join(pathElements...) - - return fmt.Sprintf("%s%c", joined, filepath.Separator) -} - -func fileContentsEqual(t *testing.T, filenameA, filenameB string) (err error) { - t.Logf("checking for equal file contents: %q and %q\n", filenameA, filenameB) - - fileA, err := os.Open(filenameA) - if err != nil { - return - } - defer fileA.Close() - - fileB, err := os.Open(filenameB) - if err != nil { - return - } - defer fileB.Close() - - hasher := sha256.New() - - if _, err = io.Copy(hasher, fileA); err != nil { - return - } - - hashA := hasher.Sum(nil) - hasher.Reset() - - if _, err = io.Copy(hasher, fileB); err != nil { - return - } - - hashB := hasher.Sum(nil) - - if !bytes.Equal(hashA, hashB) { - err = fmt.Errorf("file content hashes not equal - expected %s, got %s", hex.EncodeToString(hashA), hex.EncodeToString(hashB)) - } - - return -} - -func dirContentsEqual(t *testing.T, newDir, oldDir string) (err error) { - t.Logf("checking for equal directory contents: %q and %q\n", newDir, oldDir) - - var changes []Change - - if changes, err = ChangesDirs(newDir, oldDir); err != nil { - return - } - - if len(changes) != 0 { - err = fmt.Errorf("expected no changes between directories, but got: %v", changes) - } - - return -} - -func logDirContents(t *testing.T, dirPath string) { - logWalkedPaths := filepath.WalkFunc(func(path string, info os.FileInfo, err error) error { - if err != nil { - t.Errorf("stat error for path %q: %s", path, err) - return nil - } - - if info.IsDir() { - path = joinTrailingSep(path) - } - - t.Logf("\t%s", path) - - return nil - }) - - t.Logf("logging directory contents: %q", dirPath) - - if err := filepath.Walk(dirPath, logWalkedPaths); err != nil { - t.Fatal(err) - } -} - -func testCopyHelper(t *testing.T, srcPath, dstPath string) (err error) { - t.Logf("copying from %q to %q", srcPath, dstPath) - - return CopyResource(srcPath, dstPath) -} - -// Basic assumptions about SRC and DST: -// 1. SRC must exist. -// 2. If SRC ends with a trailing separator, it must be a directory. -// 3. DST parent directory must exist. -// 4. If DST exists as a file, it must not end with a trailing separator. - -// First get these easy error cases out of the way. - -// Test for error when SRC does not exist. -func TestCopyErrSrcNotExists(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - content, err := TarResource(filepath.Join(tmpDirA, "file1")) - if err == nil { - content.Close() - t.Fatal("expected IsNotExist error, but got nil instead") - } - - if !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } -} - -// Test for error when SRC ends in a trailing -// path separator but it exists as a file. -func TestCopyErrSrcNotDir(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - content, err := TarResource(joinTrailingSep(tmpDirA, "file1")) - if err == nil { - content.Close() - t.Fatal("expected IsNotDir error, but got nil instead") - } - - if !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } -} - -// Test for error when SRC is a valid file or directory, -// but the DST parent directory does not exist. -func TestCopyErrDstParentNotExists(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} - - // Try with a file source. - content, err := TarResource(srcInfo.Path) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - // Copy to a file whose parent does not exist. - if err = CopyTo(content, srcInfo, filepath.Join(tmpDirB, "fakeParentDir", "file1")); err == nil { - t.Fatal("expected IsNotExist error, but got nil instead") - } - - if !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } - - // Try with a directory source. - srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} - - content, err = TarResource(srcInfo.Path) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - // Copy to a directory whose parent does not exist. - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "fakeParentDir", "fakeDstDir")); err == nil { - t.Fatal("expected IsNotExist error, but got nil instead") - } - - if !os.IsNotExist(err) { - t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) - } -} - -// Test for error when DST ends in a trailing -// path separator but exists as a file. -func TestCopyErrDstNotDir(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - // Try with a file source. - srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} - - content, err := TarResource(srcInfo.Path) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { - t.Fatal("expected IsNotDir error, but got nil instead") - } - - if !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } - - // Try with a directory source. - srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} - - content, err = TarResource(srcInfo.Path) - if err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - defer content.Close() - - if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { - t.Fatal("expected IsNotDir error, but got nil instead") - } - - if !isNotDir(err) { - t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) - } -} - -// Possibilities are reduced to the remaining 10 cases: -// -// case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action -// =================================================================================================== -// A | no | - | no | - | no | create file -// B | no | - | no | - | yes | error -// C | no | - | yes | no | - | overwrite file -// D | no | - | yes | yes | - | create file in dst dir -// E | yes | no | no | - | - | create dir, copy contents -// F | yes | no | yes | no | - | error -// G | yes | no | yes | yes | - | copy dir and contents -// H | yes | yes | no | - | - | create dir, copy contents -// I | yes | yes | yes | no | - | error -// J | yes | yes | yes | yes | - | copy dir contents -// - -// A. SRC specifies a file and DST (no trailing path separator) doesn't -// exist. This should create a file with the name DST and copy the -// contents of the source file into it. -func TestCopyCaseA(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcPath := filepath.Join(tmpDirA, "file1") - dstPath := filepath.Join(tmpDirB, "itWorks.txt") - - var err error - - if err = testCopyHelper(t, srcPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } -} - -// B. SRC specifies a file and DST (with trailing path separator) doesn't -// exist. This should cause an error because the copy operation cannot -// create a directory when copying a single file. -func TestCopyCaseB(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcPath := filepath.Join(tmpDirA, "file1") - dstDir := joinTrailingSep(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcPath, dstDir); err == nil { - t.Fatal("expected ErrDirNotExists error, but got nil instead") - } - - if err != ErrDirNotExists { - t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) - } -} - -// C. SRC specifies a file and DST exists as a file. This should overwrite -// the file at DST with the contents of the source file. -func TestCopyCaseC(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcPath := filepath.Join(tmpDirA, "file1") - dstPath := filepath.Join(tmpDirB, "file2") - - var err error - - // Ensure they start out different. - if err = fileContentsEqual(t, srcPath, dstPath); err == nil { - t.Fatal("expected different file contents") - } - - if err = testCopyHelper(t, srcPath, dstPath); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } -} - -// D. SRC specifies a file and DST exists as a directory. This should place -// a copy of the source file inside it using the basename from SRC. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseD(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcPath := filepath.Join(tmpDirA, "file1") - dstDir := filepath.Join(tmpDirB, "dir1") - dstPath := filepath.Join(dstDir, "file1") - - var err error - - // Ensure that dstPath doesn't exist. - if _, err = os.Stat(dstPath); !os.IsNotExist(err) { - t.Fatalf("did not expect dstPath %q to exist", dstPath) - } - - if err = testCopyHelper(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir1") - - if err = testCopyHelper(t, srcPath, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = fileContentsEqual(t, srcPath, dstPath); err != nil { - t.Fatal(err) - } -} - -// E. SRC specifies a directory and DST does not exist. This should create a -// directory at DST and copy the contents of the SRC directory into the DST -// directory. Ensure this works whether DST has a trailing path separator or -// not. -func TestCopyCaseE(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } -} - -// F. SRC specifies a directory and DST exists as a file. This should cause an -// error as it is not possible to overwrite a file with a directory. -func TestCopyCaseF(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := filepath.Join(tmpDirA, "dir1") - dstFile := filepath.Join(tmpDirB, "file1") - - var err error - - if err = testCopyHelper(t, srcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } -} - -// G. SRC specifies a directory and DST exists as a directory. This should copy -// the SRC directory and all its contents to the DST directory. Ensure this -// works whether DST has a trailing path separator or not. -func TestCopyCaseG(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := filepath.Join(tmpDirA, "dir1") - dstDir := filepath.Join(tmpDirB, "dir2") - resultDir := filepath.Join(dstDir, "dir1") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, srcDir); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir2") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, resultDir, srcDir); err != nil { - t.Fatal(err) - } -} - -// H. SRC specifies a directory's contents only and DST does not exist. This -// should create a directory at DST and copy the contents of the SRC -// directory (but not the directory itself) into the DST directory. Ensure -// this works whether DST has a trailing path separator or not. -func TestCopyCaseH(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A with some sample files and directories. - createSampleDir(t, tmpDirA) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - dstDir := filepath.Join(tmpDirB, "testDir") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "testDir") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Log("dir contents not equal") - logDirContents(t, tmpDirA) - logDirContents(t, tmpDirB) - t.Fatal(err) - } -} - -// I. SRC specifies a directory's contents only and DST exists as a file. This -// should cause an error as it is not possible to overwrite a file with a -// directory. -func TestCopyCaseI(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - dstFile := filepath.Join(tmpDirB, "file1") - - var err error - - if err = testCopyHelper(t, srcDir, dstFile); err == nil { - t.Fatal("expected ErrCannotCopyDir error, but got nil instead") - } - - if err != ErrCannotCopyDir { - t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) - } -} - -// J. SRC specifies a directory's contents only and DST exists as a directory. -// This should copy the contents of the SRC directory (but not the directory -// itself) into the DST directory. Ensure this works whether DST has a -// trailing path separator or not. -func TestCopyCaseJ(t *testing.T) { - tmpDirA, tmpDirB := getTestTempDirs(t) - defer removeAllPaths(tmpDirA, tmpDirB) - - // Load A and B with some sample files and directories. - createSampleDir(t, tmpDirA) - createSampleDir(t, tmpDirB) - - srcDir := joinTrailingSep(tmpDirA, "dir1") + "." - dstDir := filepath.Join(tmpDirB, "dir5") - - var err error - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } - - // Now try again but using a trailing path separator for dstDir. - - if err = os.RemoveAll(dstDir); err != nil { - t.Fatalf("unable to remove dstDir: %s", err) - } - - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { - t.Fatalf("unable to make dstDir: %s", err) - } - - dstDir = joinTrailingSep(tmpDirB, "dir5") - - if err = testCopyHelper(t, srcDir, dstDir); err != nil { - t.Fatalf("unexpected error %T: %s", err, err) - } - - if err = dirContentsEqual(t, dstDir, srcDir); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go deleted file mode 100644 index 01ed4372805..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package archive - -import ( - "archive/tar" - "testing" -) - -func TestApplyLayerInvalidFilenames(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { - { - Name: "../victim/dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { - { - // Note the leading slash - Name: "/../victim/slash-dotdot", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidFilenames", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestApplyLayerInvalidHardlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeLink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeLink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (hardlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try reading victim/hello (hardlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // Try removing victim directory (hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeLink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidHardlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} - -func TestApplyLayerInvalidSymlink(t *testing.T) { - for i, headers := range [][]*tar.Header{ - { // try reading victim/hello (../) - { - Name: "dotdot", - Typeflag: tar.TypeSymlink, - Linkname: "../victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (/../) - { - Name: "slash-dotdot", - Typeflag: tar.TypeSymlink, - // Note the leading slash - Linkname: "/../victim/hello", - Mode: 0644, - }, - }, - { // try writing victim/file - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim/file", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "symlink", - Typeflag: tar.TypeSymlink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try reading victim/hello (symlink, hardlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "hardlink", - Typeflag: tar.TypeLink, - Linkname: "loophole-victim/hello", - Mode: 0644, - }, - }, - { // try removing victim directory (symlink) - { - Name: "loophole-victim", - Typeflag: tar.TypeSymlink, - Linkname: "../victim", - Mode: 0755, - }, - { - Name: "loophole-victim", - Typeflag: tar.TypeReg, - Mode: 0644, - }, - }, - } { - if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidSymlink", headers); err != nil { - t.Fatalf("i=%d. %v", i, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go deleted file mode 100644 index f5cacea8f0e..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "time" -) - -var testUntarFns = map[string]func(string, io.Reader) error{ - "untar": func(dest string, r io.Reader) error { - return Untar(r, dest, nil) - }, - "applylayer": func(dest string, r io.Reader) error { - _, err := ApplyLayer(dest, ArchiveReader(r)) - return err - }, -} - -// testBreakout is a helper function that, within the provided `tmpdir` directory, -// creates a `victim` folder with a generated `hello` file in it. -// `untar` extracts to a directory named `dest`, the tar file created from `headers`. -// -// Here are the tested scenarios: -// - removed `victim` folder (write) -// - removed files from `victim` folder (write) -// - new files in `victim` folder (write) -// - modified files in `victim` folder (write) -// - file in `dest` with same content as `victim/hello` (read) -// -// When using testBreakout make sure you cover one of the scenarios listed above. -func testBreakout(untarFn string, tmpdir string, headers []*tar.Header) error { - tmpdir, err := ioutil.TempDir("", tmpdir) - if err != nil { - return err - } - defer os.RemoveAll(tmpdir) - - dest := filepath.Join(tmpdir, "dest") - if err := os.Mkdir(dest, 0755); err != nil { - return err - } - - victim := filepath.Join(tmpdir, "victim") - if err := os.Mkdir(victim, 0755); err != nil { - return err - } - hello := filepath.Join(victim, "hello") - helloData, err := time.Now().MarshalText() - if err != nil { - return err - } - if err := ioutil.WriteFile(hello, helloData, 0644); err != nil { - return err - } - helloStat, err := os.Stat(hello) - if err != nil { - return err - } - - reader, writer := io.Pipe() - go func() { - t := tar.NewWriter(writer) - for _, hdr := range headers { - t.WriteHeader(hdr) - } - t.Close() - }() - - untar := testUntarFns[untarFn] - if untar == nil { - return fmt.Errorf("could not find untar function %q in testUntarFns", untarFn) - } - if err := untar(dest, reader); err != nil { - if _, ok := err.(breakoutError); !ok { - // If untar returns an error unrelated to an archive breakout, - // then consider this an unexpected error and abort. - return err - } - // Here, untar detected the breakout. - // Let's move on verifying that indeed there was no breakout. - fmt.Printf("breakoutError: %v\n", err) - } - - // Check victim folder - f, err := os.Open(victim) - if err != nil { - // codepath taken if victim folder was removed - return fmt.Errorf("archive breakout: error reading %q: %v", victim, err) - } - defer f.Close() - - // Check contents of victim folder - // - // We are only interested in getting 2 files from the victim folder, because if all is well - // we expect only one result, the `hello` file. If there is a second result, it cannot - // hold the same name `hello` and we assume that a new file got created in the victim folder. - // That is enough to detect an archive breakout. - names, err := f.Readdirnames(2) - if err != nil { - // codepath taken if victim is not a folder - return fmt.Errorf("archive breakout: error reading directory content of %q: %v", victim, err) - } - for _, name := range names { - if name != "hello" { - // codepath taken if new file was created in victim folder - return fmt.Errorf("archive breakout: new file %q", name) - } - } - - // Check victim/hello - f, err = os.Open(hello) - if err != nil { - // codepath taken if read permissions were removed - return fmt.Errorf("archive breakout: could not lstat %q: %v", hello, err) - } - defer f.Close() - b, err := ioutil.ReadAll(f) - if err != nil { - return err - } - fi, err := f.Stat() - if err != nil { - return err - } - if helloStat.IsDir() != fi.IsDir() || - // TODO: cannot check for fi.ModTime() change - helloStat.Mode() != fi.Mode() || - helloStat.Size() != fi.Size() || - !bytes.Equal(helloData, b) { - // codepath taken if hello has been modified - return fmt.Errorf("archive breakout: file %q has been modified. Contents: expected=%q, got=%q. FileInfo: expected=%#v, got=%#v", hello, helloData, b, helloStat, fi) - } - - // Check that nothing in dest/ has the same content as victim/hello. - // Since victim/hello was generated with time.Now(), it is safe to assume - // that any file whose content matches exactly victim/hello, managed somehow - // to access victim/hello. - return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { - if info.IsDir() { - if err != nil { - // skip directory if error - return filepath.SkipDir - } - // enter directory - return nil - } - if err != nil { - // skip file if error - return nil - } - b, err := ioutil.ReadFile(path) - if err != nil { - // Houston, we have a problem. Aborting (space)walk. - return err - } - if bytes.Equal(helloData, b) { - return fmt.Errorf("archive breakout: file %q has been accessed via %q", hello, path) - } - return nil - }) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go deleted file mode 100644 index 46ab36697a7..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package archive - -import ( - "archive/tar" - "bytes" - "io" - "testing" -) - -func TestGenerateEmptyFile(t *testing.T) { - archive, err := Generate("emptyFile") - if err != nil { - t.Fatal(err) - } - if archive == nil { - t.Fatal("The generated archive should not be nil.") - } - - expectedFiles := [][]string{ - {"emptyFile", ""}, - } - - tr := tar.NewReader(archive) - actualFiles := make([][]string, 0, 10) - i := 0 - for { - hdr, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - buf := new(bytes.Buffer) - buf.ReadFrom(tr) - content := buf.String() - actualFiles = append(actualFiles, []string{hdr.Name, content}) - i++ - } - if len(actualFiles) != len(expectedFiles) { - t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) - } - for i := 0; i < len(expectedFiles); i++ { - actual := actualFiles[i] - expected := expectedFiles[i] - if actual[0] != expected[0] { - t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) - } - if actual[1] != expected[1] { - t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) - } - } -} - -func TestGenerateWithContent(t *testing.T) { - archive, err := Generate("file", "content") - if err != nil { - t.Fatal(err) - } - if archive == nil { - t.Fatal("The generated archive should not be nil.") - } - - expectedFiles := [][]string{ - {"file", "content"}, - } - - tr := tar.NewReader(archive) - actualFiles := make([][]string, 0, 10) - i := 0 - for { - hdr, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - buf := new(bytes.Buffer) - buf.ReadFrom(tr) - content := buf.String() - actualFiles = append(actualFiles, []string{hdr.Name, content}) - i++ - } - if len(actualFiles) != len(expectedFiles) { - t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) - } - for i := 0; i < len(expectedFiles); i++ { - actual := actualFiles[i] - expected := expectedFiles[i] - if actual[0] != expected[0] { - t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) - } - if actual[1] != expected[1] { - t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go deleted file mode 100644 index b544ffbf2ed..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go +++ /dev/null @@ -1,402 +0,0 @@ -package fileutils - -import ( - "io/ioutil" - "os" - "path" - "path/filepath" - "testing" -) - -// CopyFile with invalid src -func TestCopyFileWithInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest")) - if err == nil { - t.Fatal("Should have fail to copy an invalid src file") - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes") - } - -} - -// CopyFile with invalid dest -func TestCopyFileWithInvalidDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - src := path.Join(tempFolder, "file") - err = ioutil.WriteFile(src, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path")) - if err == nil { - t.Fatal("Should have fail to copy an invalid src file") - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes") - } - -} - -// CopyFile with same src and dest -func TestCopyFileWithSameSrcAndDest(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - file := path.Join(tempFolder, "file") - err = ioutil.WriteFile(file, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(file, file) - if err != nil { - t.Fatal(err) - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes as it is the same file.") - } -} - -// CopyFile with same src and dest but path is different and not clean -func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - testFolder := path.Join(tempFolder, "test") - err = os.MkdirAll(testFolder, 0740) - if err != nil { - t.Fatal(err) - } - file := path.Join(testFolder, "file") - sameFile := testFolder + "/../test/file" - err = ioutil.WriteFile(file, []byte("content"), 0740) - if err != nil { - t.Fatal(err) - } - bytes, err := CopyFile(file, sameFile) - if err != nil { - t.Fatal(err) - } - if bytes != 0 { - t.Fatal("Should have written 0 bytes as it is the same file.") - } -} - -func TestCopyFile(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - defer os.RemoveAll(tempFolder) - if err != nil { - t.Fatal(err) - } - src := path.Join(tempFolder, "src") - dest := path.Join(tempFolder, "dest") - ioutil.WriteFile(src, []byte("content"), 0777) - ioutil.WriteFile(dest, []byte("destContent"), 0777) - bytes, err := CopyFile(src, dest) - if err != nil { - t.Fatal(err) - } - if bytes != 7 { - t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes) - } - actual, err := ioutil.ReadFile(dest) - if err != nil { - t.Fatal(err) - } - if string(actual) != "content" { - t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content") - } -} - -// Reading a symlink to a directory must return the directory -func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { - var err error - if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { - t.Errorf("failed to create directory: %s", err) - } - - if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil { - t.Errorf("failed to create symlink: %s", err) - } - - var path string - if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil { - t.Fatalf("failed to read symlink to directory: %s", err) - } - - if path != "/tmp/testReadSymlinkToExistingDirectory" { - t.Fatalf("symlink returned unexpected directory: %s", path) - } - - if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil { - t.Errorf("failed to remove temporary directory: %s", err) - } - - if err = os.Remove("/tmp/dirLinkTest"); err != nil { - t.Errorf("failed to remove symlink: %s", err) - } -} - -// Reading a non-existing symlink must fail -func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) { - var path string - var err error - if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil { - t.Fatalf("error expected for non-existing symlink") - } - - if path != "" { - t.Fatalf("expected empty path, but '%s' was returned", path) - } -} - -// Reading a symlink to a file must fail -func TestReadSymlinkedDirectoryToFile(t *testing.T) { - var err error - var file *os.File - - if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { - t.Fatalf("failed to create file: %s", err) - } - - file.Close() - - if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil { - t.Errorf("failed to create symlink: %s", err) - } - - var path string - if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil { - t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed") - } - - if path != "" { - t.Fatalf("path should've been empty: %s", path) - } - - if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil { - t.Errorf("failed to remove file: %s", err) - } - - if err = os.Remove("/tmp/fileLinkTest"); err != nil { - t.Errorf("failed to remove symlink: %s", err) - } -} - -func TestWildcardMatches(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*"}) - if match != true { - t.Errorf("failed to get a wildcard match, got %v", match) - } -} - -// A simple pattern match should return true. -func TestPatternMatches(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*.go"}) - if match != true { - t.Errorf("failed to get a match, got %v", match) - } -} - -// An exclusion followed by an inclusion should return true. -func TestExclusionPatternMatchesPatternBefore(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"}) - if match != true { - t.Errorf("failed to get true match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A folder pattern followed by an exception should return false. -func TestPatternMatchesFolderWildcardExclusions(t *testing.T) { - match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"}) - if match != false { - t.Errorf("failed to get a false match on exclusion pattern, got %v", match) - } -} - -// A pattern followed by an exclusion should return false. -func TestExclusionPatternMatchesPatternAfter(t *testing.T) { - match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"}) - if match != false { - t.Errorf("failed to get false match on exclusion pattern, got %v", match) - } -} - -// A filename evaluating to . should return false. -func TestExclusionPatternMatchesWholeDirectory(t *testing.T) { - match, _ := Matches(".", []string{"*.go"}) - if match != false { - t.Errorf("failed to get false match on ., got %v", match) - } -} - -// A single ! pattern should return an error. -func TestSingleExclamationError(t *testing.T) { - _, err := Matches("fileutils.go", []string{"!"}) - if err == nil { - t.Errorf("failed to get an error for a single exclamation point, got %v", err) - } -} - -// A string preceded with a ! should return true from Exclusion. -func TestExclusion(t *testing.T) { - exclusion := exclusion("!") - if !exclusion { - t.Errorf("failed to get true for a single !, got %v", exclusion) - } -} - -// Matches with no patterns -func TestMatchesWithNoPatterns(t *testing.T) { - matches, err := Matches("/any/path/there", []string{}) - if err != nil { - t.Fatal(err) - } - if matches { - t.Fatalf("Should not have match anything") - } -} - -// Matches with malformed patterns -func TestMatchesWithMalformedPatterns(t *testing.T) { - matches, err := Matches("/any/path/there", []string{"["}) - if err == nil { - t.Fatal("Should have failed because of a malformed syntax in the pattern") - } - if matches { - t.Fatalf("Should not have match anything") - } -} - -// An empty string should return true from Empty. -func TestEmpty(t *testing.T) { - empty := empty("") - if !empty { - t.Errorf("failed to get true for an empty string, got %v", empty) - } -} - -func TestCleanPatterns(t *testing.T) { - cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"}) - if len(cleaned) != 2 { - t.Errorf("expected 2 element slice, got %v", len(cleaned)) - } -} - -func TestCleanPatternsStripEmptyPatterns(t *testing.T) { - cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""}) - if len(cleaned) != 2 { - t.Errorf("expected 2 element slice, got %v", len(cleaned)) - } -} - -func TestCleanPatternsExceptionFlag(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) { - _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "}) - if !exceptions { - t.Errorf("expected exceptions to be true, got %v", exceptions) - } -} - -func TestCleanPatternsErrorSingleException(t *testing.T) { - _, _, _, err := CleanPatterns([]string{"!"}) - if err == nil { - t.Errorf("expected error on single exclamation point, got %v", err) - } -} - -func TestCleanPatternsFolderSplit(t *testing.T) { - _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"}) - if dirs[0][0] != "docs" { - t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1]) - } - if dirs[0][1] != "config" { - t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1]) - } -} - -func TestCreateIfNotExistsDir(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - - folderToCreate := filepath.Join(tempFolder, "tocreate") - - if err := CreateIfNotExists(folderToCreate, true); err != nil { - t.Fatal(err) - } - fileinfo, err := os.Stat(folderToCreate) - if err != nil { - t.Fatalf("Should have create a folder, got %v", err) - } - - if !fileinfo.IsDir() { - t.Fatalf("Should have been a dir, seems it's not") - } -} - -func TestCreateIfNotExistsFile(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempFolder) - - fileToCreate := filepath.Join(tempFolder, "file/to/create") - - if err := CreateIfNotExists(fileToCreate, false); err != nil { - t.Fatal(err) - } - fileinfo, err := os.Stat(fileToCreate) - if err != nil { - t.Fatalf("Should have create a file, got %v", err) - } - - if fileinfo.IsDir() { - t.Fatalf("Should have been a file, seems it's not") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go deleted file mode 100644 index 7a95cb2bd7d..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package homedir - -import ( - "path/filepath" - "testing" -) - -func TestGet(t *testing.T) { - home := Get() - if home == "" { - t.Fatal("returned home directory is empty") - } - - if !filepath.IsAbs(home) { - t.Fatalf("returned path is not absolute: %s", home) - } -} - -func TestGetShortcutString(t *testing.T) { - shortcut := GetShortcutString() - if shortcut == "" { - t.Fatal("returned shortcut string is empty") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go deleted file mode 100644 index 8968863296d..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package ioutils - -import "testing" - -func TestFprintfIfNotEmpty(t *testing.T) { - wc := NewWriteCounter(&NopWriter{}) - n, _ := FprintfIfNotEmpty(wc, "foo%s", "") - - if wc.Count != 0 || n != 0 { - t.Errorf("Wrong count: %v vs. %v vs. 0", wc.Count, n) - } - - n, _ = FprintfIfNotEmpty(wc, "foo%s", "bar") - if wc.Count != 6 || n != 6 { - t.Errorf("Wrong count: %v vs. %v vs. 6", wc.Count, n) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go deleted file mode 100644 index de495b56da4..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package ioutils - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - "testing" -) - -func TestMultiReadSeekerReadAll(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - expectedSize := int64(s1.Len() + s2.Len() + s3.Len()) - - b, err := ioutil.ReadAll(mr) - if err != nil { - t.Fatal(err) - } - - expected := "hello world 1hello world 2hello world 3" - if string(b) != expected { - t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) - } - - size, err := mr.Seek(0, os.SEEK_END) - if err != nil { - t.Fatal(err) - } - if size != expectedSize { - t.Fatalf("reader size does not match, got %d, expected %d", size, expectedSize) - } - - // Reset the position and read again - pos, err := mr.Seek(0, os.SEEK_SET) - if err != nil { - t.Fatal(err) - } - if pos != 0 { - t.Fatalf("expected position to be set to 0, got %d", pos) - } - - b, err = ioutil.ReadAll(mr) - if err != nil { - t.Fatal(err) - } - - if string(b) != expected { - t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) - } -} - -func TestMultiReadSeekerReadEach(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - var totalBytes int64 - for i, s := range []*strings.Reader{s1, s2, s3} { - sLen := int64(s.Len()) - buf := make([]byte, s.Len()) - expected := []byte(fmt.Sprintf("%s %d", str, i+1)) - - if _, err := mr.Read(buf); err != nil && err != io.EOF { - t.Fatal(err) - } - - if !bytes.Equal(buf, expected) { - t.Fatalf("expected %q to be %q", string(buf), string(expected)) - } - - pos, err := mr.Seek(0, os.SEEK_CUR) - if err != nil { - t.Fatalf("iteration: %d, error: %v", i+1, err) - } - - // check that the total bytes read is the current position of the seeker - totalBytes += sLen - if pos != totalBytes { - t.Fatalf("expected current position to be: %d, got: %d, iteration: %d", totalBytes, pos, i+1) - } - - // This tests not only that SEEK_SET and SEEK_CUR give the same values, but that the next iteration is in the expected position as well - newPos, err := mr.Seek(pos, os.SEEK_SET) - if err != nil { - t.Fatal(err) - } - if newPos != pos { - t.Fatalf("expected to get same position when calling SEEK_SET with value from SEEK_CUR, cur: %d, set: %d", pos, newPos) - } - } -} - -func TestMultiReadSeekerReadSpanningChunks(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - buf := make([]byte, s1.Len()+3) - _, err := mr.Read(buf) - if err != nil { - t.Fatal(err) - } - - // expected is the contents of s1 + 3 bytes from s2, ie, the `hel` at the end of this string - expected := "hello world 1hel" - if string(buf) != expected { - t.Fatalf("expected %s to be %s", string(buf), expected) - } -} - -func TestMultiReadSeekerNegativeSeek(t *testing.T) { - str := "hello world" - s1 := strings.NewReader(str + " 1") - s2 := strings.NewReader(str + " 2") - s3 := strings.NewReader(str + " 3") - mr := MultiReadSeeker(s1, s2, s3) - - s1Len := s1.Len() - s2Len := s2.Len() - s3Len := s3.Len() - - s, err := mr.Seek(int64(-1*s3.Len()), os.SEEK_END) - if err != nil { - t.Fatal(err) - } - if s != int64(s1Len+s2Len) { - t.Fatalf("expected %d to be %d", s, s1.Len()+s2.Len()) - } - - buf := make([]byte, s3Len) - if _, err := mr.Read(buf); err != nil && err != io.EOF { - t.Fatal(err) - } - expected := fmt.Sprintf("%s %d", str, 3) - if string(buf) != fmt.Sprintf("%s %d", str, 3) { - t.Fatalf("expected %q to be %q", string(buf), expected) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go deleted file mode 100644 index 0a39b6ec6a1..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package ioutils - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "strings" - "testing" -) - -// Implement io.Reader -type errorReader struct{} - -func (r *errorReader) Read(p []byte) (int, error) { - return 0, fmt.Errorf("Error reader always fail.") -} - -func TestReadCloserWrapperClose(t *testing.T) { - reader := strings.NewReader("A string reader") - wrapper := NewReadCloserWrapper(reader, func() error { - return fmt.Errorf("This will be called when closing") - }) - err := wrapper.Close() - if err == nil || !strings.Contains(err.Error(), "This will be called when closing") { - t.Fatalf("readCloserWrapper should have call the anonymous func and thus, fail.") - } -} - -func TestReaderErrWrapperReadOnError(t *testing.T) { - called := false - reader := &errorReader{} - wrapper := NewReaderErrWrapper(reader, func() { - called = true - }) - _, err := wrapper.Read([]byte{}) - if err == nil || !strings.Contains(err.Error(), "Error reader always fail.") { - t.Fatalf("readErrWrapper should returned an error") - } - if !called { - t.Fatalf("readErrWrapper should have call the anonymous function on failure") - } -} - -func TestReaderErrWrapperRead(t *testing.T) { - reader := strings.NewReader("a string reader.") - wrapper := NewReaderErrWrapper(reader, func() { - t.Fatalf("readErrWrapper should not have called the anonymous function") - }) - // Read 20 byte (should be ok with the string above) - num, err := wrapper.Read(make([]byte, 20)) - if err != nil { - t.Fatal(err) - } - if num != 16 { - t.Fatalf("readerErrWrapper should have read 16 byte, but read %d", num) - } -} - -func TestNewBufReaderWithDrainbufAndBuffer(t *testing.T) { - reader, writer := io.Pipe() - - drainBuffer := make([]byte, 1024) - buffer := bytes.Buffer{} - bufreader := NewBufReaderWithDrainbufAndBuffer(reader, drainBuffer, &buffer) - - // Write everything down to a Pipe - // Usually, a pipe should block but because of the buffered reader, - // the writes will go through - done := make(chan bool) - go func() { - writer.Write([]byte("hello world")) - writer.Close() - done <- true - }() - - // Drain the reader *after* everything has been written, just to verify - // it is indeed buffering - <-done - - output, err := ioutil.ReadAll(bufreader) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(output, []byte("hello world")) { - t.Error(string(output)) - } -} - -func TestBufReader(t *testing.T) { - reader, writer := io.Pipe() - bufreader := NewBufReader(reader) - - // Write everything down to a Pipe - // Usually, a pipe should block but because of the buffered reader, - // the writes will go through - done := make(chan bool) - go func() { - writer.Write([]byte("hello world")) - writer.Close() - done <- true - }() - - // Drain the reader *after* everything has been written, just to verify - // it is indeed buffering - <-done - output, err := ioutil.ReadAll(bufreader) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(output, []byte("hello world")) { - t.Error(string(output)) - } -} - -func TestBufReaderCloseWithNonReaderCloser(t *testing.T) { - reader := strings.NewReader("buffer") - bufreader := NewBufReader(reader) - - if err := bufreader.Close(); err != nil { - t.Fatal(err) - } - -} - -// implements io.ReadCloser -type simpleReaderCloser struct{} - -func (r *simpleReaderCloser) Read(p []byte) (n int, err error) { - return 0, nil -} - -func (r *simpleReaderCloser) Close() error { - return nil -} - -func TestBufReaderCloseWithReaderCloser(t *testing.T) { - reader := &simpleReaderCloser{} - bufreader := NewBufReader(reader) - - err := bufreader.Close() - if err != nil { - t.Fatal(err) - } - -} - -func TestHashData(t *testing.T) { - reader := strings.NewReader("hash-me") - actual, err := HashData(reader) - if err != nil { - t.Fatal(err) - } - expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" - if actual != expected { - t.Fatalf("Expecting %s, got %s", expected, actual) - } -} - -type repeatedReader struct { - readCount int - maxReads int - data []byte -} - -func newRepeatedReader(max int, data []byte) *repeatedReader { - return &repeatedReader{0, max, data} -} - -func (r *repeatedReader) Read(p []byte) (int, error) { - if r.readCount >= r.maxReads { - return 0, io.EOF - } - r.readCount++ - n := copy(p, r.data) - return n, nil -} - -func testWithData(data []byte, reads int) { - reader := newRepeatedReader(reads, data) - bufReader := NewBufReader(reader) - io.Copy(ioutil.Discard, bufReader) -} - -func Benchmark1M10BytesReads(b *testing.B) { - reads := 1000000 - readSize := int64(10) - data := make([]byte, readSize) - b.SetBytes(readSize * int64(reads)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - testWithData(data, reads) - } -} - -func Benchmark1M1024BytesReads(b *testing.B) { - reads := 1000000 - readSize := int64(1024) - data := make([]byte, readSize) - b.SetBytes(readSize * int64(reads)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - testWithData(data, reads) - } -} - -func Benchmark10k32KBytesReads(b *testing.B) { - reads := 10000 - readSize := int64(32 * 1024) - data := make([]byte, readSize) - b.SetBytes(readSize * int64(reads)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - testWithData(data, reads) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go deleted file mode 100644 index 564b1cd4f5f..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package ioutils - -import ( - "bytes" - "strings" - "testing" -) - -func TestWriteCloserWrapperClose(t *testing.T) { - called := false - writer := bytes.NewBuffer([]byte{}) - wrapper := NewWriteCloserWrapper(writer, func() error { - called = true - return nil - }) - if err := wrapper.Close(); err != nil { - t.Fatal(err) - } - if !called { - t.Fatalf("writeCloserWrapper should have call the anonymous function.") - } -} - -func TestNopWriteCloser(t *testing.T) { - writer := bytes.NewBuffer([]byte{}) - wrapper := NopWriteCloser(writer) - if err := wrapper.Close(); err != nil { - t.Fatal("NopWriteCloser always return nil on Close.") - } - -} - -func TestNopWriter(t *testing.T) { - nw := &NopWriter{} - l, err := nw.Write([]byte{'c'}) - if err != nil { - t.Fatal(err) - } - if l != 1 { - t.Fatalf("Expected 1 got %d", l) - } -} - -func TestWriteCounter(t *testing.T) { - dummy1 := "This is a dummy string." - dummy2 := "This is another dummy string." - totalLength := int64(len(dummy1) + len(dummy2)) - - reader1 := strings.NewReader(dummy1) - reader2 := strings.NewReader(dummy2) - - var buffer bytes.Buffer - wc := NewWriteCounter(&buffer) - - reader1.WriteTo(wc) - reader2.WriteTo(wc) - - if wc.Count != totalLength { - t.Errorf("Wrong count: %d vs. %d", wc.Count, totalLength) - } - - if buffer.String() != dummy1+dummy2 { - t.Error("Wrong message written") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/mflag/flag_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/mflag/flag_test.go deleted file mode 100644 index 85f32c8aa46..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/mflag/flag_test.go +++ /dev/null @@ -1,516 +0,0 @@ -// Copyright 2014-2015 The Docker & 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 mflag - -import ( - "bytes" - "fmt" - "os" - "sort" - "strings" - "testing" - "time" -) - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = NewFlagSet(os.Args[0], ContinueOnError) - Usage = usage -} -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - ResetForTesting(nil) - Bool([]string{"test_bool"}, false, "bool value") - Int([]string{"test_int"}, 0, "int value") - Int64([]string{"test_int64"}, 0, "int64 value") - Uint([]string{"test_uint"}, 0, "uint value") - Uint64([]string{"test_uint64"}, 0, "uint64 value") - String([]string{"test_string"}, "0", "string value") - Float64([]string{"test_float64"}, 0, "float64 value") - Duration([]string{"test_duration"}, 0, "time.Duration value") - - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - for _, name := range f.Names { - if len(name) > 5 && name[0:5] == "test_" { - m[name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", name) - } - } - } - } - VisitAll(visitor) - if len(m) != 8 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - desired = "1" - Visit(visitor) - if len(m) != 8 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { - for _, name := range f.Names { - flagNames = append(flagNames, name) - } - }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestGet(t *testing.T) { - ResetForTesting(nil) - Bool([]string{"test_bool"}, true, "bool value") - Int([]string{"test_int"}, 1, "int value") - Int64([]string{"test_int64"}, 2, "int64 value") - Uint([]string{"test_uint"}, 3, "uint value") - Uint64([]string{"test_uint64"}, 4, "uint64 value") - String([]string{"test_string"}, "5", "string value") - Float64([]string{"test_float64"}, 6, "float64 value") - Duration([]string{"test_duration"}, 7, "time.Duration value") - - visitor := func(f *Flag) { - for _, name := range f.Names { - if len(name) > 5 && name[0:5] == "test_" { - g, ok := f.Value.(Getter) - if !ok { - t.Errorf("Visit: value does not satisfy Getter: %T", f.Value) - return - } - switch name { - case "test_bool": - ok = g.Get() == true - case "test_int": - ok = g.Get() == int(1) - case "test_int64": - ok = g.Get() == int64(2) - case "test_uint": - ok = g.Get() == uint(3) - case "test_uint64": - ok = g.Get() == uint64(4) - case "test_string": - ok = g.Get() == "5" - case "test_float64": - ok = g.Get() == float64(6) - case "test_duration": - ok = g.Get() == time.Duration(7) - } - if !ok { - t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), name) - } - } - } - } - VisitAll(visitor) -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool([]string{"bool"}, false, "bool value") - bool2Flag := f.Bool([]string{"bool2"}, false, "bool2 value") - f.Bool([]string{"bool3"}, false, "bool3 value") - bool4Flag := f.Bool([]string{"bool4"}, false, "bool4 value") - intFlag := f.Int([]string{"-int"}, 0, "int value") - int64Flag := f.Int64([]string{"-int64"}, 0, "int64 value") - uintFlag := f.Uint([]string{"uint"}, 0, "uint value") - uint64Flag := f.Uint64([]string{"-uint64"}, 0, "uint64 value") - stringFlag := f.String([]string{"string"}, "0", "string value") - f.String([]string{"string2"}, "0", "string2 value") - singleQuoteFlag := f.String([]string{"squote"}, "", "single quoted value") - doubleQuoteFlag := f.String([]string{"dquote"}, "", "double quoted value") - mixedQuoteFlag := f.String([]string{"mquote"}, "", "mixed quoted value") - mixed2QuoteFlag := f.String([]string{"mquote2"}, "", "mixed2 quoted value") - nestedQuoteFlag := f.String([]string{"nquote"}, "", "nested quoted value") - nested2QuoteFlag := f.String([]string{"nquote2"}, "", "nested2 quoted value") - float64Flag := f.Float64([]string{"float64"}, 0, "float64 value") - durationFlag := f.Duration([]string{"duration"}, 5*time.Second, "time.Duration value") - extra := "one-extra-argument" - args := []string{ - "-bool", - "-bool2=true", - "-bool4=false", - "--int", "22", - "--int64", "0x23", - "-uint", "24", - "--uint64", "25", - "-string", "hello", - "-squote='single'", - `-dquote="double"`, - `-mquote='mixed"`, - `-mquote2="mixed2'`, - `-nquote="'single nested'"`, - `-nquote2='"double nested"'`, - "-float64", "2718e28", - "-duration", "2m", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if !f.IsSet("bool2") { - t.Error("bool2 should be marked as set") - } - if f.IsSet("bool3") { - t.Error("bool3 should not be marked as set") - } - if !f.IsSet("bool4") { - t.Error("bool4 should be marked as set") - } - if *bool4Flag != false { - t.Error("bool4 flag should be false, is ", *bool4Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if !f.IsSet("string") { - t.Error("string flag should be marked as set") - } - if f.IsSet("string2") { - t.Error("string2 flag should not be marked as set") - } - if *singleQuoteFlag != "single" { - t.Error("single quote string flag should be `single`, is ", *singleQuoteFlag) - } - if *doubleQuoteFlag != "double" { - t.Error("double quote string flag should be `double`, is ", *doubleQuoteFlag) - } - if *mixedQuoteFlag != `'mixed"` { - t.Error("mixed quote string flag should be `'mixed\"`, is ", *mixedQuoteFlag) - } - if *mixed2QuoteFlag != `"mixed2'` { - t.Error("mixed2 quote string flag should be `\"mixed2'`, is ", *mixed2QuoteFlag) - } - if *nestedQuoteFlag != "'single nested'" { - t.Error("nested quote string flag should be `'single nested'`, is ", *nestedQuoteFlag) - } - if *nested2QuoteFlag != `"double nested"` { - t.Error("double quote string flag should be `\"double nested\"`, is ", *nested2QuoteFlag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func testPanic(f *FlagSet, t *testing.T) { - f.Int([]string{"-int"}, 0, "int value") - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - args := []string{ - "-int", "21", - } - f.Parse(args) -} - -func TestParsePanic(t *testing.T) { - ResetForTesting(func() {}) - testPanic(CommandLine, t) -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(CommandLine, t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.Var(&v, []string{"v"}, "usage") - if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -// Declare a user-defined boolean flag type. -type boolFlagVar struct { - count int -} - -func (b *boolFlagVar) String() string { - return fmt.Sprintf("%d", b.count) -} - -func (b *boolFlagVar) Set(value string) error { - if value == "true" { - b.count++ - } - return nil -} - -func (b *boolFlagVar) IsBoolFlag() bool { - return b.count < 4 -} - -func TestUserDefinedBool(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var b boolFlagVar - var err error - flags.Var(&b, []string{"b"}, "usage") - if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil { - if b.count < 4 { - t.Error(err) - } - } - - if b.count != 4 { - t.Errorf("want: %d; got: %d", 4, b.count) - } - - if err == nil { - t.Error("expected error; got none") - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"-unknown"}) - if out := buf.String(); !strings.Contains(out, "-unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"} - before := Bool([]string{"before"}, false, "") - if err := CommandLine.Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = Args() - after := Bool([]string{"after"}, false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, []string{"flag"}, false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"-flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by -flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"-help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, []string{"help"}, false, "help flag") - helpCalled = false - err = fs.Parse([]string{"-help"}) - if err != nil { - t.Fatal("expected no error for defined -help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -// Test the flag count functions. -func TestFlagCounts(t *testing.T) { - fs := NewFlagSet("help test", ContinueOnError) - var flag bool - fs.BoolVar(&flag, []string{"flag1"}, false, "regular flag") - fs.BoolVar(&flag, []string{"#deprecated1"}, false, "regular flag") - fs.BoolVar(&flag, []string{"f", "flag2"}, false, "regular flag") - fs.BoolVar(&flag, []string{"#d", "#deprecated2"}, false, "regular flag") - fs.BoolVar(&flag, []string{"flag3"}, false, "regular flag") - fs.BoolVar(&flag, []string{"g", "#flag4", "-flag4"}, false, "regular flag") - - if fs.FlagCount() != 6 { - t.Fatal("FlagCount wrong. ", fs.FlagCount()) - } - if fs.FlagCountUndeprecated() != 4 { - t.Fatal("FlagCountUndeprecated wrong. ", fs.FlagCountUndeprecated()) - } - if fs.NFlag() != 0 { - t.Fatal("NFlag wrong. ", fs.NFlag()) - } - err := fs.Parse([]string{"-fd", "-g", "-flag4"}) - if err != nil { - t.Fatal("expected no error for defined -help; got ", err) - } - if fs.NFlag() != 4 { - t.Fatal("NFlag wrong. ", fs.NFlag()) - } -} - -// Show up bug in sortFlags -func TestSortFlags(t *testing.T) { - fs := NewFlagSet("help TestSortFlags", ContinueOnError) - - var err error - - var b bool - fs.BoolVar(&b, []string{"b", "-banana"}, false, "usage") - - err = fs.Parse([]string{"--banana=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - count := 0 - - fs.VisitAll(func(flag *Flag) { - count++ - if flag == nil { - t.Fatal("VisitAll should not return a nil flag") - } - }) - flagcount := fs.FlagCount() - if flagcount != count { - t.Fatalf("FlagCount (%d) != number (%d) of elements visited", flagcount, count) - } - // Make sure its idempotent - if flagcount != fs.FlagCount() { - t.Fatalf("FlagCount (%d) != fs.FlagCount() (%d) of elements visited", flagcount, fs.FlagCount()) - } - - count = 0 - fs.Visit(func(flag *Flag) { - count++ - if flag == nil { - t.Fatal("Visit should not return a nil flag") - } - }) - nflag := fs.NFlag() - if nflag != count { - t.Fatalf("NFlag (%d) != number (%d) of elements visited", nflag, count) - } - if nflag != fs.NFlag() { - t.Fatalf("NFlag (%d) != fs.NFlag() (%d) of elements visited", nflag, fs.NFlag()) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/parsers/parsers_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/parsers/parsers_test.go deleted file mode 100644 index 903c66afb49..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/parsers/parsers_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package parsers - -import ( - "strings" - "testing" -) - -func TestParseHost(t *testing.T) { - var ( - defaultHTTPHost = "127.0.0.1" - defaultUnix = "/var/run/docker.sock" - ) - invalids := map[string]string{ - "0.0.0.0": "Invalid bind address format: 0.0.0.0", - "tcp://": "Invalid proto, expected tcp: ", - "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", - "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", - "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", - "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", - } - valids := map[string]string{ - "0.0.0.1:5555": "tcp://0.0.0.1:5555", - "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", - ":6666": "tcp://127.0.0.1:6666", - ":6666/path": "tcp://127.0.0.1:6666/path", - "tcp://:7777": "tcp://127.0.0.1:7777", - "tcp://:7777/path": "tcp://127.0.0.1:7777/path", - "": "unix:///var/run/docker.sock", - "unix:///run/docker.sock": "unix:///run/docker.sock", - "unix://": "unix:///var/run/docker.sock", - "fd://": "fd://", - "fd://something": "fd://something", - } - for invalidAddr, expectedError := range invalids { - if addr, err := ParseHost(defaultHTTPHost, defaultUnix, invalidAddr); err == nil || err.Error() != expectedError { - t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) - } - } - for validAddr, expectedAddr := range valids { - if addr, err := ParseHost(defaultHTTPHost, defaultUnix, validAddr); err != nil || addr != expectedAddr { - t.Errorf("%v -> expected %v, got %v", validAddr, expectedAddr, addr) - } - } -} - -func TestParseInvalidUnixAddrInvalid(t *testing.T) { - if _, err := ParseUnixAddr("unix://tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { - t.Fatalf("Expected an error, got %v", err) - } -} - -func TestParseRepositoryTag(t *testing.T) { - if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "root" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "root", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("user/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "user/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "user/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } - if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag) - } - if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" { - t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag) - } - if repo, digest := ParseRepositoryTag("url:5000/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "url:5000/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { - t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "url:5000/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) - } -} - -func TestParsePortMapping(t *testing.T) { - if _, err := PartParser("ip:public:private", "192.168.1.1:80"); err == nil { - t.Fatalf("Expected an error, got %v", err) - } - data, err := PartParser("ip:public:private", "192.168.1.1:80:8080") - if err != nil { - t.Fatal(err) - } - - if len(data) != 3 { - t.FailNow() - } - if data["ip"] != "192.168.1.1" { - t.Fail() - } - if data["public"] != "80" { - t.Fail() - } - if data["private"] != "8080" { - t.Fail() - } -} - -func TestParseKeyValueOpt(t *testing.T) { - invalids := map[string]string{ - "": "Unable to parse key/value option: ", - "key": "Unable to parse key/value option: key", - } - for invalid, expectedError := range invalids { - if _, _, err := ParseKeyValueOpt(invalid); err == nil || err.Error() != expectedError { - t.Fatalf("Expected error %v for %v, got %v", expectedError, invalid, err) - } - } - valids := map[string][]string{ - "key=value": {"key", "value"}, - " key = value ": {"key", "value"}, - "key=value1=value2": {"key", "value1=value2"}, - " key = value1 = value2 ": {"key", "value1 = value2"}, - } - for valid, expectedKeyValue := range valids { - key, value, err := ParseKeyValueOpt(valid) - if err != nil { - t.Fatal(err) - } - if key != expectedKeyValue[0] || value != expectedKeyValue[1] { - t.Fatalf("Expected {%v: %v} got {%v: %v}", expectedKeyValue[0], expectedKeyValue[1], key, value) - } - } -} - -func TestParsePortRange(t *testing.T) { - if start, end, err := ParsePortRange("8000-8080"); err != nil || start != 8000 || end != 8080 { - t.Fatalf("Error: %s or Expecting {start,end} values {8000,8080} but found {%d,%d}.", err, start, end) - } -} - -func TestParsePortRangeEmpty(t *testing.T) { - if _, _, err := ParsePortRange(""); err == nil || err.Error() != "Empty string specified for ports." { - t.Fatalf("Expected error 'Empty string specified for ports.', got %v", err) - } -} - -func TestParsePortRangeWithNoRange(t *testing.T) { - start, end, err := ParsePortRange("8080") - if err != nil { - t.Fatal(err) - } - if start != 8080 || end != 8080 { - t.Fatalf("Expected start and end to be the same and equal to 8080, but were %v and %v", start, end) - } -} - -func TestParsePortRangeIncorrectRange(t *testing.T) { - if _, _, err := ParsePortRange("9000-8080"); err == nil || !strings.Contains(err.Error(), "Invalid range specified for the Port") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectEndRange(t *testing.T) { - if _, _, err := ParsePortRange("8000-a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("8000-30a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParsePortRangeIncorrectStartRange(t *testing.T) { - if _, _, err := ParsePortRange("a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } - - if _, _, err := ParsePortRange("30a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { - t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) - } -} - -func TestParseLink(t *testing.T) { - name, alias, err := ParseLink("name:alias") - if err != nil { - t.Fatalf("Expected not to error out on a valid name:alias format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "alias" { - t.Fatalf("Link alias should have been alias, got %s instead", alias) - } - // short format definition - name, alias, err = ParseLink("name") - if err != nil { - t.Fatalf("Expected not to error out on a valid name only format but got: %v", err) - } - if name != "name" { - t.Fatalf("Link name should have been name, got %s instead", name) - } - if alias != "name" { - t.Fatalf("Link alias should have been name, got %s instead", alias) - } - // empty string link definition is not allowed - if _, _, err := ParseLink(""); err == nil || !strings.Contains(err.Error(), "empty string specified for links") { - t.Fatalf("Expected error 'empty string specified for links' but got: %v", err) - } - // more than two colons are not allowed - if _, _, err := ParseLink("link:alias:wrong"); err == nil || !strings.Contains(err.Error(), "bad format for links: link:alias:wrong") { - t.Fatalf("Expected error 'bad format for links: link:alias:wrong' but got: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go deleted file mode 100644 index 78689800b40..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package pools - -import ( - "bufio" - "bytes" - "io" - "strings" - "testing" -) - -func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) { - reader := BufioReader32KPool.Get(nil) - if reader == nil { - t.Fatalf("BufioReaderPool should have create a bufio.Reader but did not.") - } -} - -func TestBufioReaderPoolPutAndGet(t *testing.T) { - sr := bufio.NewReader(strings.NewReader("foobar")) - reader := BufioReader32KPool.Get(sr) - if reader == nil { - t.Fatalf("BufioReaderPool should not return a nil reader.") - } - // verify the first 3 byte - buf1 := make([]byte, 3) - _, err := reader.Read(buf1) - if err != nil { - t.Fatal(err) - } - if actual := string(buf1); actual != "foo" { - t.Fatalf("The first letter should have been 'foo' but was %v", actual) - } - BufioReader32KPool.Put(reader) - // Try to read the next 3 bytes - _, err = sr.Read(make([]byte, 3)) - if err == nil || err != io.EOF { - t.Fatalf("The buffer should have been empty, issue an EOF error.") - } -} - -type simpleReaderCloser struct { - io.Reader - closed bool -} - -func (r *simpleReaderCloser) Close() error { - r.closed = true - return nil -} - -func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) { - br := bufio.NewReader(strings.NewReader("")) - sr := &simpleReaderCloser{ - Reader: strings.NewReader("foobar"), - closed: false, - } - reader := BufioReader32KPool.NewReadCloserWrapper(br, sr) - if reader == nil { - t.Fatalf("NewReadCloserWrapper should not return a nil reader.") - } - // Verify the content of reader - buf := make([]byte, 3) - _, err := reader.Read(buf) - if err != nil { - t.Fatal(err) - } - if actual := string(buf); actual != "foo" { - t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual) - } - reader.Close() - // Read 3 more bytes "bar" - _, err = reader.Read(buf) - if err != nil { - t.Fatal(err) - } - if actual := string(buf); actual != "bar" { - t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual) - } - if !sr.closed { - t.Fatalf("The ReaderCloser should have been closed, it is not.") - } -} - -func TestBufioWriterPoolGetWithNoReaderShouldCreateOne(t *testing.T) { - writer := BufioWriter32KPool.Get(nil) - if writer == nil { - t.Fatalf("BufioWriterPool should have create a bufio.Writer but did not.") - } -} - -func TestBufioWriterPoolPutAndGet(t *testing.T) { - buf := new(bytes.Buffer) - bw := bufio.NewWriter(buf) - writer := BufioWriter32KPool.Get(bw) - if writer == nil { - t.Fatalf("BufioReaderPool should not return a nil writer.") - } - written, err := writer.Write([]byte("foobar")) - if err != nil { - t.Fatal(err) - } - if written != 6 { - t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) - } - // Make sure we Flush all the way ? - writer.Flush() - bw.Flush() - if len(buf.Bytes()) != 6 { - t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes())) - } - // Reset the buffer - buf.Reset() - BufioWriter32KPool.Put(writer) - // Try to write something - written, err = writer.Write([]byte("barfoo")) - if err != nil { - t.Fatal(err) - } - // If we now try to flush it, it should panic (the writer is nil) - // recover it - defer func() { - if r := recover(); r == nil { - t.Fatal("Trying to flush the writter should have 'paniced', did not.") - } - }() - writer.Flush() -} - -type simpleWriterCloser struct { - io.Writer - closed bool -} - -func (r *simpleWriterCloser) Close() error { - r.closed = true - return nil -} - -func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) { - buf := new(bytes.Buffer) - bw := bufio.NewWriter(buf) - sw := &simpleWriterCloser{ - Writer: new(bytes.Buffer), - closed: false, - } - bw.Flush() - writer := BufioWriter32KPool.NewWriteCloserWrapper(bw, sw) - if writer == nil { - t.Fatalf("BufioReaderPool should not return a nil writer.") - } - written, err := writer.Write([]byte("foobar")) - if err != nil { - t.Fatal(err) - } - if written != 6 { - t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) - } - writer.Close() - if !sw.closed { - t.Fatalf("The ReaderCloser should have been closed, it is not.") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go deleted file mode 100644 index a9fd73a49ed..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package stdcopy - -import ( - "bytes" - "io/ioutil" - "strings" - "testing" -) - -func TestNewStdWriter(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - if writer == nil { - t.Fatalf("NewStdWriter with an invalid StdType should not return nil.") - } -} - -func TestWriteWithUnitializedStdWriter(t *testing.T) { - writer := StdWriter{ - Writer: nil, - prefix: Stdout, - sizeBuf: make([]byte, 4), - } - n, err := writer.Write([]byte("Something here")) - if n != 0 || err == nil { - t.Fatalf("Should fail when given an uncomplete or uninitialized StdWriter") - } -} - -func TestWriteWithNilBytes(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - n, err := writer.Write(nil) - if err != nil { - t.Fatalf("Shouldn't have fail when given no data") - } - if n > 0 { - t.Fatalf("Write should have written 0 byte, but has written %d", n) - } -} - -func TestWrite(t *testing.T) { - writer := NewStdWriter(ioutil.Discard, Stdout) - data := []byte("Test StdWrite.Write") - n, err := writer.Write(data) - if err != nil { - t.Fatalf("Error while writing with StdWrite") - } - if n != len(data) { - t.Fatalf("Write should have writen %d byte but wrote %d.", len(data), n) - } -} - -func TestStdCopyWithInvalidInputHeader(t *testing.T) { - dstOut := NewStdWriter(ioutil.Discard, Stdout) - dstErr := NewStdWriter(ioutil.Discard, Stderr) - src := strings.NewReader("Invalid input") - _, err := StdCopy(dstOut, dstErr, src) - if err == nil { - t.Fatal("StdCopy with invalid input header should fail.") - } -} - -func TestStdCopyWithCorruptedPrefix(t *testing.T) { - data := []byte{0x01, 0x02, 0x03} - src := bytes.NewReader(data) - written, err := StdCopy(nil, nil, src) - if err != nil { - t.Fatalf("StdCopy should not return an error with corrupted prefix.") - } - if written != 0 { - t.Fatalf("StdCopy should have written 0, but has written %d", written) - } -} - -func BenchmarkWrite(b *testing.B) { - w := NewStdWriter(ioutil.Discard, Stdout) - data := []byte("Test line for testing stdwriter performance\n") - data = bytes.Repeat(data, 100) - b.SetBytes(int64(len(data))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := w.Write(data); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_test.go deleted file mode 100644 index 6bac492eb1a..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package system - -import ( - "os" - "testing" -) - -// TestLstat tests Lstat for existing and non existing files -func TestLstat(t *testing.T) { - file, invalid, _, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - statFile, err := Lstat(file) - if err != nil { - t.Fatal(err) - } - if statFile == nil { - t.Fatal("returned empty stat for existing file") - } - - statInvalid, err := Lstat(invalid) - if err == nil { - t.Fatal("did not return error for non-existing file") - } - if statInvalid != nil { - t.Fatal("returned non-nil stat for non-existing file") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux_test.go deleted file mode 100644 index 87830ccb2e2..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package system - -import ( - "strings" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units" -) - -// TestMemInfo tests parseMemInfo with a static meminfo string -func TestMemInfo(t *testing.T) { - const input = ` - MemTotal: 1 kB - MemFree: 2 kB - SwapTotal: 3 kB - SwapFree: 4 kB - Malformed1: - Malformed2: 1 - Malformed3: 2 MB - Malformed4: X kB - ` - meminfo, err := parseMemInfo(strings.NewReader(input)) - if err != nil { - t.Fatal(err) - } - if meminfo.MemTotal != 1*units.KiB { - t.Fatalf("Unexpected MemTotal: %d", meminfo.MemTotal) - } - if meminfo.MemFree != 2*units.KiB { - t.Fatalf("Unexpected MemFree: %d", meminfo.MemFree) - } - if meminfo.SwapTotal != 3*units.KiB { - t.Fatalf("Unexpected SwapTotal: %d", meminfo.SwapTotal) - } - if meminfo.SwapFree != 4*units.KiB { - t.Fatalf("Unexpected SwapFree: %d", meminfo.SwapFree) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_test.go deleted file mode 100644 index 4534129200e..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package system - -import ( - "os" - "syscall" - "testing" -) - -// TestFromStatT tests fromStatT for a tempfile -func TestFromStatT(t *testing.T) { - file, _, _, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - stat := &syscall.Stat_t{} - err := syscall.Lstat(file, stat) - - s, err := fromStatT(stat) - if err != nil { - t.Fatal(err) - } - - if stat.Mode != s.Mode() { - t.Fatal("got invalid mode") - } - if stat.Uid != s.Uid() { - t.Fatal("got invalid uid") - } - if stat.Gid != s.Gid() { - t.Fatal("got invalid gid") - } - if stat.Rdev != s.Rdev() { - t.Fatal("got invalid rdev") - } - if stat.Mtim != s.Mtim() { - t.Fatal("got invalid mtim") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_test.go deleted file mode 100644 index 350cce1ead4..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package system - -import ( - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" -) - -// prepareFiles creates files for testing in the temp directory -func prepareFiles(t *testing.T) (string, string, string, string) { - dir, err := ioutil.TempDir("", "docker-system-test") - if err != nil { - t.Fatal(err) - } - - file := filepath.Join(dir, "exist") - if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { - t.Fatal(err) - } - - invalid := filepath.Join(dir, "doesnt-exist") - - symlink := filepath.Join(dir, "symlink") - if err := os.Symlink(file, symlink); err != nil { - t.Fatal(err) - } - - return file, invalid, symlink, dir -} - -func TestLUtimesNano(t *testing.T) { - file, invalid, symlink, dir := prepareFiles(t) - defer os.RemoveAll(dir) - - before, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - - ts := []syscall.Timespec{{0, 0}, {0, 0}} - if err := LUtimesNano(symlink, ts); err != nil { - t.Fatal(err) - } - - symlinkInfo, err := os.Lstat(symlink) - if err != nil { - t.Fatal(err) - } - if before.ModTime().Unix() == symlinkInfo.ModTime().Unix() { - t.Fatal("The modification time of the symlink should be different") - } - - fileInfo, err := os.Stat(file) - if err != nil { - t.Fatal(err) - } - if before.ModTime().Unix() != fileInfo.ModTime().Unix() { - t.Fatal("The modification time of the file should be same") - } - - if err := LUtimesNano(invalid, ts); err == nil { - t.Fatal("Doesn't return an error on a non-existing file") - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit/ulimit_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit/ulimit_test.go deleted file mode 100644 index 1e8c881f51d..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit/ulimit_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package ulimit - -import "testing" - -func TestParseValid(t *testing.T) { - u1 := &Ulimit{"nofile", 1024, 512} - if u2, _ := Parse("nofile=512:1024"); *u1 != *u2 { - t.Fatalf("expected %q, but got %q", u1, u2) - } -} - -func TestParseInvalidLimitType(t *testing.T) { - if _, err := Parse("notarealtype=1024:1024"); err == nil { - t.Fatalf("expected error on invalid ulimit type") - } -} - -func TestParseBadFormat(t *testing.T) { - if _, err := Parse("nofile:1024:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := Parse("nofile"); err == nil { - t.Fatal("expected error on bad syntax") - } - - if _, err := Parse("nofile="); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := Parse("nofile=:"); err == nil { - t.Fatal("expected error on bad syntax") - } - if _, err := Parse("nofile=:1024"); err == nil { - t.Fatal("expected error on bad syntax") - } -} - -func TestParseHardLessThanSoft(t *testing.T) { - if _, err := Parse("nofile:1024:1"); err == nil { - t.Fatal("expected error on hard limit less than soft limit") - } -} - -func TestParseInvalidValueType(t *testing.T) { - if _, err := Parse("nofile:asdf"); err == nil { - t.Fatal("expected error on bad value type") - } -} - -func TestStringOutput(t *testing.T) { - u := &Ulimit{"nofile", 1024, 512} - if s := u.String(); s != "nofile=512:1024" { - t.Fatal("expected String to return nofile=512:1024, but got", s) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/duration_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/duration_test.go deleted file mode 100644 index fcfb6b7bbd7..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/duration_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package units - -import ( - "testing" - "time" -) - -func TestHumanDuration(t *testing.T) { - // Useful duration abstractions - day := 24 * time.Hour - week := 7 * day - month := 30 * day - year := 365 * day - - assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) - assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) - assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) - assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) - assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) - assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) - assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) - assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) - assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) - assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) - assertEquals(t, "2 days", HumanDuration(2*day)) - assertEquals(t, "7 days", HumanDuration(7*day)) - assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) - assertEquals(t, "2 weeks", HumanDuration(2*week)) - assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) - assertEquals(t, "3 weeks", HumanDuration(3*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week)) - assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) - assertEquals(t, "4 weeks", HumanDuration(1*month)) - assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) - assertEquals(t, "8 weeks", HumanDuration(2*month)) - assertEquals(t, "3 months", HumanDuration(3*month+1*week)) - assertEquals(t, "5 months", HumanDuration(5*month+2*week)) - assertEquals(t, "13 months", HumanDuration(13*month)) - assertEquals(t, "23 months", HumanDuration(23*month)) - assertEquals(t, "24 months", HumanDuration(24*month)) - assertEquals(t, "2 years", HumanDuration(24*month+2*week)) - assertEquals(t, "3 years", HumanDuration(3*year+2*month)) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/size_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/size_test.go deleted file mode 100644 index 67c3b81e6b4..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/units/size_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package units - -import ( - "reflect" - "runtime" - "strings" - "testing" -) - -func TestBytesSize(t *testing.T) { - assertEquals(t, "1 KiB", BytesSize(1024)) - assertEquals(t, "1 MiB", BytesSize(1024*1024)) - assertEquals(t, "1 MiB", BytesSize(1048576)) - assertEquals(t, "2 MiB", BytesSize(2*MiB)) - assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) - assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) - assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) -} - -func TestHumanSize(t *testing.T) { - assertEquals(t, "1 kB", HumanSize(1000)) - assertEquals(t, "1.024 kB", HumanSize(1024)) - assertEquals(t, "1 MB", HumanSize(1000000)) - assertEquals(t, "1.049 MB", HumanSize(1048576)) - assertEquals(t, "2 MB", HumanSize(2*MB)) - assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) - assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) - assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) -} - -func TestFromHumanSize(t *testing.T) { - assertSuccessEquals(t, 32, FromHumanSize, "32") - assertSuccessEquals(t, 32, FromHumanSize, "32b") - assertSuccessEquals(t, 32, FromHumanSize, "32B") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") - assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") - assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") - assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") - assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") - assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") - - assertError(t, FromHumanSize, "") - assertError(t, FromHumanSize, "hello") - assertError(t, FromHumanSize, "-32") - assertError(t, FromHumanSize, "32.3") - assertError(t, FromHumanSize, " 32 ") - assertError(t, FromHumanSize, "32.3Kb") - assertError(t, FromHumanSize, "32 mb") - assertError(t, FromHumanSize, "32m b") - assertError(t, FromHumanSize, "32bm") -} - -func TestRAMInBytes(t *testing.T) { - assertSuccessEquals(t, 32, RAMInBytes, "32") - assertSuccessEquals(t, 32, RAMInBytes, "32b") - assertSuccessEquals(t, 32, RAMInBytes, "32B") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") - assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") - assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") - assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") - assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") - assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") - - assertError(t, RAMInBytes, "") - assertError(t, RAMInBytes, "hello") - assertError(t, RAMInBytes, "-32") - assertError(t, RAMInBytes, "32.3") - assertError(t, RAMInBytes, " 32 ") - assertError(t, RAMInBytes, "32.3Kb") - assertError(t, RAMInBytes, "32 mb") - assertError(t, RAMInBytes, "32m b") - assertError(t, RAMInBytes, "32bm") -} - -func assertEquals(t *testing.T, expected, actual interface{}) { - if expected != actual { - t.Errorf("Expected '%v' but got '%v'", expected, actual) - } -} - -// func that maps to the parse function signatures as testing abstraction -type parseFn func(string) (int64, error) - -// Define 'String()' for pretty-print -func (fn parseFn) String() string { - fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() - return fnName[strings.LastIndex(fnName, ".")+1:] -} - -func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { - res, err := fn(arg) - if err != nil || res != expected { - t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) - } -} - -func assertError(t *testing.T, fn parseFn, arg string) { - res, err := fn(arg) - if err == nil && res != -1 { - t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/libcontainer/user/user_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/libcontainer/user/user_test.go deleted file mode 100644 index ffb0760e220..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/docker/libcontainer/user/user_test.go +++ /dev/null @@ -1,443 +0,0 @@ -package user - -import ( - "fmt" - "io" - "io/ioutil" - "reflect" - "sort" - "strconv" - "strings" - "testing" -) - -func TestUserParseLine(t *testing.T) { - var ( - a, b string - c []string - d int - ) - - parseLine("", &a, &b) - if a != "" || b != "" { - t.Fatalf("a and b should be empty ('%v', '%v')", a, b) - } - - parseLine("a", &a, &b) - if a != "a" || b != "" { - t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) - } - - parseLine("bad boys:corny cows", &a, &b) - if a != "bad boys" || b != "corny cows" { - t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) - } - - parseLine("", &c) - if len(c) != 0 { - t.Fatalf("c should be empty (%#v)", c) - } - - parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) - if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { - t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("::::::::::", &a, &b, &c) - if a != "" || b != "" || len(c) != 0 { - t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("not a number", &d) - if d != 0 { - t.Fatalf("d should be 0 (%v)", d) - } - - parseLine("b:12:c", &a, &d, &b) - if a != "b" || b != "c" || d != 12 { - t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) - } -} - -func TestUserParsePasswd(t *testing.T) { - users, err := ParsePasswdFilter(strings.NewReader(` -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm:/bin/false -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(users) != 3 { - t.Fatalf("Expected 3 users, got %v", len(users)) - } - if users[0].Uid != 0 || users[0].Name != "root" { - t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) - } - if users[1].Uid != 3 || users[1].Name != "adm" { - t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) - } -} - -func TestUserParseGroup(t *testing.T) { - groups, err := ParseGroupFilter(strings.NewReader(` -root:x:0:root -adm:x:4:root,adm,daemon -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(groups) != 3 { - t.Fatalf("Expected 3 groups, got %v", len(groups)) - } - if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { - t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) - } - if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { - t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) - } -} - -func TestValidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - expected ExecUser - }{ - { - ref: "root", - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{0, 1234}, - Home: "/root", - }, - }, - { - ref: "adm", - expected: ExecUser{ - Uid: 42, - Gid: 43, - Sgids: []int{1234}, - Home: "/var/adm", - }, - }, - { - ref: "root:adm", - expected: ExecUser{ - Uid: 0, - Gid: 43, - Sgids: defaultExecUser.Sgids, - Home: "/root", - }, - }, - { - ref: "adm:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "42:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "1337:1234", - expected: ExecUser{ - Uid: 1337, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "1337", - expected: ExecUser{ - Uid: 1337, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "", - expected: ExecUser{ - Uid: defaultExecUser.Uid, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestInvalidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - tests := []string{ - // No such user/group. - "notuser", - "notuser:notgroup", - "root:notgroup", - "notuser:adm", - "8888:notgroup", - "notuser:8888", - - // Invalid user/group values. - "-1:0", - "0:-3", - "-5:-2", - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test, nil, passwd, group) - if err == nil { - t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) - t.Fail() - continue - } - } -} - -func TestGetExecUserNilSources(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - passwd, group bool - expected ExecUser - }{ - { - ref: "", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "root", - passwd: true, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/root", - }, - }, - { - ref: "0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "0:0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - } - - for _, test := range tests { - var passwd, group io.Reader - - if test.passwd { - passwd = strings.NewReader(passwdContent) - } - - if test.group { - group = strings.NewReader(groupContent) - } - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestGetAdditionalGroupsPath(t *testing.T) { - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -adm:x:4343:root,adm-duplicate -this is just some garbage data -` - tests := []struct { - groups []string - expected []int - hasError bool - }{ - { - // empty group - groups: []string{}, - expected: []int{}, - }, - { - // single group - groups: []string{"adm"}, - expected: []int{43}, - }, - { - // multiple groups - groups: []string{"adm", "grp"}, - expected: []int{43, 1234}, - }, - { - // invalid group - groups: []string{"adm", "grp", "not-exist"}, - expected: nil, - hasError: true, - }, - { - // group with numeric id - groups: []string{"43"}, - expected: []int{43}, - }, - { - // group with unknown numeric id - groups: []string{"adm", "10001"}, - expected: []int{43, 10001}, - }, - { - // groups specified twice with numeric and name - groups: []string{"adm", "43"}, - expected: []int{43}, - }, - { - // groups with too small id - groups: []string{"-1"}, - expected: nil, - hasError: true, - }, - { - // groups with too large id - groups: []string{strconv.Itoa(1 << 31)}, - expected: nil, - hasError: true, - }, - } - - for _, test := range tests { - tmpFile, err := ioutil.TempFile("", "get-additional-groups-path") - if err != nil { - t.Error(err) - } - fmt.Fprint(tmpFile, groupContent) - tmpFile.Close() - - gids, err := GetAdditionalGroupsPath(test.groups, tmpFile.Name()) - if test.hasError && err == nil { - t.Errorf("Parse(%#v) expects error but has none", test) - continue - } - if !test.hasError && err != nil { - t.Errorf("Parse(%#v) has error %v", test, err) - continue - } - sort.Sort(sort.IntSlice(gids)) - if !reflect.DeepEqual(gids, test.expected) { - t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go deleted file mode 100644 index 9814c501e8a..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2012 The Gorilla 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 ( - "net/http" - "testing" -) - -type keyType int - -const ( - key1 keyType = iota - key2 -) - -func TestContext(t *testing.T) { - assertEqual := func(val interface{}, exp interface{}) { - if val != exp { - t.Errorf("Expected %v, got %v.", exp, val) - } - } - - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - - // Get() - assertEqual(Get(r, key1), nil) - - // Set() - Set(r, key1, "1") - assertEqual(Get(r, key1), "1") - assertEqual(len(data[r]), 1) - - Set(r, key2, "2") - assertEqual(Get(r, key2), "2") - assertEqual(len(data[r]), 2) - - //GetOk - value, ok := GetOk(r, key1) - assertEqual(value, "1") - assertEqual(ok, true) - - value, ok = GetOk(r, "not exists") - assertEqual(value, nil) - assertEqual(ok, false) - - Set(r, "nil value", nil) - value, ok = GetOk(r, "nil value") - assertEqual(value, nil) - assertEqual(ok, true) - - // GetAll() - values := GetAll(r) - assertEqual(len(values), 3) - - // GetAll() for empty request - values = GetAll(emptyR) - if values != nil { - t.Error("GetAll didn't return nil value for invalid request") - } - - // GetAllOk() - values, ok = GetAllOk(r) - assertEqual(len(values), 3) - assertEqual(ok, true) - - // GetAllOk() for empty request - values, ok = GetAllOk(emptyR) - assertEqual(value, nil) - assertEqual(ok, false) - - // Delete() - Delete(r, key1) - assertEqual(Get(r, key1), nil) - assertEqual(len(data[r]), 2) - - Delete(r, key2) - assertEqual(Get(r, key2), nil) - assertEqual(len(data[r]), 1) - - // Clear() - Clear(r) - assertEqual(len(data), 0) -} - -func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Get(r, key) - } - done <- struct{}{} - -} - -func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Set(r, key, value) - } - done <- struct{}{} - -} - -func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { - - b.StopTimer() - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - done := make(chan struct{}) - b.StartTimer() - - for i := 0; i < b.N; i++ { - wait := make(chan struct{}) - - for i := 0; i < numReaders; i++ { - go parallelReader(r, "test", iterations, wait, done) - } - - for i := 0; i < numWriters; i++ { - go parallelWriter(r, "test", "123", iterations, wait, done) - } - - close(wait) - - for i := 0; i < numReaders+numWriters; i++ { - <-done - } - - } - -} - -func BenchmarkMutexSameReadWrite1(b *testing.B) { - benchmarkMutex(b, 1, 1, 32) -} -func BenchmarkMutexSameReadWrite2(b *testing.B) { - benchmarkMutex(b, 2, 2, 32) -} -func BenchmarkMutexSameReadWrite4(b *testing.B) { - benchmarkMutex(b, 4, 4, 32) -} -func BenchmarkMutex1(b *testing.B) { - benchmarkMutex(b, 2, 8, 32) -} -func BenchmarkMutex2(b *testing.B) { - benchmarkMutex(b, 16, 4, 64) -} -func BenchmarkMutex3(b *testing.B) { - benchmarkMutex(b, 1, 2, 128) -} -func BenchmarkMutex4(b *testing.B) { - benchmarkMutex(b, 128, 32, 256) -} -func BenchmarkMutex5(b *testing.B) { - benchmarkMutex(b, 1024, 2048, 64) -} -func BenchmarkMutex6(b *testing.B) { - benchmarkMutex(b, 2048, 1024, 512) -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go deleted file mode 100644 index c5f97b2b2a8..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "net/http" - "testing" -) - -func BenchmarkMux(b *testing.B) { - router := new(Router) - handler := func(w http.ResponseWriter, r *http.Request) {} - router.HandleFunc("/v1/{v1}", handler) - - request, _ := http.NewRequest("GET", "/v1/anything", nil) - for i := 0; i < b.N; i++ { - router.ServeHTTP(nil, request) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go deleted file mode 100644 index 74cb98b8329..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go +++ /dev/null @@ -1,1334 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "fmt" - "net/http" - "strings" - "testing" - - "github.com/fsouza/go-dockerclient/external/github.com/gorilla/context" -) - -func (r *Route) GoString() string { - matchers := make([]string, len(r.matchers)) - for i, m := range r.matchers { - matchers[i] = fmt.Sprintf("%#v", m) - } - return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", ")) -} - -func (r *routeRegexp) GoString() string { - return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR) -} - -type routeTest struct { - title string // title of the test - route *Route // the route being tested - request *http.Request // a request to test the route - vars map[string]string // the expected vars of the match - host string // the expected host of the match - path string // the expected path of the match - shouldMatch bool // whether the request is expected to match the route at all - shouldRedirect bool // whether the request should result in a redirect -} - -func TestHost(t *testing.T) { - // newRequestHost a new request with a method, url, and host header - newRequestHost := func(method, url, host string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - req.Host = host - return req - } - - tests := []routeTest{ - { - title: "Host route match", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with port, match", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: true, - }, - { - title: "Host route with port, wrong port in request URL", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route, match with host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, - { - title: "Host route with port, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with pattern, additional capturing group, match", - route: new(Route).Host("aaa.{v1:[a-z]{2}(b|c)}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with pattern, wrong host in request URL", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with multiple patterns, wrong host in request URL", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with hyphenated name and pattern, match", - route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with hyphenated name and pattern, additional capturing group, match", - route: new(Route).Host("aaa.{v-1:[a-z]{2}(b|c)}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with multiple hyphenated names and patterns, match", - route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/a"), - vars: map[string]string{"category": "a"}, - host: "", - path: "/a", - shouldMatch: true, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/b/c"), - vars: map[string]string{"category": "b/c"}, - host: "", - path: "/b/c", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/b/c/product_name/1"), - vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"}, - host: "", - path: "/b/c/product_name/1", - shouldMatch: true, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPath(t *testing.T) { - tests := []routeTest{ - { - title: "Path route, match", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route, match with trailing slash in request and path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - }, - { - title: "Path route, do not match with trailing slash in path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "Path route, do not match with trailing slash in request", - route: new(Route).Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: false, - }, - { - title: "Path route, wrong path in request in request URL", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with pattern, match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with pattern, URL in request does not match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with multiple patterns, match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns, URL in request does not match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|(b/c)}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - { - title: "Path route with hyphenated name and pattern, match", - route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v-1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple hyphenated names and patterns, match", - route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple hyphenated names and patterns with pipe, match", - route: new(Route).Path("/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPathPrefix(t *testing.T) { - tests := []routeTest{ - { - title: "PathPrefix route, match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - }, - { - title: "PathPrefix route, match substring", - route: new(Route).PathPrefix("/1"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/1", - shouldMatch: true, - }, - { - title: "PathPrefix route, URL prefix in request does not match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "PathPrefix route with pattern, match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with pattern, URL prefix in request does not match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - { - title: "PathPrefix route with multiple patterns, match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with multiple patterns, URL prefix in request does not match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHostPath(t *testing.T) { - tests := []routeTest{ - { - title: "Host and Path route, match", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Host and Path route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Host and Path route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with pattern, URL in request does not match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Host and Path route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with multiple patterns, URL in request does not match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHeaders(t *testing.T) { - // newRequestHeaders creates a new request with a method, url, and headers - newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - for k, v := range headers { - req.Header.Add(k, v) - } - return req - } - - tests := []routeTest{ - { - title: "Headers route, match", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Headers route, bad header values", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Headers route, regex header values to match", - route: new(Route).Headers("foo", "ba[zr]"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Headers route, regex header values to match", - route: new(Route).HeadersRegexp("foo", "ba[zr]"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } - -} - -func TestMethods(t *testing.T) { - tests := []routeTest{ - { - title: "Methods route, match GET", - route: new(Route).Methods("GET", "POST"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, match POST", - route: new(Route).Methods("GET", "POST"), - request: newRequest("POST", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, bad method", - route: new(Route).Methods("GET", "POST"), - request: newRequest("PUT", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestQueries(t *testing.T) { - tests := []routeTest{ - { - title: "Queries route, match", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string out of order", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, bad query", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with pattern, match", - route: new(Route).Queries("foo", "{v1}"), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{"v1": "bar"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with multiple patterns, match", - route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=10"), - vars: map[string]string{"v1": "10"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=a"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with regexp pattern with quantifier, match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=1"), - vars: map[string]string{"v1": "1"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, additional variable in query string, match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?bar=2&foo=1"), - vars: map[string]string{"v1": "1"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=12"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with regexp pattern with quantifier, additional capturing group", - route: new(Route).Queries("foo", "{v1:[0-9]{1}(a|b)}"), - request: newRequest("GET", "http://localhost?foo=1a"), - vars: map[string]string{"v1": "1a"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), - request: newRequest("GET", "http://localhost?foo=12"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with hyphenated name, match", - route: new(Route).Queries("foo", "{v-1}"), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{"v-1": "bar"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with multiple hyphenated names, match", - route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{"v-1": "bar", "v-2": "ding"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with hyphenate name and pattern, match", - route: new(Route).Queries("foo", "{v-1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=10"), - vars: map[string]string{"v-1": "10"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group", - route: new(Route).Queries("foo", "{v-1:[0-9]{1}(a|b)}"), - request: newRequest("GET", "http://localhost?foo=1a"), - vars: map[string]string{"v-1": "1a"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with empty value, should match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with empty value and no parameter in request, should not match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with empty value and empty parameter in request, should match", - route: new(Route).Queries("foo", ""), - request: newRequest("GET", "http://localhost?foo="), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with overlapping value, should not match", - route: new(Route).Queries("foo", "bar"), - request: newRequest("GET", "http://localhost?foo=barfoo"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with no parameter in request, should not match", - route: new(Route).Queries("foo", "{bar}"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with empty parameter in request, should match", - route: new(Route).Queries("foo", "{bar}"), - request: newRequest("GET", "http://localhost?foo="), - vars: map[string]string{"foo": ""}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, bad submatch", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSchemes(t *testing.T) { - tests := []routeTest{ - // Schemes - { - title: "Schemes route, match https", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "https://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, match ftp", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "ftp://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, bad scheme", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestMatcherFunc(t *testing.T) { - m := func(r *http.Request, m *RouteMatch) bool { - if r.URL.Host == "aaa.bbb.ccc" { - return true - } - return false - } - - tests := []routeTest{ - { - title: "MatchFunc route, match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.bbb.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "MatchFunc route, non-match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.222.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestBuildVarsFunc(t *testing.T) { - tests := []routeTest{ - { - title: "BuildVarsFunc set on route", - route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "3" - vars["v2"] = "a" - return vars - }), - request: newRequest("GET", "http://localhost/111/2"), - path: "/111/3a", - shouldMatch: true, - }, - { - title: "BuildVarsFunc set on route and parent route", - route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "2" - return vars - }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v2"] = "b" - return vars - }), - request: newRequest("GET", "http://localhost/1/a"), - path: "/2/b", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSubRouter(t *testing.T) { - subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() - subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() - - tests := []routeTest{ - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://aaa.google.com/bbb"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: true, - }, - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://111.google.com/111"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: false, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: true, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestNamedRoutes(t *testing.T) { - r1 := NewRouter() - r1.NewRoute().Name("a") - r1.NewRoute().Name("b") - r1.NewRoute().Name("c") - - r2 := r1.NewRoute().Subrouter() - r2.NewRoute().Name("d") - r2.NewRoute().Name("e") - r2.NewRoute().Name("f") - - r3 := r2.NewRoute().Subrouter() - r3.NewRoute().Name("g") - r3.NewRoute().Name("h") - r3.NewRoute().Name("i") - - if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { - t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) - } else if r1.Get("i") == nil { - t.Errorf("Subroute name not registered") - } -} - -func TestStrictSlash(t *testing.T) { - r := NewRouter() - r.StrictSlash(true) - - tests := []routeTest{ - { - title: "Redirect path without slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path with slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Redirect path with slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path without slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Propagate StrictSlash to subrouters", - route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), - request: newRequest("GET", "http://localhost/static/images"), - vars: map[string]string{}, - host: "", - path: "/static/images/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Ignore StrictSlash for path prefix", - route: r.NewRoute().PathPrefix("/static/"), - request: newRequest("GET", "http://localhost/static/logo.png"), - vars: map[string]string{}, - host: "", - path: "/static/", - shouldMatch: true, - shouldRedirect: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestWalkSingleDepth(t *testing.T) { - r0 := NewRouter() - r1 := NewRouter() - r2 := NewRouter() - - r0.Path("/g") - r0.Path("/o") - r0.Path("/d").Handler(r1) - r0.Path("/r").Handler(r2) - r0.Path("/a") - - r1.Path("/z") - r1.Path("/i") - r1.Path("/l") - r1.Path("/l") - - r2.Path("/i") - r2.Path("/l") - r2.Path("/l") - - paths := []string{"g", "o", "r", "i", "l", "l", "a"} - depths := []int{0, 0, 0, 1, 1, 1, 0} - i := 0 - err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error { - matcher := route.matchers[0].(*routeRegexp) - if matcher.template == "/d" { - return SkipRouter - } - if len(ancestors) != depths[i] { - t.Errorf(`Expected depth of %d at i = %d; got "%s"`, depths[i], i, len(ancestors)) - } - if matcher.template != "/"+paths[i] { - t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template) - } - i++ - return nil - }) - if err != nil { - panic(err) - } - if i != len(paths) { - t.Errorf("Expected %d routes, found %d", len(paths), i) - } -} - -func TestWalkNested(t *testing.T) { - router := NewRouter() - - g := router.Path("/g").Subrouter() - o := g.PathPrefix("/o").Subrouter() - r := o.PathPrefix("/r").Subrouter() - i := r.PathPrefix("/i").Subrouter() - l1 := i.PathPrefix("/l").Subrouter() - l2 := l1.PathPrefix("/l").Subrouter() - l2.Path("/a") - - paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"} - idx := 0 - err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { - path := paths[idx] - tpl := route.regexp.path.template - if tpl != path { - t.Errorf(`Expected %s got %s`, path, tpl) - } - idx++ - return nil - }) - if err != nil { - panic(err) - } - if idx != len(paths) { - t.Errorf("Expected %d routes, found %d", len(paths), idx) - } -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -func getRouteTemplate(route *Route) string { - host, path := "none", "none" - if route.regexp != nil { - if route.regexp.host != nil { - host = route.regexp.host.template - } - if route.regexp.path != nil { - path = route.regexp.path.template - } - } - return fmt.Sprintf("Host: %v, Path: %v", host, path) -} - -func testRoute(t *testing.T, test routeTest) { - request := test.request - route := test.route - vars := test.vars - shouldMatch := test.shouldMatch - host := test.host - path := test.path - url := test.host + test.path - shouldRedirect := test.shouldRedirect - - var match RouteMatch - ok := route.Match(request, &match) - if ok != shouldMatch { - msg := "Should match" - if !shouldMatch { - msg = "Should not match" - } - t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) - return - } - if shouldMatch { - if test.vars != nil && !stringMapEqual(test.vars, match.Vars) { - t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) - return - } - if host != "" { - u, _ := test.route.URLHost(mapToPairs(match.Vars)...) - if host != u.Host { - t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route)) - return - } - } - if path != "" { - u, _ := route.URLPath(mapToPairs(match.Vars)...) - if path != u.Path { - t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route)) - return - } - } - if url != "" { - u, _ := route.URL(mapToPairs(match.Vars)...) - if url != u.Host+u.Path { - t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route)) - return - } - } - if shouldRedirect && match.Handler == nil { - t.Errorf("(%v) Did not redirect", test.title) - return - } - if !shouldRedirect && match.Handler != nil { - t.Errorf("(%v) Unexpected redirect", test.title) - return - } - } -} - -// Tests that the context is cleared or not cleared properly depending on -// the configuration of the router -func TestKeepContext(t *testing.T) { - func1 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - res := new(http.ResponseWriter) - r.ServeHTTP(*res, req) - - if _, ok := context.GetOk(req, "t"); ok { - t.Error("Context should have been cleared at end of request") - } - - r.KeepContext = true - - req, _ = http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - r.ServeHTTP(*res, req) - if _, ok := context.GetOk(req, "t"); !ok { - t.Error("Context should NOT have been cleared at end of request") - } - -} - -type TestA301ResponseWriter struct { - hh http.Header - status int -} - -func (ho TestA301ResponseWriter) Header() http.Header { - return http.Header(ho.hh) -} - -func (ho TestA301ResponseWriter) Write(b []byte) (int, error) { - return 0, nil -} - -func (ho TestA301ResponseWriter) WriteHeader(code int) { - ho.status = code -} - -func Test301Redirect(t *testing.T) { - m := make(http.Header) - - func1 := func(w http.ResponseWriter, r *http.Request) {} - func2 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/api/", func2).Name("func2") - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) - - res := TestA301ResponseWriter{ - hh: m, - status: 0, - } - r.ServeHTTP(&res, req) - - if "http://localhost/api/?abc=def" != res.hh["Location"][0] { - t.Errorf("Should have complete URL with query string") - } -} - -// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW -func TestSubrouterHeader(t *testing.T) { - expected := "func1 response" - func1 := func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, expected) - } - func2 := func(http.ResponseWriter, *http.Request) {} - - r := NewRouter() - s := r.Headers("SomeSpecialHeader", "").Subrouter() - s.HandleFunc("/", func1).Name("func1") - r.HandleFunc("/", func2).Name("func2") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - req.Header.Add("SomeSpecialHeader", "foo") - match := new(RouteMatch) - matched := r.Match(req, match) - if !matched { - t.Errorf("Should match request") - } - if match.Route.GetName() != "func1" { - t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) - } - resp := NewRecorder() - match.Handler.ServeHTTP(resp, req) - if resp.Body.String() != expected { - t.Errorf("Expecting %q", expected) - } -} - -// mapToPairs converts a string map to a slice of string pairs -func mapToPairs(m map[string]string) []string { - var i int - p := make([]string, len(m)*2) - for k, v := range m { - p[i] = k - p[i+1] = v - i += 2 - } - return p -} - -// stringMapEqual checks the equality of two string maps -func stringMapEqual(m1, m2 map[string]string) bool { - nil1 := m1 == nil - nil2 := m2 == nil - if nil1 != nil2 || len(m1) != len(m2) { - return false - } - for k, v := range m1 { - if v != m2[k] { - return false - } - } - return true -} - -// newRequest is a helper function to create a new request with a method and url -func newRequest(method, url string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - return req -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go deleted file mode 100644 index 755db483e8f..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go +++ /dev/null @@ -1,714 +0,0 @@ -// Old tests ported to Go1. This is a mess. Want to drop it one day. - -// Copyright 2011 Gorilla 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 mux - -import ( - "bytes" - "net/http" - "testing" -) - -// ---------------------------------------------------------------------------- -// ResponseRecorder -// ---------------------------------------------------------------------------- -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// ResponseRecorder is an implementation of http.ResponseWriter that -// records its mutations for later inspection in tests. -type ResponseRecorder struct { - Code int // the HTTP response code from WriteHeader - HeaderMap http.Header // the HTTP response headers - Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to - Flushed bool -} - -// NewRecorder returns an initialized ResponseRecorder. -func NewRecorder() *ResponseRecorder { - return &ResponseRecorder{ - HeaderMap: make(http.Header), - Body: new(bytes.Buffer), - } -} - -// DefaultRemoteAddr is the default remote address to return in RemoteAddr if -// an explicit DefaultRemoteAddr isn't set on ResponseRecorder. -const DefaultRemoteAddr = "1.2.3.4" - -// Header returns the response headers. -func (rw *ResponseRecorder) Header() http.Header { - return rw.HeaderMap -} - -// Write always succeeds and writes to rw.Body, if not nil. -func (rw *ResponseRecorder) Write(buf []byte) (int, error) { - if rw.Body != nil { - rw.Body.Write(buf) - } - if rw.Code == 0 { - rw.Code = http.StatusOK - } - return len(buf), nil -} - -// WriteHeader sets rw.Code. -func (rw *ResponseRecorder) WriteHeader(code int) { - rw.Code = code -} - -// Flush sets rw.Flushed to true. -func (rw *ResponseRecorder) Flush() { - rw.Flushed = true -} - -// ---------------------------------------------------------------------------- - -func TestRouteMatchers(t *testing.T) { - var scheme, host, path, query, method string - var headers map[string]string - var resultVars map[bool]map[string]string - - router := NewRouter() - router.NewRoute().Host("{var1}.google.com"). - Path("/{var2:[a-z]+}/{var3:[0-9]+}"). - Queries("foo", "bar"). - Methods("GET"). - Schemes("https"). - Headers("x-requested-with", "XMLHttpRequest") - router.NewRoute().Host("www.{var4}.com"). - PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). - Queries("baz", "ding"). - Methods("POST"). - Schemes("http"). - Headers("Content-Type", "application/json") - - reset := func() { - // Everything match. - scheme = "https" - host = "www.google.com" - path = "/product/42" - query = "?foo=bar" - method = "GET" - headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} - resultVars = map[bool]map[string]string{ - true: {"var1": "www", "var2": "product", "var3": "42"}, - false: {}, - } - } - - reset2 := func() { - // Everything match. - scheme = "http" - host = "www.google.com" - path = "/foo/product/42/path/that/is/ignored" - query = "?baz=ding" - method = "POST" - headers = map[string]string{"Content-Type": "application/json"} - resultVars = map[bool]map[string]string{ - true: {"var4": "google", "var5": "product", "var6": "42"}, - false: {}, - } - } - - match := func(shouldMatch bool) { - url := scheme + "://" + host + path + query - request, _ := http.NewRequest(method, url, nil) - for key, value := range headers { - request.Header.Add(key, value) - } - - var routeMatch RouteMatch - matched := router.Match(request, &routeMatch) - if matched != shouldMatch { - // Need better messages. :) - if matched { - t.Errorf("Should match.") - } else { - t.Errorf("Should not match.") - } - } - - if matched { - currentRoute := routeMatch.Route - if currentRoute == nil { - t.Errorf("Expected a current route.") - } - vars := routeMatch.Vars - expectedVars := resultVars[shouldMatch] - if len(vars) != len(expectedVars) { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - for name, value := range vars { - if expectedVars[name] != value { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - } - } - } - - // 1st route -------------------------------------------------------------- - - // Everything match. - reset() - match(true) - - // Scheme doesn't match. - reset() - scheme = "http" - match(false) - - // Host doesn't match. - reset() - host = "www.mygoogle.com" - match(false) - - // Path doesn't match. - reset() - path = "/product/notdigits" - match(false) - - // Query doesn't match. - reset() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset() - method = "POST" - match(false) - - // Header doesn't match. - reset() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset() - match(true) - - // 2nd route -------------------------------------------------------------- - - // Everything match. - reset2() - match(true) - - // Scheme doesn't match. - reset2() - scheme = "https" - match(false) - - // Host doesn't match. - reset2() - host = "sub.google.com" - match(false) - - // Path doesn't match. - reset2() - path = "/bar/product/42" - match(false) - - // Query doesn't match. - reset2() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset2() - method = "GET" - match(false) - - // Header doesn't match. - reset2() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset2() - match(true) -} - -type headerMatcherTest struct { - matcher headerMatcher - headers map[string]string - result bool -} - -var headerMatcherTests = []headerMatcherTest{ - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": ""}), - headers: map[string]string{"X-Requested-With": "anything"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{}, - result: false, - }, -} - -type hostMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var hostMatcherTests = []hostMatcherTest{ - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://abc.def.ghi/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://a.b.c/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: false, - }, -} - -type methodMatcherTest struct { - matcher methodMatcher - method string - result bool -} - -var methodMatcherTests = []methodMatcherTest{ - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "GET", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "POST", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "PUT", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "DELETE", - result: false, - }, -} - -type pathMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var pathMatcherTests = []pathMatcherTest{ - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/123/456/789", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/1/2/3", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: false, - }, -} - -type schemeMatcherTest struct { - matcher schemeMatcher - url string - result bool -} - -var schemeMatcherTests = []schemeMatcherTest{ - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "http://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "https://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"https"}), - url: "http://localhost:8080/", - result: false, - }, - { - matcher: schemeMatcher([]string{"http"}), - url: "https://localhost:8080/", - result: false, - }, -} - -type urlBuildingTest struct { - route *Route - vars []string - url string -} - -var urlBuildingTests = []urlBuildingTest{ - { - route: new(Route).Host("foo.domain.com"), - vars: []string{}, - url: "http://foo.domain.com", - }, - { - route: new(Route).Host("{subdomain}.domain.com"), - vars: []string{"subdomain", "bar"}, - url: "http://bar.domain.com", - }, - { - route: new(Route).Host("foo.domain.com").Path("/articles"), - vars: []string{}, - url: "http://foo.domain.com/articles", - }, - { - route: new(Route).Path("/articles"), - vars: []string{}, - url: "/articles", - }, - { - route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"category", "technology", "id", "42"}, - url: "/articles/technology/42", - }, - { - route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, - url: "http://foo.domain.com/articles/technology/42", - }, -} - -func TestHeaderMatcher(t *testing.T) { - for _, v := range headerMatcherTests { - request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - for key, value := range v.headers { - request.Header.Add(key, value) - } - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, request.Header) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, request.Header) - } - } - } -} - -func TestHostMatcher(t *testing.T) { - for _, v := range hostMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestMethodMatcher(t *testing.T) { - for _, v := range methodMatcherTests { - request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.method) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.method) - } - } - } -} - -func TestPathMatcher(t *testing.T) { - for _, v := range pathMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestSchemeMatcher(t *testing.T) { - for _, v := range schemeMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - } -} - -func TestUrlBuilding(t *testing.T) { - - for _, v := range urlBuildingTests { - u, _ := v.route.URL(v.vars...) - url := u.String() - if url != v.url { - t.Errorf("expected %v, got %v", v.url, url) - /* - reversePath := "" - reverseHost := "" - if v.route.pathTemplate != nil { - reversePath = v.route.pathTemplate.Reverse - } - if v.route.hostTemplate != nil { - reverseHost = v.route.hostTemplate.Reverse - } - - t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) - */ - } - } - - ArticleHandler := func(w http.ResponseWriter, r *http.Request) { - } - - router := NewRouter() - router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") - - url, _ := router.Get("article").URL("category", "technology", "id", "42") - expected := "/articles/technology/42" - if url.String() != expected { - t.Errorf("Expected %v, got %v", expected, url.String()) - } -} - -func TestMatchedRouteName(t *testing.T) { - routeName := "stock" - router := NewRouter() - route := router.NewRoute().Path("/products/").Name(routeName) - - url := "http://www.example.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - retName := rv.Route.GetName() - if retName != routeName { - t.Errorf("Expected %q, got %q.", routeName, retName) - } -} - -func TestSubRouting(t *testing.T) { - // Example from docs. - router := NewRouter() - subrouter := router.NewRoute().Host("www.example.com").Subrouter() - route := subrouter.NewRoute().Path("/products/").Name("products") - - url := "http://www.example.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - u, _ := router.Get("products").URL() - builtUrl := u.String() - // Yay, subroute aware of the domain when building! - if builtUrl != url { - t.Errorf("Expected %q, got %q.", url, builtUrl) - } -} - -func TestVariableNames(t *testing.T) { - route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") - if route.err == nil { - t.Errorf("Expected error for duplicated variable names") - } -} - -func TestRedirectSlash(t *testing.T) { - var route *Route - var routeMatch RouteMatch - r := NewRouter() - - r.StrictSlash(false) - route = r.NewRoute() - if route.strictSlash != false { - t.Errorf("Expected false redirectSlash.") - } - - r.StrictSlash(true) - route = r.NewRoute() - if route.strictSlash != true { - t.Errorf("Expected true redirectSlash.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}/") - request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars := routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp := NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { - t.Errorf("Expected redirect header.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}") - request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars = routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp = NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { - t.Errorf("Expected redirect header.") - } -} - -// Test for the new regexp library, still not available in stable Go. -func TestNewRegexp(t *testing.T) { - var p *routeRegexp - var matches []string - - tests := map[string]map[string][]string{ - "/{foo:a{2}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": nil, - "/aaaa": nil, - }, - "/{foo:a{2,}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": {"aaaa"}, - }, - "/{foo:a{2,3}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": nil, - }, - "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abcd": nil, - "/abc/ab": {"abc", "ab"}, - "/abc/abc": nil, - "/abcd/ab": nil, - }, - `/{foo:\w{3,}}/{bar:\d{2,}}`: { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abc/1": nil, - "/abc/12": {"abc", "12"}, - "/abcd/12": {"abcd", "12"}, - "/abcd/123": {"abcd", "123"}, - }, - } - - for pattern, paths := range tests { - p, _ = newRouteRegexp(pattern, false, false, false, false) - for path, result := range paths { - matches = p.regexp.FindStringSubmatch(path) - if result == nil { - if matches != nil { - t.Errorf("%v should not match %v.", pattern, path) - } - } else { - if len(matches) != len(result)+1 { - t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) - } else { - for k, v := range result { - if matches[k+1] != v { - t.Errorf("Expected %v, got %v.", v, matches[k+1]) - } - } - } - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go deleted file mode 100644 index 0e37ac3dd2e..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go +++ /dev/null @@ -1,436 +0,0 @@ -package user - -import ( - "io" - "reflect" - "sort" - "strconv" - "strings" - "testing" -) - -func TestUserParseLine(t *testing.T) { - var ( - a, b string - c []string - d int - ) - - parseLine("", &a, &b) - if a != "" || b != "" { - t.Fatalf("a and b should be empty ('%v', '%v')", a, b) - } - - parseLine("a", &a, &b) - if a != "a" || b != "" { - t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) - } - - parseLine("bad boys:corny cows", &a, &b) - if a != "bad boys" || b != "corny cows" { - t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) - } - - parseLine("", &c) - if len(c) != 0 { - t.Fatalf("c should be empty (%#v)", c) - } - - parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) - if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { - t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("::::::::::", &a, &b, &c) - if a != "" || b != "" || len(c) != 0 { - t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) - } - - parseLine("not a number", &d) - if d != 0 { - t.Fatalf("d should be 0 (%v)", d) - } - - parseLine("b:12:c", &a, &d, &b) - if a != "b" || b != "c" || d != 12 { - t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) - } -} - -func TestUserParsePasswd(t *testing.T) { - users, err := ParsePasswdFilter(strings.NewReader(` -root:x:0:0:root:/root:/bin/bash -adm:x:3:4:adm:/var/adm:/bin/false -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(users) != 3 { - t.Fatalf("Expected 3 users, got %v", len(users)) - } - if users[0].Uid != 0 || users[0].Name != "root" { - t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) - } - if users[1].Uid != 3 || users[1].Name != "adm" { - t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) - } -} - -func TestUserParseGroup(t *testing.T) { - groups, err := ParseGroupFilter(strings.NewReader(` -root:x:0:root -adm:x:4:root,adm,daemon -this is just some garbage data -`), nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if len(groups) != 3 { - t.Fatalf("Expected 3 groups, got %v", len(groups)) - } - if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { - t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) - } - if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { - t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) - } -} - -func TestValidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - expected ExecUser - }{ - { - ref: "root", - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{0, 1234}, - Home: "/root", - }, - }, - { - ref: "adm", - expected: ExecUser{ - Uid: 42, - Gid: 43, - Sgids: []int{1234}, - Home: "/var/adm", - }, - }, - { - ref: "root:adm", - expected: ExecUser{ - Uid: 0, - Gid: 43, - Sgids: defaultExecUser.Sgids, - Home: "/root", - }, - }, - { - ref: "adm:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "42:1234", - expected: ExecUser{ - Uid: 42, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: "/var/adm", - }, - }, - { - ref: "1337:1234", - expected: ExecUser{ - Uid: 1337, - Gid: 1234, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "1337", - expected: ExecUser{ - Uid: 1337, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - { - ref: "", - expected: ExecUser{ - Uid: defaultExecUser.Uid, - Gid: defaultExecUser.Gid, - Sgids: defaultExecUser.Sgids, - Home: defaultExecUser.Home, - }, - }, - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestInvalidGetExecUser(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - tests := []string{ - // No such user/group. - "notuser", - "notuser:notgroup", - "root:notgroup", - "notuser:adm", - "8888:notgroup", - "notuser:8888", - - // Invalid user/group values. - "-1:0", - "0:-3", - "-5:-2", - } - - for _, test := range tests { - passwd := strings.NewReader(passwdContent) - group := strings.NewReader(groupContent) - - execUser, err := GetExecUser(test, nil, passwd, group) - if err == nil { - t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) - t.Fail() - continue - } - } -} - -func TestGetExecUserNilSources(t *testing.T) { - const passwdContent = ` -root:x:0:0:root user:/root:/bin/bash -adm:x:42:43:adm:/var/adm:/bin/false -this is just some garbage data -` - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -this is just some garbage data -` - - defaultExecUser := ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - } - - tests := []struct { - ref string - passwd, group bool - expected ExecUser - }{ - { - ref: "", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 8888, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "root", - passwd: true, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/root", - }, - }, - { - ref: "0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 8888, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - { - ref: "0:0", - passwd: false, - group: false, - expected: ExecUser{ - Uid: 0, - Gid: 0, - Sgids: []int{8888}, - Home: "/8888", - }, - }, - } - - for _, test := range tests { - var passwd, group io.Reader - - if test.passwd { - passwd = strings.NewReader(passwdContent) - } - - if test.group { - group = strings.NewReader(groupContent) - } - - execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) - if err != nil { - t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) - t.Fail() - continue - } - - if !reflect.DeepEqual(test.expected, *execUser) { - t.Logf("got: %#v", execUser) - t.Logf("expected: %#v", test.expected) - t.Fail() - continue - } - } -} - -func TestGetAdditionalGroups(t *testing.T) { - const groupContent = ` -root:x:0:root -adm:x:43: -grp:x:1234:root,adm -adm:x:4343:root,adm-duplicate -this is just some garbage data -` - tests := []struct { - groups []string - expected []int - hasError bool - }{ - { - // empty group - groups: []string{}, - expected: []int{}, - }, - { - // single group - groups: []string{"adm"}, - expected: []int{43}, - }, - { - // multiple groups - groups: []string{"adm", "grp"}, - expected: []int{43, 1234}, - }, - { - // invalid group - groups: []string{"adm", "grp", "not-exist"}, - expected: nil, - hasError: true, - }, - { - // group with numeric id - groups: []string{"43"}, - expected: []int{43}, - }, - { - // group with unknown numeric id - groups: []string{"adm", "10001"}, - expected: []int{43, 10001}, - }, - { - // groups specified twice with numeric and name - groups: []string{"adm", "43"}, - expected: []int{43}, - }, - { - // groups with too small id - groups: []string{"-1"}, - expected: nil, - hasError: true, - }, - { - // groups with too large id - groups: []string{strconv.Itoa(1 << 31)}, - expected: nil, - hasError: true, - }, - } - - for _, test := range tests { - group := strings.NewReader(groupContent) - - gids, err := GetAdditionalGroups(test.groups, group) - if test.hasError && err == nil { - t.Errorf("Parse(%#v) expects error but has none", test) - continue - } - if !test.hasError && err != nil { - t.Errorf("Parse(%#v) has error %v", test, err) - continue - } - sort.Sort(sort.IntSlice(gids)) - if !reflect.DeepEqual(gids, test.expected) { - t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go deleted file mode 100644 index 8d9ee7ae2ff..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/image_test.go +++ /dev/null @@ -1,973 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "reflect" - "strings" - "testing" - "time" -) - -func newTestClient(rt *FakeRoundTripper) Client { - endpoint := "http://localhost:4243" - u, _ := parseEndpoint("http://localhost:4243", false) - testAPIVersion, _ := NewAPIVersion("1.17") - client := Client{ - HTTPClient: &http.Client{Transport: rt}, - Dialer: &net.Dialer{}, - endpoint: endpoint, - endpointURL: u, - SkipServerVersionCheck: true, - serverAPIVersion: testAPIVersion, - } - return client -} - -type stdoutMock struct { - *bytes.Buffer -} - -func (m stdoutMock) Close() error { - return nil -} - -type stdinMock struct { - *bytes.Buffer -} - -func (m stdinMock) Close() error { - return nil -} - -func TestListImages(t *testing.T) { - body := `[ - { - "Repository":"base", - "Tag":"ubuntu-12.10", - "Id":"b750fe79269d", - "Created":1364102658 - }, - { - "Repository":"base", - "Tag":"ubuntu-quantal", - "Id":"b750fe79269d", - "Created":1364102658 - }, - { - "RepoTag": [ - "ubuntu:12.04", - "ubuntu:precise", - "ubuntu:latest" - ], - "Id": "8dbd9e392a964c", - "Created": 1365714795, - "Size": 131506275, - "VirtualSize": 131506275 - }, - { - "RepoTag": [ - "ubuntu:12.10", - "ubuntu:quantal" - ], - "ParentId": "27cf784147099545", - "Id": "b750fe79269d2e", - "Created": 1364102658, - "Size": 24653, - "VirtualSize": 180116135 - } -]` - var expected []APIImages - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - images, err := client.ListImages(ListImagesOptions{}) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(images, expected) { - t.Errorf("ListImages: Wrong return value. Want %#v. Got %#v.", expected, images) - } -} - -func TestListImagesParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "null", status: http.StatusOK} - client := newTestClient(fakeRT) - _, err := client.ListImages(ListImagesOptions{All: false}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ListImages({All: false}: Wrong HTTP method. Want GET. Got %s.", req.Method) - } - if all := req.URL.Query().Get("all"); all != "0" && all != "" { - t.Errorf("ListImages({All: false}): Wrong parameter. Want all=0 or not present at all. Got all=%s", all) - } - fakeRT.Reset() - _, err = client.ListImages(ListImagesOptions{All: true}) - if err != nil { - t.Fatal(err) - } - req = fakeRT.requests[0] - if all := req.URL.Query().Get("all"); all != "1" { - t.Errorf("ListImages({All: true}): Wrong parameter. Want all=1. Got all=%s", all) - } - fakeRT.Reset() - _, err = client.ListImages(ListImagesOptions{Filters: map[string][]string{ - "dangling": {"true"}, - }}) - if err != nil { - t.Fatal(err) - } - req = fakeRT.requests[0] - body := req.URL.Query().Get("filters") - var filters map[string][]string - err = json.Unmarshal([]byte(body), &filters) - if err != nil { - t.Fatal(err) - } - if len(filters["dangling"]) != 1 || filters["dangling"][0] != "true" { - t.Errorf("ListImages(dangling=[true]): Wrong filter map. Want dangling=[true], got dangling=%v", filters["dangling"]) - } -} - -func TestImageHistory(t *testing.T) { - body := `[ - { - "Id": "25daec02219d2d852f7526137213a9b199926b4b24e732eab5b8bc6c49bd470e", - "Tags": [ - "debian:7.6", - "debian:latest", - "debian:7", - "debian:wheezy" - ], - "Created": 1409856216, - "CreatedBy": "/bin/sh -c #(nop) CMD [/bin/bash]" - }, - { - "Id": "41026a5347fb5be6ed16115bf22df8569697139f246186de9ae8d4f67c335dce", - "Created": 1409856213, - "CreatedBy": "/bin/sh -c #(nop) ADD file:1ee9e97209d00e3416a4543b23574cc7259684741a46bbcbc755909b8a053a38 in /", - "Size": 85178663 - }, - { - "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158", - "Tags": [ - "scratch:latest" - ], - "Created": 1371157430 - } -]` - var expected []ImageHistory - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - history, err := client.ImageHistory("debian:latest") - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(history, expected) { - t.Errorf("ImageHistory: Wrong return value. Want %#v. Got %#v.", expected, history) - } -} - -func TestRemoveImage(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - err := client.RemoveImage(name) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) - err := client.RemoveImage("test:") - if err != ErrNoSuchImage { - t.Errorf("RemoveImage: wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestRemoveImageExtended(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - err := client.RemoveImageExtended(name, RemoveImageOptions{Force: true, NoPrune: true}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } - expectedQuery := "force=1&noprune=1" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestInspectImage(t *testing.T) { - body := `{ - "Id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - "Parent":"27cf784147099545", - "Created":"2013-03-23T22:24:18.818426Z", - "Container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", - "ContainerConfig":{"Memory":1}, - "VirtualSize":12345 -}` - - created, err := time.Parse(time.RFC3339Nano, "2013-03-23T22:24:18.818426Z") - if err != nil { - t.Fatal(err) - } - - expected := Image{ - ID: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - Parent: "27cf784147099545", - Created: created, - Container: "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", - ContainerConfig: Config{ - Memory: 1, - }, - VirtualSize: 12345, - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - image, err := client.InspectImage(expected.ID) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*image, expected) { - t.Errorf("InspectImage(%q): Wrong image returned. Want %#v. Got %#v.", expected.ID, expected, *image) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("InspectImage(%q): Wrong HTTP method. Want GET. Got %s.", expected.ID, req.Method) - } - u, _ := url.Parse(client.getURL("/images/" + expected.ID + "/json")) - if req.URL.Path != u.Path { - t.Errorf("InspectImage(%q): Wrong request URL. Want %q. Got %q.", expected.ID, u.Path, req.URL.Path) - } -} - -func TestInspectImageNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) - name := "test" - image, err := client.InspectImage(name) - if image != nil { - t.Errorf("InspectImage(%q): expected image, got %#v.", name, image) - } - if err != ErrNoSuchImage { - t.Errorf("InspectImage(%q): wrong error. Want %#v. Got %#v.", name, ErrNoSuchImage, err) - } -} - -func TestPushImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - expected := "Pushing 1/100" - if buf.String() != expected { - t.Errorf("PushImage: Wrong output. Want %q. Got %q.", expected, buf.String()) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PushImage: Wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/images/test/push")) - if req.URL.Path != u.Path { - t.Errorf("PushImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } - if query := req.URL.Query().Encode(); query != "" { - t.Errorf("PushImage: Wrong query string. Want no parameters, got %q.", query) - } - - auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) - if err != nil { - t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) - } - if strings.TrimSpace(string(auth)) != "{}" { - t.Errorf("PushImage: wrong body. Want %q. Got %q.", - base64.URLEncoding.EncodeToString([]byte("{}")), req.Header.Get("X-Registry-Auth")) - } -} - -func TestPushImageWithRawJSON(t *testing.T) { - body := ` - {"status":"Pushing..."} - {"status":"Pushing", "progress":"1/? (n/a)", "progressDetail":{"current":1}}} - {"status":"Image successfully pushed"} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - - err := client.PushImage(PushImageOptions{ - Name: "test", - OutputStream: &buf, - RawJSONStream: true, - }, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("PushImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) - } -} - -func TestPushImageWithAuthentication(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - inputAuth := AuthConfiguration{ - Username: "gopher", - Password: "gopher123", - Email: "gopher@tsuru.io", - } - err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, inputAuth) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - var gotAuth AuthConfiguration - - auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) - if err != nil { - t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) - } - - err = json.Unmarshal(auth, &gotAuth) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(gotAuth, inputAuth) { - t.Errorf("PushImage: wrong auth configuration. Want %#v. Got %#v.", inputAuth, gotAuth) - } -} - -func TestPushImageCustomRegistry(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var authConfig AuthConfiguration - var buf bytes.Buffer - opts := PushImageOptions{ - Name: "test", Registry: "docker.tsuru.io", - OutputStream: &buf, - } - err := client.PushImage(opts, authConfig) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedQuery := "registry=docker.tsuru.io" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestPushImageNoName(t *testing.T) { - client := Client{} - err := client.PushImage(PushImageOptions{}, AuthConfiguration{}) - if err != ErrNoSuchImage { - t.Errorf("PushImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestPullImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PullImage(PullImageOptions{Repository: "base", OutputStream: &buf}, - AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - expected := "Pulling 1/100" - if buf.String() != expected { - t.Errorf("PullImage: Wrong output. Want %q. Got %q.", expected, buf.String()) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("PullImage: Wrong HTTP method. Want POST. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/images/create")) - if req.URL.Path != u.Path { - t.Errorf("PullImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } - expectedQuery := "fromImage=base" - if query := req.URL.Query().Encode(); query != expectedQuery { - t.Errorf("PullImage: Wrong query strin. Want %q. Got %q.", expectedQuery, query) - } -} - -func TestPullImageWithRawJSON(t *testing.T) { - body := ` - {"status":"Pulling..."} - {"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - err := client.PullImage(PullImageOptions{ - Repository: "base", - OutputStream: &buf, - RawJSONStream: true, - }, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("PullImage: Wrong raw output. Want %q. Got %q", body, buf.String()) - } -} - -func TestPullImageWithoutOutputStream(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageCustomRegistry(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - OutputStream: &buf, - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageTag(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := PullImageOptions{ - Repository: "base", - Registry: "docker.tsuru.io", - Tag: "latest", - OutputStream: &buf, - } - err := client.PullImage(opts, AuthConfiguration{}) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}, "tag": {"latest"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestPullImageNoRepository(t *testing.T) { - var opts PullImageOptions - client := Client{} - err := client.PullImage(opts, AuthConfiguration{}) - if err != ErrNoSuchImage { - t.Errorf("PullImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) - } -} - -func TestImportImageFromUrl(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := ImportImageOptions{ - Source: "http://mycompany.com/file.tar", - Repository: "testimage", - Tag: "tag", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestImportImageFromInput(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - in := bytes.NewBufferString("tar content") - var buf bytes.Buffer - opts := ImportImageOptions{ - Source: "-", Repository: "testimage", - InputStream: in, OutputStream: &buf, - Tag: "tag", - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) - } - e := "tar content" - if string(body) != e { - t.Errorf("ImportImage: wrong body. Want %#v. Got %#v.", e, string(body)) - } -} - -func TestImportImageDoesNotPassesInputIfSourceIsNotDash(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - in := bytes.NewBufferString("foo") - opts := ImportImageOptions{ - Source: "http://test.com/container.tar", Repository: "testimage", - InputStream: in, OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) - } - if string(body) != "" { - t.Errorf("ImportImage: wrong body. Want nothing. Got %#v.", string(body)) - } -} - -func TestImportImageShouldPassTarContentToBodyWhenSourceIsFilePath(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - tarPath := "testing/data/container.tar" - opts := ImportImageOptions{ - Source: tarPath, Repository: "testimage", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - tar, err := os.Open(tarPath) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - tarContent, err := ioutil.ReadAll(tar) - body, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tarContent, body) { - t.Errorf("ImportImage: wrong body. Want %#v content. Got %#v.", tarPath, body) - } -} - -func TestImportImageShouldChangeSourceToDashWhenItsAFilePath(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - tarPath := "testing/data/container.tar" - opts := ImportImageOptions{ - Source: tarPath, Repository: "testimage", - OutputStream: &buf, - } - err := client.ImportImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"fromSrc": {"-"}, "repo": {opts.Repository}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - NoCache: true, - SuppressOutput: true, - Pull: true, - RmTmpContainer: true, - ForceRmTmpContainer: true, - Memory: 1024, - Memswap: 2048, - CPUShares: 10, - CPUSetCPUs: "0-3", - Ulimits: []ULimit{ULimit{Name: "nofile", Soft: 100, Hard: 200}}, - InputStream: &buf, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil && strings.Index(err.Error(), "build image fail") == -1 { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{ - "t": {opts.Name}, - "nocache": {"1"}, - "q": {"1"}, - "pull": {"1"}, - "rm": {"1"}, - "forcerm": {"1"}, - "memory": {"1024"}, - "memswap": {"2048"}, - "cpushares": {"10"}, - "cpusetcpus": {"0-3"}, - "ulimits": {"[{\"Name\":\"nofile\",\"Soft\":100,\"Hard\":200}]"}, - } - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageParametersForRemoteBuild(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - Remote: "testing/data/container.tar", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"t": {opts.Name}, "remote": {opts.Remote}, "q": {"1"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestBuildImageMissingRepoAndNilInput(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != ErrMissingRepo { - t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingRepo, err) - } -} - -func TestBuildImageMissingOutputStream(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := BuildImageOptions{Name: "testImage"} - err := client.BuildImage(opts) - if err != ErrMissingOutputStream { - t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingOutputStream, err) - } -} - -func TestBuildImageWithRawJSON(t *testing.T) { - body := ` - {"stream":"Step 0 : FROM ubuntu:latest\n"} - {"stream":" ---\u003e 4300eb9d3c8d\n"} - {"stream":"Step 1 : MAINTAINER docker \n"} - {"stream":" ---\u003e Using cache\n"} - {"stream":" ---\u003e 3a3ed758c370\n"} - {"stream":"Step 2 : CMD /usr/bin/top\n"} - {"stream":" ---\u003e Running in 36b1479cc2e4\n"} - {"stream":" ---\u003e 4b6188aebe39\n"} - {"stream":"Removing intermediate container 36b1479cc2e4\n"} - {"stream":"Successfully built 4b6188aebe39\n"} - ` - fakeRT := &FakeRoundTripper{ - message: body, - status: http.StatusOK, - header: map[string]string{ - "Content-Type": "application/json", - }, - } - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Name: "testImage", - RmTmpContainer: true, - InputStream: &buf, - OutputStream: &buf, - RawJSONStream: true, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - if buf.String() != body { - t.Errorf("BuildImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) - } -} - -func TestBuildImageRemoteWithoutName(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - var buf bytes.Buffer - opts := BuildImageOptions{ - Remote: "testing/data/container.tar", - SuppressOutput: true, - OutputStream: &buf, - } - err := client.BuildImage(opts) - if err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := map[string][]string{"t": {opts.Remote}, "remote": {opts.Remote}, "q": {"1"}} - got := map[string][]string(req.URL.Query()) - if !reflect.DeepEqual(got, expected) { - t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestTagImageParameters(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := TagImageOptions{Repo: "testImage"} - err := client.TagImage("base", opts) - if err != nil && strings.Index(err.Error(), "tag image fail") == -1 { - t.Fatal(err) - } - req := fakeRT.requests[0] - expected := "http://localhost:4243/images/base/tag?repo=testImage" - got := req.URL.String() - if !reflect.DeepEqual(got, expected) { - t.Errorf("TagImage: wrong query string. Want %#v. Got %#v.", expected, got) - } -} - -func TestTagImageMissingRepo(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := TagImageOptions{Repo: "testImage"} - err := client.TagImage("", opts) - if err != ErrNoSuchImage { - t.Errorf("TestTag: wrong error returned. Want %#v. Got %#v.", - ErrNoSuchImage, err) - } -} - -func TestIsUrl(t *testing.T) { - url := "http://foo.bar/" - result := isURL(url) - if !result { - t.Errorf("isURL: wrong match. Expected %#v to be a url. Got %#v.", url, result) - } - url = "/foo/bar.tar" - result = isURL(url) - if result { - t.Errorf("isURL: wrong match. Expected %#v to not be a url. Got %#v", url, result) - } -} - -func TestLoadImage(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - tar, err := os.Open("testing/data/container.tar") - if err != nil { - t.Fatal(err) - } else { - defer tar.Close() - } - opts := LoadImageOptions{InputStream: tar} - err = client.LoadImage(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "POST" { - t.Errorf("LoadImage: wrong method. Expected %q. Got %q.", "POST", req.Method) - } - if req.URL.Path != "/images/load" { - t.Errorf("LoadImage: wrong URL. Expected %q. Got %q.", "/images/load", req.URL.Path) - } -} - -func TestExportImage(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImageOptions{Name: "testimage", OutputStream: &buf} - err := client.ExportImage(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) - } - expectedPath := "/images/testimage/get" - if req.URL.Path != expectedPath { - t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expectedPath, req.URL.Path) - } -} - -func TestExportImages(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImagesOptions{Names: []string{"testimage1", "testimage2:latest"}, OutputStream: &buf} - err := client.ExportImages(opts) - if nil != err { - t.Error(err) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) - } - expected := "http://localhost:4243/images/get?names=testimage1&names=testimage2%3Alatest" - got := req.URL.String() - if !reflect.DeepEqual(got, expected) { - t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expected, got) - } -} - -func TestExportImagesNoNames(t *testing.T) { - var buf bytes.Buffer - fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} - client := newTestClient(fakeRT) - opts := ExportImagesOptions{Names: []string{}, OutputStream: &buf} - err := client.ExportImages(opts) - if err == nil { - t.Error("Expected an error") - } - if err != ErrMustSpecifyNames { - t.Error(err) - } -} - -func TestSearchImages(t *testing.T) { - body := `[ - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - }, - { - "description":"A container with Cassandra 2.0.3", - "is_official":true, - "is_automated":false, - "name":"poklet/cassandra", - "star_count":17 - } - , - { - "description":"A container with Cassandra 2.0.3", - "is_official":false, - "is_automated":true, - "name":"poklet/cassandra", - "star_count":17 - } -]` - var expected []APIImageSearch - err := json.Unmarshal([]byte(body), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - result, err := client.SearchImages("cassandra") - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("SearchImages: Wrong return value. Want %#v. Got %#v.", expected, result) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go deleted file mode 100644 index ceaf076eda6..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/misc_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 go-dockerclient 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 docker - -import ( - "net/http" - "net/url" - "reflect" - "sort" - "testing" -) - -type DockerVersion struct { - Version string - GitCommit string - GoVersion string -} - -func TestVersion(t *testing.T) { - body := `{ - "Version":"0.2.2", - "GitCommit":"5a2a5cc+CHANGES", - "GoVersion":"go1.0.3" -}` - fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(&fakeRT) - expected := DockerVersion{ - Version: "0.2.2", - GitCommit: "5a2a5cc+CHANGES", - GoVersion: "go1.0.3", - } - version, err := client.Version() - if err != nil { - t.Fatal(err) - } - - if result := version.Get("Version"); result != expected.Version { - t.Errorf("Version(): Wrong result. Want %#v. Got %#v.", expected.Version, version.Get("Version")) - } - if result := version.Get("GitCommit"); result != expected.GitCommit { - t.Errorf("GitCommit(): Wrong result. Want %#v. Got %#v.", expected.GitCommit, version.Get("GitCommit")) - } - if result := version.Get("GoVersion"); result != expected.GoVersion { - t.Errorf("GoVersion(): Wrong result. Want %#v. Got %#v.", expected.GoVersion, version.Get("GoVersion")) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("Version(): wrong request method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/version")) - if req.URL.Path != u.Path { - t.Errorf("Version(): wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestVersionError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - version, err := client.Version() - if version != nil { - t.Errorf("Version(): expected value, got %#v.", version) - } - if err == nil { - t.Error("Version(): unexpected error") - } -} - -func TestInfo(t *testing.T) { - body := `{ - "Containers":11, - "Images":16, - "Debug":0, - "NFd":11, - "NGoroutines":21, - "MemoryLimit":1, - "SwapLimit":0 -}` - fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(&fakeRT) - expected := Env{} - expected.SetInt("Containers", 11) - expected.SetInt("Images", 16) - expected.SetBool("Debug", false) - expected.SetInt("NFd", 11) - expected.SetInt("NGoroutines", 21) - expected.SetBool("MemoryLimit", true) - expected.SetBool("SwapLimit", false) - info, err := client.Info() - if err != nil { - t.Fatal(err) - } - infoSlice := []string(*info) - expectedSlice := []string(expected) - sort.Strings(infoSlice) - sort.Strings(expectedSlice) - if !reflect.DeepEqual(expectedSlice, infoSlice) { - t.Errorf("Info(): Wrong result.\nWant %#v.\nGot %#v.", expected, *info) - } - req := fakeRT.requests[0] - if req.Method != "GET" { - t.Errorf("Info(): Wrong HTTP method. Want GET. Got %s.", req.Method) - } - u, _ := url.Parse(client.getURL("/info")) - if req.URL.Path != u.Path { - t.Errorf("Info(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestInfoError(t *testing.T) { - fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} - client := newTestClient(fakeRT) - version, err := client.Info() - if version != nil { - t.Errorf("Info(): expected value, got %#v.", version) - } - if err == nil { - t.Error("Info(): unexpected error") - } -} - -func TestParseRepositoryTag(t *testing.T) { - var tests = []struct { - input string - expectedRepo string - expectedTag string - }{ - { - "localhost.localdomain:5000/samalba/hipache:latest", - "localhost.localdomain:5000/samalba/hipache", - "latest", - }, - { - "localhost.localdomain:5000/samalba/hipache", - "localhost.localdomain:5000/samalba/hipache", - "", - }, - { - "tsuru/python", - "tsuru/python", - "", - }, - { - "tsuru/python:2.7", - "tsuru/python", - "2.7", - }, - } - for _, tt := range tests { - repo, tag := ParseRepositoryTag(tt.input) - if repo != tt.expectedRepo { - t.Errorf("ParseRepositoryTag(%q): wrong repository. Want %q. Got %q", tt.input, tt.expectedRepo, repo) - } - if tag != tt.expectedTag { - t.Errorf("ParseRepositoryTag(%q): wrong tag. Want %q. Got %q", tt.input, tt.expectedTag, tag) - } - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go deleted file mode 100644 index 970988cf477..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/network_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "encoding/json" - "net/http" - "net/url" - "reflect" - "testing" -) - -func TestListNetworks(t *testing.T) { - jsonNetworks := `[ - { - "ID": "8dfafdbc3a40", - "Name": "blah", - "Type": "bridge", - "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] - }, - { - "ID": "9fb1e39c", - "Name": "foo", - "Type": "bridge", - "Endpoints":[{"ID": "c080be979dda", "Name": "lllll2222", "Network": "9fb1e39c"}] - } -]` - var expected []Network - err := json.Unmarshal([]byte(jsonNetworks), &expected) - if err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: jsonNetworks, status: http.StatusOK}) - containers, err := client.ListNetworks() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(containers, expected) { - t.Errorf("ListNetworks: Expected %#v. Got %#v.", expected, containers) - } -} - -func TestNetworkInfo(t *testing.T) { - jsonNetwork := `{ - "ID": "8dfafdbc3a40", - "Name": "blah", - "Type": "bridge", - "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] - }` - var expected Network - err := json.Unmarshal([]byte(jsonNetwork), &expected) - if err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: jsonNetwork, status: http.StatusOK} - client := newTestClient(fakeRT) - id := "8dfafdbc3a40" - network, err := client.NetworkInfo(id) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(*network, expected) { - t.Errorf("NetworkInfo(%q): Expected %#v. Got %#v.", id, expected, network) - } - expectedURL, _ := url.Parse(client.getURL("/networks/8dfafdbc3a40")) - if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { - t.Errorf("NetworkInfo(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) - } -} - -func TestNetworkCreate(t *testing.T) { - jsonID := `{"ID": "8dfafdbc3a40"}` - jsonNetwork := `{ - "ID": "8dfafdbc3a40", - "Name": "foobar", - "Type": "bridge" - }` - var expected Network - err := json.Unmarshal([]byte(jsonNetwork), &expected) - if err != nil { - t.Fatal(err) - } - - client := newTestClient(&FakeRoundTripper{message: jsonID, status: http.StatusOK}) - opts := CreateNetworkOptions{"foobar", "bridge", nil} - network, err := client.CreateNetwork(opts) - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(*network, expected) { - t.Errorf("CreateNetwork: Expected %#v. Got %#v.", expected, network) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go deleted file mode 100644 index bb24ce56081..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/testing/server_test.go +++ /dev/null @@ -1,1843 +0,0 @@ -// Copyright 2015 go-dockerclient 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 testing - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "math/rand" - "net" - "net/http" - "net/http/httptest" - "os" - "reflect" - "strings" - "sync" - "testing" - "time" - - "github.com/fsouza/go-dockerclient" -) - -func TestNewServer(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.listener.Close() - conn, err := net.Dial("tcp", server.listener.Addr().String()) - if err != nil { - t.Fatal(err) - } - conn.Close() -} - -func TestServerStop(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - server.Stop() - _, err = net.Dial("tcp", server.listener.Addr().String()) - if err == nil { - t.Error("Unexpected error when dialing to stopped server") - } -} - -func TestServerStopNoListener(t *testing.T) { - server := DockerServer{} - server.Stop() -} - -func TestServerURL(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - url := server.URL() - if expected := "http://" + server.listener.Addr().String() + "/"; url != expected { - t.Errorf("DockerServer.URL(): Want %q. Got %q.", expected, url) - } -} - -func TestServerURLNoListener(t *testing.T) { - server := DockerServer{} - url := server.URL() - if url != "" { - t.Errorf("DockerServer.URL(): Expected empty URL on handler mode, got %q.", url) - } -} - -func TestHandleWithHook(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, func(*http.Request) { called = true }) - defer server.Stop() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("ServeHTTP did not call the hook function.") - } -} - -func TestSetHook(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - defer server.Stop() - server.SetHook(func(*http.Request) { called = true }) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("ServeHTTP did not call the hook function.") - } -} - -func TestCustomHandler(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 2) - server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - fmt.Fprint(w, "Hello world") - })) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("Did not call the custom handler") - } - if got := recorder.Body.String(); got != "Hello world" { - t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) - } -} - -func TestCustomHandlerRegexp(t *testing.T) { - var called bool - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 2) - server.CustomHandler("/containers/.*/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - called = true - fmt.Fprint(w, "Hello world") - })) - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/.*/json?all=1", nil) - server.ServeHTTP(recorder, request) - if !called { - t.Error("Did not call the custom handler") - } - if got := recorder.Body.String(); got != "Hello world" { - t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) - } -} - -func TestListContainers(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.APIContainers, 2) - for i, container := range server.containers { - expected[i] = docker.APIContainers{ - ID: container.ID, - Image: container.Image, - Command: strings.Join(container.Config.Cmd, " "), - Created: container.Created.Unix(), - Status: container.State.String(), - Ports: container.NetworkSettings.PortMappingAPI(), - Names: []string{"/" + container.Name}, - } - } - var got []docker.APIContainers - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListContainers. Want %#v. Got %#v.", expected, got) - } -} - -func TestListRunningContainers(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=0", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListRunningContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got []docker.APIContainers - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if len(got) != 0 { - t.Errorf("ListRunningContainers: Want 0. Got %d.", len(got)) - } -} - -func TestCreateContainer(t *testing.T) { - server := DockerServer{} - server.imgIDs = map[string]string{"base": "a1234"} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Container - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.containers[0] - if returned.ID != stored.ID { - t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) - } - if stored.State.Running { - t.Errorf("CreateContainer should not set container to running state.") - } - if stored.Config.User != "ubuntu" { - t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) - } - if stored.Config.Hostname != returned.ID[:12] { - t.Errorf("CreateContainer: wrong hostname. Expected: %q. Returned: %q.", returned.ID[:12], stored.Config.Hostname) - } - expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} - if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { - t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) - } -} - -func TestCreateContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.imgIDs = map[string]string{"base": "a1234"} - server.cChan = ch - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if notified := <-ch; notified != server.containers[0] { - t.Errorf("CreateContainer: did not notify the proper container. Want %q. Got %q.", server.containers[0].ID, notified.ID) - } -} - -func TestCreateContainerInvalidBody(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader("whaaaaaat---")) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCreateContainerDuplicateName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.imgIDs = map[string]string{"base": "a1234"} - addContainers(&server, 1) - server.containers[0].Name = "mycontainer" - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create?name=mycontainer", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusConflict { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusConflict, recorder.Code) - } -} - -func TestCreateMultipleContainersEmptyName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - server.imgIDs = map[string]string{"base": "a1234"} - addContainers(&server, 1) - server.containers[0].Name = "" - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - var returned docker.Container - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.containers[1] - if returned.ID != stored.ID { - t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) - } - if stored.State.Running { - t.Errorf("CreateContainer should not set container to running state.") - } - if stored.Config.User != "ubuntu" { - t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) - } - expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} - if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { - t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) - } -} - -func TestCreateContainerInvalidName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], -"Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create?name=myapp/container1", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } - expectedBody := "Invalid container name\n" - if got := recorder.Body.String(); got != expectedBody { - t.Errorf("CreateContainer: wrong body. Want %q. Got %q.", expectedBody, got) - } -} - -func TestCreateContainerImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, -"PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], -"Image":"base", "Volumes":{}, "VolumesFrom":""}` - request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRenameContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - newName := server.containers[0].Name + "abc" - path := fmt.Sprintf("/containers/%s/rename?name=%s", server.containers[0].ID, newName) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - container := server.containers[0] - if container.Name != newName { - t.Errorf("RenameContainer: did not rename the container. Want %q. Got %q.", newName, container.Name) - } -} - -func TestRenameContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/containers/blabla/rename?name=something", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestCommitContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("CommitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := fmt.Sprintf(`{"ID":"%s"}`, server.images[0].ID) - if got := recorder.Body.String(); got != expected { - t.Errorf("CommitContainer: wrong response body. Want %q. Got %q.", expected, got) - } -} - -func TestCommitContainerComplete(t *testing.T) { - server := DockerServer{} - server.imgIDs = make(map[string]string) - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&m=saving&author=developers" - queryString += `&run={"Cmd": ["cat", "/world"],"PortSpecs":["22"]}` - request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) - server.ServeHTTP(recorder, request) - image := server.images[0] - if image.Parent != server.containers[0].Image { - t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) - } - if image.Container != server.containers[0].ID { - t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) - } - message := "saving" - if image.Comment != message { - t.Errorf("CommitContainer: wrong comment (commit message). Want %q. Got %q.", message, image.Comment) - } - author := "developers" - if image.Author != author { - t.Errorf("CommitContainer: wrong author. Want %q. Got %q.", author, image.Author) - } - if id := server.imgIDs["tsuru/python"]; id != image.ID { - t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) - } - portSpecs := []string{"22"} - if !reflect.DeepEqual(image.Config.PortSpecs, portSpecs) { - t.Errorf("CommitContainer: wrong port spec in config. Want %#v. Got %#v.", portSpecs, image.Config.PortSpecs) - } - cmd := []string{"cat", "/world"} - if !reflect.DeepEqual(image.Config.Cmd, cmd) { - t.Errorf("CommitContainer: wrong cmd in config. Want %#v. Got %#v.", cmd, image.Config.Cmd) - } -} - -func TestCommitContainerWithTag(t *testing.T) { - server := DockerServer{} - server.imgIDs = make(map[string]string) - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&tag=v1" - request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) - server.ServeHTTP(recorder, request) - image := server.images[0] - if image.Parent != server.containers[0].Image { - t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) - } - if image.Container != server.containers[0].ID { - t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) - } - if id := server.imgIDs["tsuru/python:v1"]; id != image.ID { - t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) - } -} - -func TestCommitContainerInvalidRun(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID+"&run=abc---", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCommitContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/commit?container=abc123", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestInspectContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/json", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("InspectContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := server.containers[0] - var got docker.Container - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got.Config, expected.Config) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } - if !reflect.DeepEqual(got.NetworkSettings, expected.NetworkSettings) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } - got.State.StartedAt = expected.State.StartedAt - got.State.FinishedAt = expected.State.FinishedAt - got.Config = expected.Config - got.Created = expected.Created - got.NetworkSettings = expected.NetworkSettings - if !reflect.DeepEqual(got, *expected) { - t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) - } -} - -func TestInspectContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/abc123/json", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("InspectContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTopContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got docker.TopResult - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got.Titles, []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}) { - t.Fatalf("TopContainer: Unexpected titles, got: %#v", got.Titles) - } - if len(got.Processes) != 1 { - t.Fatalf("TopContainer: Unexpected process len, got: %d", len(got.Processes)) - } - if got.Processes[0][len(got.Processes[0])-1] != "ls -la .." { - t.Fatalf("TopContainer: Unexpected command name, got: %s", got.Processes[0][len(got.Processes[0])-1]) - } -} - -func TestTopContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/xyz/top", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTopContainerStopped(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } -} - -func TestStartContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - memory := int64(536870912) - hostConfig := docker.HostConfig{Memory: memory} - configBytes, err := json.Marshal(hostConfig) - if err != nil { - t.Fatal(err) - } - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer(configBytes)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if !server.containers[0].State.Running { - t.Error("StartContainer: did not set the container to running state") - } - if gotMemory := server.containers[0].HostConfig.Memory; gotMemory != memory { - t.Errorf("StartContainer: wrong HostConfig. Wants %d of memory. Got %d", memory, gotMemory) - } -} - -func TestStartContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.cChan = ch - addContainers(&server, 1) - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[1].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("{}"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if notified := <-ch; notified != server.containers[1] { - t.Errorf("StartContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) - } -} - -func TestStartContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/start" - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestStartContainerAlreadyRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotModified { - t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotModified, recorder.Code) - } -} - -func TestStopContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Running { - t.Error("StopContainer: did not stop the container") - } -} - -func TestKillContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/kill", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("KillContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Running { - t.Error("KillContainer: did not stop the container") - } -} - -func TestStopContainerWithNotifyChannel(t *testing.T) { - ch := make(chan *docker.Container, 1) - server := DockerServer{} - server.cChan = ch - addContainers(&server, 1) - addContainers(&server, 1) - server.containers[1].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[1].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if notified := <-ch; notified != server.containers[1] { - t.Errorf("StopContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) - } -} - -func TestStopContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/stop" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestStopContainerNotRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestPauseContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if !server.containers[0].State.Paused { - t.Error("PauseContainer: did not pause the container") - } -} - -func TestPauseContainerAlreadyPaused(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Paused = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestPauseContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/pause" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestUnpauseContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Paused = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if server.containers[0].State.Paused { - t.Error("UnpauseContainer: did not unpause the container") - } -} - -func TestUnpauseContainerNotPaused(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestUnpauseContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/unpause" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestWaitContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - go func() { - server.cMut.Lock() - server.containers[0].State.Running = false - server.cMut.Unlock() - }() - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := `{"StatusCode":0}` + "\n" - if body := recorder.Body.String(); body != expected { - t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestWaitContainerStatus(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - server.containers[0].State.ExitCode = 63 - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := `{"StatusCode":63}` + "\n" - if body := recorder.Body.String(); body != expected { - t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestWaitContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := "/containers/abc123/wait" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("WaitContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -type HijackableResponseRecorder struct { - httptest.ResponseRecorder - readCh chan []byte -} - -func (r *HijackableResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { - myConn, otherConn := net.Pipe() - r.readCh = make(chan []byte) - go func() { - data, _ := ioutil.ReadAll(myConn) - r.readCh <- data - }() - return otherConn, nil, nil -} - -func (r *HijackableResponseRecorder) HijackBuffer() string { - return string(<-r.readCh) -} - -func TestAttachContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := &HijackableResponseRecorder{} - path := fmt.Sprintf("/containers/%s/attach?logs=1", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - lines := []string{ - "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", - "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", - "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", - } - expected := strings.Join(lines, "\n") + "\n" - if body := recorder.HijackBuffer(); body != expected { - t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestAttachContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := &HijackableResponseRecorder{} - path := "/containers/abc123/attach?logs=1" - request, _ := http.NewRequest("POST", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("AttachContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestAttachContainerWithStreamBlocks(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - path := fmt.Sprintf("/containers/%s/attach?logs=1&stdout=1&stream=1", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, nil) - done := make(chan string) - go func() { - recorder := &HijackableResponseRecorder{} - server.ServeHTTP(recorder, request) - done <- recorder.HijackBuffer() - }() - select { - case <-done: - t.Fatalf("attach stream returned before container is stopped") - case <-time.After(500 * time.Millisecond): - } - server.cMut.Lock() - server.containers[0].State.Running = false - server.cMut.Unlock() - var body string - select { - case body = <-done: - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for attach to finish") - } - lines := []string{ - "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", - "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", - "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", - } - expected := strings.Join(lines, "\n") + "\n" - if body != expected { - t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) - } -} - -func TestRemoveContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestRemoveContainerByName(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].Name) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestRemoveContainerNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/abc123") - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestRemoveContainerRunning(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s", server.containers[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusInternalServerError { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) - } - if len(server.containers) < 1 { - t.Error("RemoveContainer: should not remove the container.") - } -} - -func TestRemoveContainerRunningForce(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.containers[0].State.Running = true - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s?%s", server.containers[0].ID, "force=1") - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.containers) > 0 { - t.Error("RemoveContainer: did not remove the container.") - } -} - -func TestPullImage(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/create?fromImage=base", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if len(server.images) != 1 { - t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) - } - if _, ok := server.imgIDs["base"]; !ok { - t.Error("PullImage: Repository should not be empty.") - } -} - -func TestPullImageWithTag(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/create?fromImage=base&tag=tag", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if len(server.images) != 1 { - t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) - } - if _, ok := server.imgIDs["base:tag"]; !ok { - t.Error("PullImage: Repository should not be empty.") - } -} - -func TestPushImage(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestPushImageWithTag(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python:v1": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push?tag=v1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestPushImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func TestTagImage(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python"] { - t.Errorf("TagImage: did not tag the image") - } -} - -func TestTagImageWithRepoAndTag(t *testing.T) { - server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python&tag=v1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python:v1"] { - t.Errorf("TagImage: did not tag the image") - } -} - -func TestTagImageNotFound(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/images/tsuru/python/tag", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNotFound { - t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) - } -} - -func addContainers(server *DockerServer, n int) { - server.cMut.Lock() - defer server.cMut.Unlock() - for i := 0; i < n; i++ { - date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) - container := docker.Container{ - Name: fmt.Sprintf("%x", rand.Int()%10000), - ID: fmt.Sprintf("%x", rand.Int()%10000), - Created: date, - Path: "ls", - Args: []string{"-la", ".."}, - Config: &docker.Config{ - Hostname: fmt.Sprintf("docker-%d", i), - AttachStdout: true, - AttachStderr: true, - Env: []string{"ME=you", fmt.Sprintf("NUMBER=%d", i)}, - Cmd: []string{"ls", "-la", ".."}, - Image: "base", - }, - State: docker.State{ - Running: false, - Pid: 400 + i, - ExitCode: 0, - StartedAt: date, - }, - Image: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", - NetworkSettings: &docker.NetworkSettings{ - IPAddress: fmt.Sprintf("10.10.10.%d", i+2), - IPPrefixLen: 24, - Gateway: "10.10.10.1", - Bridge: "docker0", - PortMapping: map[string]docker.PortMapping{ - "Tcp": {"8888": fmt.Sprintf("%d", 49600+i)}, - }, - }, - ResolvConfPath: "/etc/resolv.conf", - } - server.containers = append(server.containers, &container) - } -} - -func addImages(server *DockerServer, n int, repo bool) { - server.iMut.Lock() - defer server.iMut.Unlock() - if server.imgIDs == nil { - server.imgIDs = make(map[string]string) - } - for i := 0; i < n; i++ { - date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) - image := docker.Image{ - ID: fmt.Sprintf("%x", rand.Int()%10000), - Created: date, - } - server.images = append(server.images, image) - if repo { - repo := "docker/python-" + image.ID - server.imgIDs[repo] = image.ID - } - } -} - -func TestListImages(t *testing.T) { - server := DockerServer{} - addImages(&server, 2, true) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/images/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListImages: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.APIImages, 2) - for i, image := range server.images { - expected[i] = docker.APIImages{ - ID: image.ID, - Created: image.Created.Unix(), - RepoTags: []string{"docker/python-" + image.ID}, - } - } - var got []docker.APIImages - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListImages. Want %#v. Got %#v.", expected, got) - } -} - -func TestRemoveImage(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, false) - server.buildMuxer() - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/images/%s", server.images[0].ID) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.images) > 0 { - t.Error("RemoveImage: did not remove the image.") - } -} - -func TestRemoveImageByName(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, true) - server.buildMuxer() - recorder := httptest.NewRecorder() - imgName := "docker/python-" + server.images[0].ID - path := "/images/" + imgName - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) - } - if len(server.images) > 0 { - t.Error("RemoveImage: did not remove the image.") - } - _, ok := server.imgIDs[imgName] - if ok { - t.Error("RemoveImage: did not remove image tag name.") - } -} - -func TestRemoveImageWithMultipleTags(t *testing.T) { - server := DockerServer{} - addImages(&server, 1, true) - server.buildMuxer() - imgID := server.images[0].ID - imgName := "docker/python-" + imgID - server.imgIDs["docker/python-wat"] = imgID - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/images/%s", imgName) - request, _ := http.NewRequest("DELETE", path, nil) - server.ServeHTTP(recorder, request) - _, ok := server.imgIDs[imgName] - if ok { - t.Error("RemoveImage: did not remove image tag name.") - } - id, ok := server.imgIDs["docker/python-wat"] - if !ok { - t.Error("RemoveImage: removed the wrong tag name.") - } - if id != imgID { - t.Error("RemoveImage: disassociated the wrong ID from the tag") - } - if len(server.images) < 1 { - t.Fatal("RemoveImage: removed the image, but should keep it") - } - if server.images[0].ID != imgID { - t.Error("RemoveImage: changed the ID of the image!") - } -} - -func TestPrepareFailure(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - errorID := "my_error" - server.PrepareFailure(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } -} - -func TestPrepareMultiFailures(t *testing.T) { - server := DockerServer{multiFailures: []map[string]string{}} - server.buildMuxer() - errorID := "multi error" - server.PrepareMultiFailures(errorID, "containers/json") - server.PrepareMultiFailures(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - if recorder.Body.String() != errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - if recorder.Body.String() == errorID+"\n" { - t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) - } -} - -func TestRemoveFailure(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - errorID := "my_error" - server.PrepareFailure(errorID, "containers/json") - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } - server.ResetFailure(errorID) - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("RemoveFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } -} - -func TestResetMultiFailures(t *testing.T) { - server := DockerServer{multiFailures: []map[string]string{}} - server.buildMuxer() - errorID := "multi error" - server.PrepareMultiFailures(errorID, "containers/json") - server.PrepareMultiFailures(errorID, "containers/json") - if len(server.multiFailures) != 2 { - t.Errorf("PrepareMultiFailures: error adding multi failures.") - } - server.ResetMultiFailures() - if len(server.multiFailures) != 0 { - t.Errorf("ResetMultiFailures: error reseting multi failures.") - } -} - -func TestMutateContainer(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - server.containers = append(server.containers, &docker.Container{ID: "id123"}) - state := docker.State{Running: false, ExitCode: 1} - err := server.MutateContainer("id123", state) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(server.containers[0].State, state) { - t.Errorf("Wrong state after mutation.\nWant %#v.\nGot %#v.", - state, server.containers[0].State) - } -} - -func TestMutateContainerNotFound(t *testing.T) { - server := DockerServer{failures: make(map[string]string)} - server.buildMuxer() - state := docker.State{Running: false, ExitCode: 1} - err := server.MutateContainer("id123", state) - if err == nil { - t.Error("Unexpected error") - } - if err.Error() != "container not found" { - t.Errorf("wrong error message. Want %q. Got %q.", "container not found", err) - } -} - -func TestBuildImageWithContentTypeTar(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - imageName := "teste" - recorder := httptest.NewRecorder() - tarFile, err := os.Open("data/dockerfile.tar") - if err != nil { - t.Fatal(err) - } - defer tarFile.Close() - request, _ := http.NewRequest("POST", "/build?t=teste", tarFile) - request.Header.Add("Content-Type", "application/tar") - server.buildImage(recorder, request) - if recorder.Body.String() == "miss Dockerfile" { - t.Errorf("BuildImage: miss Dockerfile") - return - } - if _, ok := server.imgIDs[imageName]; ok == false { - t.Errorf("BuildImage: image %s not builded", imageName) - } -} - -func TestBuildImageWithRemoteDockerfile(t *testing.T) { - server := DockerServer{imgIDs: make(map[string]string)} - imageName := "teste" - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/build?t=teste&remote=http://localhost/Dockerfile", nil) - server.buildImage(recorder, request) - if _, ok := server.imgIDs[imageName]; ok == false { - t.Errorf("BuildImage: image %s not builded", imageName) - } -} - -func TestPing(t *testing.T) { - server := DockerServer{} - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/_ping", nil) - server.pingDocker(recorder, request) - if recorder.Body.String() != "" { - t.Errorf("Ping: Unexpected body: %s", recorder.Body.String()) - } - if recorder.Code != http.StatusOK { - t.Errorf("Ping: Expected code %d, got: %d", http.StatusOK, recorder.Code) - } -} - -func TestDefaultHandler(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.listener.Close() - if server.mux != server.DefaultHandler() { - t.Fatalf("DefaultHandler: Expected to return server.mux, got: %#v", server.DefaultHandler()) - } -} - -func TestCreateExecContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - serverExec := server.execs[0] - var got docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if got.ID != serverExec.ID { - t.Errorf("CreateExec: wrong value. Want %#v. Got %#v.", serverExec.ID, got.ID) - } - expected := docker.ExecInspect{ - ID: got.ID, - ProcessConfig: docker.ExecProcessConfig{ - EntryPoint: "bash", - Arguments: []string{"-c", "ls"}, - }, - Container: *server.containers[0], - } - if !reflect.DeepEqual(*serverExec, expected) { - t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, *serverExec) - } -} - -func TestInspectExecContainer(t *testing.T) { - server := DockerServer{} - addContainers(&server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - path = fmt.Sprintf("/exec/%s/json", got.ID) - request, _ = http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var got2 docker.ExecInspect - err = json.NewDecoder(recorder.Body).Decode(&got2) - if err != nil { - t.Fatal(err) - } - expected := docker.ExecInspect{ - ID: got.ID, - ProcessConfig: docker.ExecProcessConfig{ - EntryPoint: "bash", - Arguments: []string{"-c", "ls"}, - }, - Container: *server.containers[0], - } - got2.Container.State.StartedAt = expected.Container.State.StartedAt - got2.Container.State.FinishedAt = expected.Container.State.FinishedAt - got2.Container.Config = expected.Container.Config - got2.Container.Created = expected.Container.Created - got2.Container.NetworkSettings = expected.Container.NetworkSettings - if !reflect.DeepEqual(got2, expected) { - t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, got2) - } -} - -func TestStartExecContainer(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - var exec docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&exec) - if err != nil { - t.Fatal(err) - } - unleash := make(chan bool) - server.PrepareExec(exec.ID, func() { - <-unleash - }) - codes := make(chan int, 1) - sent := make(chan bool) - go func() { - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/exec/%s/start", exec.ID) - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - close(sent) - server.ServeHTTP(recorder, request) - codes <- recorder.Code - }() - <-sent - execInfo, err := waitExec(server.URL(), exec.ID, true, 5) - if err != nil { - t.Fatal(err) - } - if !execInfo.Running { - t.Error("StartExec: expected exec to be running, but it's not running") - } - close(unleash) - if code := <-codes; code != http.StatusOK { - t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) - } - execInfo, err = waitExec(server.URL(), exec.ID, false, 5) - if err != nil { - t.Fatal(err) - } - if execInfo.Running { - t.Error("StartExec: expected exec to be not running after start returns, but it's running") - } -} - -func TestStartExecContainerWildcardCallback(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Cmd": ["bash", "-c", "ls"]}` - path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - unleash := make(chan bool) - server.PrepareExec("*", func() { - <-unleash - }) - var exec docker.Exec - err := json.NewDecoder(recorder.Body).Decode(&exec) - if err != nil { - t.Fatal(err) - } - codes := make(chan int, 1) - sent := make(chan bool) - go func() { - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/exec/%s/start", exec.ID) - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", path, strings.NewReader(body)) - close(sent) - server.ServeHTTP(recorder, request) - codes <- recorder.Code - }() - <-sent - execInfo, err := waitExec(server.URL(), exec.ID, true, 5) - if err != nil { - t.Fatal(err) - } - if !execInfo.Running { - t.Error("StartExec: expected exec to be running, but it's not running") - } - close(unleash) - if code := <-codes; code != http.StatusOK { - t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) - } - execInfo, err = waitExec(server.URL(), exec.ID, false, 5) - if err != nil { - t.Fatal(err) - } - if execInfo.Running { - t.Error("StartExec: expected exec to be not running after start returns, but it's running") - } -} - -func TestStartExecContainerNotFound(t *testing.T) { - server, _ := NewServer("127.0.0.1:0", nil, nil) - addContainers(server, 1) - server.buildMuxer() - recorder := httptest.NewRecorder() - body := `{"Tty":true}` - request, _ := http.NewRequest("POST", "/exec/something-wat/start", strings.NewReader(body)) - server.ServeHTTP(recorder, request) -} - -func waitExec(url, execID string, running bool, maxTry int) (*docker.ExecInspect, error) { - client, err := docker.NewClient(url) - if err != nil { - return nil, err - } - exec, err := client.InspectExec(execID) - for i := 0; i < maxTry && exec.Running != running && err == nil; i++ { - time.Sleep(100e6) - exec, err = client.InspectExec(exec.ID) - } - return exec, err -} - -func TestStatsContainer(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - addContainers(server, 2) - server.buildMuxer() - expected := docker.Stats{} - expected.CPUStats.CPUUsage.TotalUsage = 20 - server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { - return expected - }) - recorder := httptest.NewRecorder() - path := fmt.Sprintf("/containers/%s/stats?stream=false", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("StatsContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - body := recorder.Body.Bytes() - var got docker.Stats - err = json.Unmarshal(body, &got) - if err != nil { - t.Fatal(err) - } - got.Read = time.Time{} - if !reflect.DeepEqual(got, expected) { - t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) - } -} - -type safeWriter struct { - sync.Mutex - *httptest.ResponseRecorder -} - -func (w *safeWriter) Write(buf []byte) (int, error) { - w.Lock() - defer w.Unlock() - return w.ResponseRecorder.Write(buf) -} - -func TestStatsContainerStream(t *testing.T) { - server, err := NewServer("127.0.0.1:0", nil, nil) - if err != nil { - t.Fatal(err) - } - defer server.Stop() - addContainers(server, 2) - server.buildMuxer() - expected := docker.Stats{} - expected.CPUStats.CPUUsage.TotalUsage = 20 - server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { - time.Sleep(50 * time.Millisecond) - return expected - }) - recorder := &safeWriter{ - ResponseRecorder: httptest.NewRecorder(), - } - path := fmt.Sprintf("/containers/%s/stats?stream=true", server.containers[0].ID) - request, _ := http.NewRequest("GET", path, nil) - go func() { - server.ServeHTTP(recorder, request) - }() - time.Sleep(200 * time.Millisecond) - recorder.Lock() - defer recorder.Unlock() - body := recorder.Body.Bytes() - parts := bytes.Split(body, []byte("\n")) - if len(parts) < 2 { - t.Errorf("StatsContainer: wrong number of parts. Want at least 2. Got %#v.", len(parts)) - } - var got docker.Stats - err = json.Unmarshal(parts[0], &got) - if err != nil { - t.Fatal(err) - } - got.Read = time.Time{} - if !reflect.DeepEqual(got, expected) { - t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) - } -} - -func addNetworks(server *DockerServer, n int) { - server.netMut.Lock() - defer server.netMut.Unlock() - for i := 0; i < n; i++ { - netid := fmt.Sprintf("%x", rand.Int()%10000) - network := docker.Network{ - Name: netid, - ID: fmt.Sprintf("%x", rand.Int()%10000), - Type: "bridge", - Endpoints: []*docker.Endpoint{ - { - Name: "blah", - ID: fmt.Sprintf("%x", rand.Int()%10000), - Network: netid, - }, - }, - } - server.networks = append(server.networks, &network) - } -} - -func TestListNetworks(t *testing.T) { - server := DockerServer{} - addNetworks(&server, 2) - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/networks", nil) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusOK { - t.Errorf("ListNetworks: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) - } - expected := make([]docker.Network, 2) - for i, network := range server.networks { - expected[i] = docker.Network{ - ID: network.ID, - Name: network.Name, - Type: network.Type, - Endpoints: network.Endpoints, - } - } - var got []docker.Network - err := json.NewDecoder(recorder.Body).Decode(&got) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(got, expected) { - t.Errorf("ListNetworks. Want %#v. Got %#v.", expected, got) - } -} - -type createNetworkResponse struct { - ID string `json:"ID"` -} - -func TestCreateNetwork(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - netid := fmt.Sprintf("%x", rand.Int()%10000) - netname := fmt.Sprintf("%x", rand.Int()%10000) - body := fmt.Sprintf(`{"ID": "%s", "Name": "%s", "Type": "bridge" }`, netid, netname) - request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusCreated { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) - } - - var returned createNetworkResponse - err := json.NewDecoder(recorder.Body).Decode(&returned) - if err != nil { - t.Fatal(err) - } - stored := server.networks[0] - if returned.ID != stored.ID { - t.Errorf("CreateNetwork: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned) - } -} - -func TestCreateNetworkInvalidBody(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/networks", strings.NewReader("whaaaaaat---")) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusBadRequest { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) - } -} - -func TestCreateNetworkDuplicateName(t *testing.T) { - server := DockerServer{} - server.buildMuxer() - addNetworks(&server, 1) - server.networks[0].Name = "mynetwork" - recorder := httptest.NewRecorder() - body := fmt.Sprintf(`{"ID": "%s", "Name": "mynetwork", "Type": "bridge" }`, fmt.Sprintf("%x", rand.Int()%10000)) - request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) - server.ServeHTTP(recorder, request) - if recorder.Code != http.StatusForbidden { - t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusForbidden, recorder.Code) - } -} diff --git a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go b/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go deleted file mode 100644 index 9707c09cdce..00000000000 --- a/Godeps/_workspace/src/github.com/fsouza/go-dockerclient/volume_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2015 go-dockerclient 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 docker - -import ( - "encoding/json" - "net/http" - "net/url" - "reflect" - "testing" -) - -func TestListVolumes(t *testing.T) { - volumesData := `[ - { - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }, - { - "Name": "foo", - "Driver": "bar", - "Mountpoint": "/var/lib/docker/volumes/bar" - } -]` - body := `{ "Volumes": ` + volumesData + ` }` - var expected []Volume - if err := json.Unmarshal([]byte(volumesData), &expected); err != nil { - t.Fatal(err) - } - client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) - volumes, err := client.ListVolumes(ListVolumesOptions{}) - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(volumes, expected) { - t.Errorf("ListVolumes: Wrong return value. Want %#v. Got %#v.", expected, volumes) - } -} - -func TestCreateVolume(t *testing.T) { - body := `{ - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }` - var expected Volume - if err := json.Unmarshal([]byte(body), &expected); err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - volume, err := client.CreateVolume( - CreateVolumeOptions{ - Name: "tardis", - Driver: "local", - DriverOpts: map[string]string{ - "foo": "bar", - }, - }, - ) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(volume, &expected) { - t.Errorf("CreateVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) - } - req := fakeRT.requests[0] - expectedMethod := "POST" - if req.Method != expectedMethod { - t.Errorf("CreateVolume(): Wrong HTTP method. Want %s. Got %s.", expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes")) - if req.URL.Path != u.Path { - t.Errorf("CreateVolume(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) - } -} - -func TestInspectVolume(t *testing.T) { - body := `{ - "Name": "tardis", - "Driver": "local", - "Mountpoint": "/var/lib/docker/volumes/tardis" - }` - var expected Volume - if err := json.Unmarshal([]byte(body), &expected); err != nil { - t.Fatal(err) - } - fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} - client := newTestClient(fakeRT) - name := "tardis" - volume, err := client.InspectVolume(name) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(volume, &expected) { - t.Errorf("InspectVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) - } - req := fakeRT.requests[0] - expectedMethod := "GET" - if req.Method != expectedMethod { - t.Errorf("InspectVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes/" + name)) - if req.URL.Path != u.Path { - t.Errorf("CreateVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveVolume(t *testing.T) { - name := "test" - fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} - client := newTestClient(fakeRT) - if err := client.RemoveVolume(name); err != nil { - t.Fatal(err) - } - req := fakeRT.requests[0] - expectedMethod := "DELETE" - if req.Method != expectedMethod { - t.Errorf("RemoveVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) - } - u, _ := url.Parse(client.getURL("/volumes/" + name)) - if req.URL.Path != u.Path { - t.Errorf("RemoveVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) - } -} - -func TestRemoveVolumeNotFound(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "no such volume", status: http.StatusNotFound}) - if err := client.RemoveVolume("test:"); err != ErrNoSuchVolume { - t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrNoSuchVolume, err) - } -} - -func TestRemoveVolumeInUse(t *testing.T) { - client := newTestClient(&FakeRoundTripper{message: "volume in use and cannot be removed", status: http.StatusConflict}) - if err := client.RemoveVolume("test:"); err != ErrVolumeInUse { - t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrVolumeInUse, err) - } -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go deleted file mode 100644 index 800370136eb..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/conn_test.go +++ /dev/null @@ -1,542 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis_test - -import ( - "bufio" - "bytes" - "math" - "net" - "reflect" - "strings" - "testing" - "time" - - "github.com/garyburd/redigo/internal/redistest" - "github.com/garyburd/redigo/redis" -) - -var writeTests = []struct { - args []interface{} - expected string -}{ - { - []interface{}{"SET", "key", "value"}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n", - }, - { - []interface{}{"SET", "key", "value"}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n", - }, - { - []interface{}{"SET", "key", byte(100)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$3\r\n100\r\n", - }, - { - []interface{}{"SET", "key", 100}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$3\r\n100\r\n", - }, - { - []interface{}{"SET", "key", int64(math.MinInt64)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$20\r\n-9223372036854775808\r\n", - }, - { - []interface{}{"SET", "key", float64(1349673917.939762)}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$21\r\n1.349673917939762e+09\r\n", - }, - { - []interface{}{"SET", "key", ""}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$0\r\n\r\n", - }, - { - []interface{}{"SET", "key", nil}, - "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$0\r\n\r\n", - }, - { - []interface{}{"ECHO", true, false}, - "*3\r\n$4\r\nECHO\r\n$1\r\n1\r\n$1\r\n0\r\n", - }, -} - -func TestWrite(t *testing.T) { - for _, tt := range writeTests { - var buf bytes.Buffer - rw := bufio.ReadWriter{Writer: bufio.NewWriter(&buf)} - c := redis.NewConnBufio(rw) - err := c.Send(tt.args[0].(string), tt.args[1:]...) - if err != nil { - t.Errorf("Send(%v) returned error %v", tt.args, err) - continue - } - rw.Flush() - actual := buf.String() - if actual != tt.expected { - t.Errorf("Send(%v) = %q, want %q", tt.args, actual, tt.expected) - } - } -} - -var errorSentinel = &struct{}{} - -var readTests = []struct { - reply string - expected interface{} -}{ - { - "+OK\r\n", - "OK", - }, - { - "+PONG\r\n", - "PONG", - }, - { - "@OK\r\n", - errorSentinel, - }, - { - "$6\r\nfoobar\r\n", - []byte("foobar"), - }, - { - "$-1\r\n", - nil, - }, - { - ":1\r\n", - int64(1), - }, - { - ":-2\r\n", - int64(-2), - }, - { - "*0\r\n", - []interface{}{}, - }, - { - "*-1\r\n", - nil, - }, - { - "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n", - []interface{}{[]byte("foo"), []byte("bar"), []byte("Hello"), []byte("World")}, - }, - { - "*3\r\n$3\r\nfoo\r\n$-1\r\n$3\r\nbar\r\n", - []interface{}{[]byte("foo"), nil, []byte("bar")}, - }, - - { - // "x" is not a valid length - "$x\r\nfoobar\r\n", - errorSentinel, - }, - { - // -2 is not a valid length - "$-2\r\n", - errorSentinel, - }, - { - // "x" is not a valid integer - ":x\r\n", - errorSentinel, - }, - { - // missing \r\n following value - "$6\r\nfoobar", - errorSentinel, - }, - { - // short value - "$6\r\nxx", - errorSentinel, - }, - { - // long value - "$6\r\nfoobarx\r\n", - errorSentinel, - }, -} - -func TestRead(t *testing.T) { - for _, tt := range readTests { - rw := bufio.ReadWriter{ - Reader: bufio.NewReader(strings.NewReader(tt.reply)), - Writer: bufio.NewWriter(nil), // writer need to support Flush - } - c := redis.NewConnBufio(rw) - actual, err := c.Receive() - if tt.expected == errorSentinel { - if err == nil { - t.Errorf("Receive(%q) did not return expected error", tt.reply) - } - } else { - if err != nil { - t.Errorf("Receive(%q) returned error %v", tt.reply, err) - continue - } - if !reflect.DeepEqual(actual, tt.expected) { - t.Errorf("Receive(%q) = %v, want %v", tt.reply, actual, tt.expected) - } - } - } -} - -var testCommands = []struct { - args []interface{} - expected interface{} -}{ - { - []interface{}{"PING"}, - "PONG", - }, - { - []interface{}{"SET", "foo", "bar"}, - "OK", - }, - { - []interface{}{"GET", "foo"}, - []byte("bar"), - }, - { - []interface{}{"GET", "nokey"}, - nil, - }, - { - []interface{}{"MGET", "nokey", "foo"}, - []interface{}{nil, []byte("bar")}, - }, - { - []interface{}{"INCR", "mycounter"}, - int64(1), - }, - { - []interface{}{"LPUSH", "mylist", "foo"}, - int64(1), - }, - { - []interface{}{"LPUSH", "mylist", "bar"}, - int64(2), - }, - { - []interface{}{"LRANGE", "mylist", 0, -1}, - []interface{}{[]byte("bar"), []byte("foo")}, - }, - { - []interface{}{"MULTI"}, - "OK", - }, - { - []interface{}{"LRANGE", "mylist", 0, -1}, - "QUEUED", - }, - { - []interface{}{"PING"}, - "QUEUED", - }, - { - []interface{}{"EXEC"}, - []interface{}{ - []interface{}{[]byte("bar"), []byte("foo")}, - "PONG", - }, - }, -} - -func TestDoCommands(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - actual, err := c.Do(cmd.args[0].(string), cmd.args[1:]...) - if err != nil { - t.Errorf("Do(%v) returned error %v", cmd.args, err) - continue - } - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Do(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestPipelineCommands(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - if err := c.Send(cmd.args[0].(string), cmd.args[1:]...); err != nil { - t.Fatalf("Send(%v) returned error %v", cmd.args, err) - } - } - if err := c.Flush(); err != nil { - t.Errorf("Flush() returned error %v", err) - } - for _, cmd := range testCommands { - actual, err := c.Receive() - if err != nil { - t.Fatalf("Receive(%v) returned error %v", cmd.args, err) - } - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Receive(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestBlankCommmand(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - for _, cmd := range testCommands { - if err := c.Send(cmd.args[0].(string), cmd.args[1:]...); err != nil { - t.Fatalf("Send(%v) returned error %v", cmd.args, err) - } - } - reply, err := redis.Values(c.Do("")) - if err != nil { - t.Fatalf("Do() returned error %v", err) - } - if len(reply) != len(testCommands) { - t.Fatalf("len(reply)=%d, want %d", len(reply), len(testCommands)) - } - for i, cmd := range testCommands { - actual := reply[i] - if !reflect.DeepEqual(actual, cmd.expected) { - t.Errorf("Receive(%v) = %v, want %v", cmd.args, actual, cmd.expected) - } - } -} - -func TestRecvBeforeSend(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - done := make(chan struct{}) - go func() { - c.Receive() - close(done) - }() - time.Sleep(time.Millisecond) - c.Send("PING") - c.Flush() - <-done - _, err = c.Do("") - if err != nil { - t.Fatalf("error=%v", err) - } -} - -func TestError(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - c.Do("SET", "key", "val") - _, err = c.Do("HSET", "key", "fld", "val") - if err == nil { - t.Errorf("Expected err for HSET on string key.") - } - if c.Err() != nil { - t.Errorf("Conn has Err()=%v, expect nil", c.Err()) - } - _, err = c.Do("SET", "key", "val") - if err != nil { - t.Errorf("Do(SET, key, val) returned error %v, expected nil.", err) - } -} - -func TestReadDeadline(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("net.Listen returned %v", err) - } - defer l.Close() - - go func() { - for { - c, err := l.Accept() - if err != nil { - return - } - go func() { - time.Sleep(time.Second) - c.Write([]byte("+OK\r\n")) - c.Close() - }() - } - }() - - c1, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0) - if err != nil { - t.Fatalf("redis.Dial returned %v", err) - } - defer c1.Close() - - _, err = c1.Do("PING") - if err == nil { - t.Fatalf("c1.Do() returned nil, expect error") - } - if c1.Err() == nil { - t.Fatalf("c1.Err() = nil, expect error") - } - - c2, err := redis.DialTimeout(l.Addr().Network(), l.Addr().String(), 0, time.Millisecond, 0) - if err != nil { - t.Fatalf("redis.Dial returned %v", err) - } - defer c2.Close() - - c2.Send("PING") - c2.Flush() - _, err = c2.Receive() - if err == nil { - t.Fatalf("c2.Receive() returned nil, expect error") - } - if c2.Err() == nil { - t.Fatalf("c2.Err() = nil, expect error") - } -} - -// Connect to local instance of Redis running on the default port. -func ExampleDial(x int) { - c, err := redis.Dial("tcp", ":6379") - if err != nil { - // handle error - } - defer c.Close() -} - -// TextExecError tests handling of errors in a transaction. See -// http://redis.io/topics/transactions for information on how Redis handles -// errors in a transaction. -func TestExecError(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - // Execute commands that fail before EXEC is called. - - c.Do("ZADD", "k0", 0, 0) - c.Send("MULTI") - c.Send("NOTACOMMAND", "k0", 0, 0) - c.Send("ZINCRBY", "k0", 0, 0) - v, err := c.Do("EXEC") - if err == nil { - t.Fatalf("EXEC returned values %v, expected error", v) - } - - // Execute commands that fail after EXEC is called. The first command - // returns an error. - - c.Do("ZADD", "k1", 0, 0) - c.Send("MULTI") - c.Send("HSET", "k1", 0, 0) - c.Send("ZINCRBY", "k1", 0, 0) - v, err = c.Do("EXEC") - if err != nil { - t.Fatalf("EXEC returned error %v", err) - } - - vs, err := redis.Values(v, nil) - if err != nil { - t.Fatalf("Values(v) returned error %v", err) - } - - if len(vs) != 2 { - t.Fatalf("len(vs) == %d, want 2", len(vs)) - } - - if _, ok := vs[0].(error); !ok { - t.Fatalf("first result is type %T, expected error", vs[0]) - } - - if _, ok := vs[1].([]byte); !ok { - t.Fatalf("second result is type %T, expected []byte", vs[2]) - } - - // Execute commands that fail after EXEC is called. The second command - // returns an error. - - c.Do("ZADD", "k2", 0, 0) - c.Send("MULTI") - c.Send("ZINCRBY", "k2", 0, 0) - c.Send("HSET", "k2", 0, 0) - v, err = c.Do("EXEC") - if err != nil { - t.Fatalf("EXEC returned error %v", err) - } - - vs, err = redis.Values(v, nil) - if err != nil { - t.Fatalf("Values(v) returned error %v", err) - } - - if len(vs) != 2 { - t.Fatalf("len(vs) == %d, want 2", len(vs)) - } - - if _, ok := vs[0].([]byte); !ok { - t.Fatalf("first result is type %T, expected []byte", vs[0]) - } - - if _, ok := vs[1].(error); !ok { - t.Fatalf("second result is type %T, expected error", vs[2]) - } -} - -func BenchmarkDoEmpty(b *testing.B) { - b.StopTimer() - c, err := redistest.Dial() - if err != nil { - b.Fatal(err) - } - defer c.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := c.Do(""); err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkDoPing(b *testing.B) { - b.StopTimer() - c, err := redistest.Dial() - if err != nil { - b.Fatal(err) - } - defer c.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := c.Do("PING"); err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go deleted file mode 100644 index 1fe305f1685..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pool_test.go +++ /dev/null @@ -1,674 +0,0 @@ -// Copyright 2011 Gary Burd -// -// 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 redis_test - -import ( - "errors" - "io" - "reflect" - "sync" - "testing" - "time" - - "github.com/garyburd/redigo/internal/redistest" - "github.com/garyburd/redigo/redis" -) - -type poolTestConn struct { - d *poolDialer - err error - redis.Conn -} - -func (c *poolTestConn) Close() error { c.d.open -= 1; return nil } -func (c *poolTestConn) Err() error { return c.err } - -func (c *poolTestConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) { - if commandName == "ERR" { - c.err = args[0].(error) - commandName = "PING" - } - if commandName != "" { - c.d.commands = append(c.d.commands, commandName) - } - return c.Conn.Do(commandName, args...) -} - -func (c *poolTestConn) Send(commandName string, args ...interface{}) error { - c.d.commands = append(c.d.commands, commandName) - return c.Conn.Send(commandName, args...) -} - -type poolDialer struct { - t *testing.T - dialed int - open int - commands []string - dialErr error -} - -func (d *poolDialer) dial() (redis.Conn, error) { - d.dialed += 1 - if d.dialErr != nil { - return nil, d.dialErr - } - c, err := redistest.Dial() - if err != nil { - return nil, err - } - d.open += 1 - return &poolTestConn{d: d, Conn: c}, nil -} - -func (d *poolDialer) check(message string, p *redis.Pool, dialed, open int) { - if d.dialed != dialed { - d.t.Errorf("%s: dialed=%d, want %d", message, d.dialed, dialed) - } - if d.open != open { - d.t.Errorf("%s: open=%d, want %d", message, d.open, open) - } - if active := p.ActiveCount(); active != open { - d.t.Errorf("%s: active=%d, want %d", message, active, open) - } -} - -func TestPoolReuse(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - - for i := 0; i < 10; i++ { - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c1.Close() - c2.Close() - } - - d.check("before close", p, 2, 2) - p.Close() - d.check("after close", p, 2, 0) -} - -func TestPoolMaxIdle(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - for i := 0; i < 10; i++ { - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c3 := p.Get() - c3.Do("PING") - c1.Close() - c2.Close() - c3.Close() - } - d.check("before close", p, 12, 2) - p.Close() - d.check("after close", p, 12, 0) -} - -func TestPoolError(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - - c := p.Get() - c.Do("ERR", io.EOF) - if c.Err() == nil { - t.Errorf("expected c.Err() != nil") - } - c.Close() - - c = p.Get() - c.Do("ERR", io.EOF) - c.Close() - - d.check(".", p, 2, 0) -} - -func TestPoolClose(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - } - - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - c3 := p.Get() - c3.Do("PING") - - c1.Close() - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after connection closed") - } - - c2.Close() - c2.Close() - - p.Close() - - d.check("after pool close", p, 3, 1) - - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after connection and pool closed") - } - - c3.Close() - - d.check("after conn close", p, 3, 0) - - c1 = p.Get() - if _, err := c1.Do("PING"); err == nil { - t.Errorf("expected error after pool closed") - } -} - -func TestPoolTimeout(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - IdleTimeout: 300 * time.Second, - Dial: d.dial, - } - - now := time.Now() - redis.SetNowFunc(func() time.Time { return now }) - defer redis.SetNowFunc(time.Now) - - c := p.Get() - c.Do("PING") - c.Close() - - d.check("1", p, 1, 1) - - now = now.Add(p.IdleTimeout) - - c = p.Get() - c.Do("PING") - c.Close() - - d.check("2", p, 2, 1) - - p.Close() -} - -func TestPoolConcurrenSendReceive(t *testing.T) { - p := &redis.Pool{ - Dial: redistest.Dial, - } - c := p.Get() - done := make(chan error, 1) - go func() { - _, err := c.Receive() - done <- err - }() - c.Send("PING") - c.Flush() - err := <-done - if err != nil { - t.Fatalf("Receive() returned error %v", err) - } - _, err = c.Do("") - if err != nil { - t.Fatalf("Do() returned error %v", err) - } - c.Close() - p.Close() -} - -func TestPoolBorrowCheck(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - Dial: d.dial, - TestOnBorrow: func(redis.Conn, time.Time) error { return redis.Error("BLAH") }, - } - - for i := 0; i < 10; i++ { - c := p.Get() - c.Do("PING") - c.Close() - } - d.check("1", p, 10, 1) - p.Close() -} - -func TestPoolMaxActive(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - c1 := p.Get() - c1.Do("PING") - c2 := p.Get() - c2.Do("PING") - - d.check("1", p, 2, 2) - - c3 := p.Get() - if _, err := c3.Do("PING"); err != redis.ErrPoolExhausted { - t.Errorf("expected pool exhausted") - } - - c3.Close() - d.check("2", p, 2, 2) - c2.Close() - d.check("3", p, 2, 2) - - c3 = p.Get() - if _, err := c3.Do("PING"); err != nil { - t.Errorf("expected good channel, err=%v", err) - } - c3.Close() - - d.check("4", p, 2, 2) - p.Close() -} - -func TestPoolMonitorCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - c := p.Get() - c.Send("MONITOR") - c.Close() - - d.check("", p, 1, 0) - p.Close() -} - -func TestPoolPubSubCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - - c := p.Get() - c.Send("SUBSCRIBE", "x") - c.Close() - - want := []string{"SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Send("PSUBSCRIBE", "x*") - c.Close() - - want = []string{"PSUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", "ECHO"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - p.Close() -} - -func TestPoolTransactionCleanup(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 2, - MaxActive: 2, - Dial: d.dial, - } - - c := p.Get() - c.Do("WATCH", "key") - c.Do("PING") - c.Close() - - want := []string{"WATCH", "PING", "UNWATCH"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("UNWATCH") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "UNWATCH", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "PING", "DISCARD"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("DISCARD") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "DISCARD", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - c = p.Get() - c.Do("WATCH", "key") - c.Do("MULTI") - c.Do("EXEC") - c.Do("PING") - c.Close() - - want = []string{"WATCH", "MULTI", "EXEC", "PING"} - if !reflect.DeepEqual(d.commands, want) { - t.Errorf("got commands %v, want %v", d.commands, want) - } - d.commands = nil - - p.Close() -} - -func startGoroutines(p *redis.Pool, cmd string, args ...interface{}) chan error { - errs := make(chan error, 10) - for i := 0; i < cap(errs); i++ { - go func() { - c := p.Get() - _, err := c.Do(cmd, args...) - errs <- err - c.Close() - }() - } - - // Wait for goroutines to block. - time.Sleep(time.Second / 4) - - return errs -} - -func TestWaitPool(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - c := p.Get() - errs := startGoroutines(p, "PING") - d.check("before close", p, 1, 1) - c.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - d.check("done", p, 1, 1) -} - -func TestWaitPoolClose(t *testing.T) { - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - c := p.Get() - if _, err := c.Do("PING"); err != nil { - t.Fatal(err) - } - errs := startGoroutines(p, "PING") - d.check("before close", p, 1, 1) - p.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - switch err { - case nil: - t.Fatal("blocked goroutine did not get error") - case redis.ErrPoolExhausted: - t.Fatal("blocked goroutine got pool exhausted error") - } - case <-timeout: - t.Fatal("timeout waiting for blocked goroutine") - } - } - c.Close() - d.check("done", p, 1, 0) -} - -func TestWaitPoolCommandError(t *testing.T) { - testErr := errors.New("test") - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - c := p.Get() - errs := startGoroutines(p, "ERR", testErr) - d.check("before close", p, 1, 1) - c.Close() - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - if err != nil { - t.Fatal(err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - d.check("done", p, cap(errs), 0) -} - -func TestWaitPoolDialError(t *testing.T) { - testErr := errors.New("test") - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: 1, - MaxActive: 1, - Dial: d.dial, - Wait: true, - } - defer p.Close() - c := p.Get() - errs := startGoroutines(p, "ERR", testErr) - d.check("before close", p, 1, 1) - - d.dialErr = errors.New("dial") - c.Close() - - nilCount := 0 - errCount := 0 - timeout := time.After(2 * time.Second) - for i := 0; i < cap(errs); i++ { - select { - case err := <-errs: - switch err { - case nil: - nilCount++ - case d.dialErr: - errCount++ - default: - t.Fatalf("expected dial error or nil, got %v", err) - } - case <-timeout: - t.Fatalf("timeout waiting for blocked goroutine %d", i) - } - } - if nilCount != 1 { - t.Errorf("expected one nil error, got %d", nilCount) - } - if errCount != cap(errs)-1 { - t.Errorf("expected %d dial erors, got %d", cap(errs)-1, errCount) - } - d.check("done", p, cap(errs), 0) -} - -// Borrowing requires us to iterate over the idle connections, unlock the pool, -// and perform a blocking operation to check the connection still works. If -// TestOnBorrow fails, we must reacquire the lock and continue iteration. This -// test ensures that iteration will work correctly if multiple threads are -// iterating simultaneously. -func TestLocking_TestOnBorrowFails_PoolDoesntCrash(t *testing.T) { - count := 100 - - // First we'll Create a pool where the pilfering of idle connections fails. - d := poolDialer{t: t} - p := &redis.Pool{ - MaxIdle: count, - MaxActive: count, - Dial: d.dial, - TestOnBorrow: func(c redis.Conn, t time.Time) error { - return errors.New("No way back into the real world.") - }, - } - defer p.Close() - - // Fill the pool with idle connections. - b1 := sync.WaitGroup{} - b1.Add(count) - b2 := sync.WaitGroup{} - b2.Add(count) - for i := 0; i < count; i++ { - go func() { - c := p.Get() - if c.Err() != nil { - t.Errorf("pool get failed: %v", c.Err()) - } - b1.Done() - b1.Wait() - c.Close() - b2.Done() - }() - } - b2.Wait() - if d.dialed != count { - t.Errorf("Expected %d dials, got %d", count, d.dialed) - } - - // Spawn a bunch of goroutines to thrash the pool. - b2.Add(count) - for i := 0; i < count; i++ { - go func() { - c := p.Get() - if c.Err() != nil { - t.Errorf("pool get failed: %v", c.Err()) - } - c.Close() - b2.Done() - }() - } - b2.Wait() - if d.dialed != count*2 { - t.Errorf("Expected %d dials, got %d", count*2, d.dialed) - } -} - -func BenchmarkPoolGet(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - c.Close() - } -} - -func BenchmarkPoolGetErr(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - } -} - -func BenchmarkPoolGetPing(b *testing.B) { - b.StopTimer() - p := redis.Pool{Dial: redistest.Dial, MaxIdle: 2} - c := p.Get() - if err := c.Err(); err != nil { - b.Fatal(err) - } - c.Close() - defer p.Close() - b.StartTimer() - for i := 0; i < b.N; i++ { - c = p.Get() - if _, err := c.Do("PING"); err != nil { - b.Fatal(err) - } - c.Close() - } -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go deleted file mode 100644 index 707f5a4706a..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/pubsub_test.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis_test - -import ( - "fmt" - "net" - "reflect" - "sync" - "testing" - "time" - - "github.com/garyburd/redigo/internal/redistest" - "github.com/garyburd/redigo/redis" -) - -func publish(channel, value interface{}) { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - c.Do("PUBLISH", channel, value) -} - -// Applications can receive pushed messages from one goroutine and manage subscriptions from another goroutine. -func ExamplePubSubConn() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - var wg sync.WaitGroup - wg.Add(2) - - psc := redis.PubSubConn{Conn: c} - - // This goroutine receives and prints pushed notifications from the server. - // The goroutine exits when the connection is unsubscribed from all - // channels or there is an error. - go func() { - defer wg.Done() - for { - switch n := psc.Receive().(type) { - case redis.Message: - fmt.Printf("Message: %s %s\n", n.Channel, n.Data) - case redis.PMessage: - fmt.Printf("PMessage: %s %s %s\n", n.Pattern, n.Channel, n.Data) - case redis.Subscription: - fmt.Printf("Subscription: %s %s %d\n", n.Kind, n.Channel, n.Count) - if n.Count == 0 { - return - } - case error: - fmt.Printf("error: %v\n", n) - return - } - } - }() - - // This goroutine manages subscriptions for the connection. - go func() { - defer wg.Done() - - psc.Subscribe("example") - psc.PSubscribe("p*") - - // The following function calls publish a message using another - // connection to the Redis server. - publish("example", "hello") - publish("example", "world") - publish("pexample", "foo") - publish("pexample", "bar") - - // Unsubscribe from all connections. This will cause the receiving - // goroutine to exit. - psc.Unsubscribe() - psc.PUnsubscribe() - }() - - wg.Wait() - - // Output: - // Subscription: subscribe example 1 - // Subscription: psubscribe p* 2 - // Message: example hello - // Message: example world - // PMessage: p* pexample foo - // PMessage: p* pexample bar - // Subscription: unsubscribe example 1 - // Subscription: punsubscribe p* 0 -} - -func expectPushed(t *testing.T, c redis.PubSubConn, message string, expected interface{}) { - actual := c.Receive() - if !reflect.DeepEqual(actual, expected) { - t.Errorf("%s = %v, want %v", message, actual, expected) - } -} - -func TestPushed(t *testing.T) { - pc, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer pc.Close() - - nc, err := net.Dial("tcp", ":6379") - if err != nil { - t.Fatal(err) - } - defer nc.Close() - nc.SetReadDeadline(time.Now().Add(4 * time.Second)) - - c := redis.PubSubConn{Conn: redis.NewConn(nc, 0, 0)} - - c.Subscribe("c1") - expectPushed(t, c, "Subscribe(c1)", redis.Subscription{Kind: "subscribe", Channel: "c1", Count: 1}) - c.Subscribe("c2") - expectPushed(t, c, "Subscribe(c2)", redis.Subscription{Kind: "subscribe", Channel: "c2", Count: 2}) - c.PSubscribe("p1") - expectPushed(t, c, "PSubscribe(p1)", redis.Subscription{Kind: "psubscribe", Channel: "p1", Count: 3}) - c.PSubscribe("p2") - expectPushed(t, c, "PSubscribe(p2)", redis.Subscription{Kind: "psubscribe", Channel: "p2", Count: 4}) - c.PUnsubscribe() - expectPushed(t, c, "Punsubscribe(p1)", redis.Subscription{Kind: "punsubscribe", Channel: "p1", Count: 3}) - expectPushed(t, c, "Punsubscribe()", redis.Subscription{Kind: "punsubscribe", Channel: "p2", Count: 2}) - - pc.Do("PUBLISH", "c1", "hello") - expectPushed(t, c, "PUBLISH c1 hello", redis.Message{Channel: "c1", Data: []byte("hello")}) -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go deleted file mode 100644 index 92744c590b6..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/reply_test.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/garyburd/redigo/internal/redistest" - "github.com/garyburd/redigo/redis" -) - -type valueError struct { - v interface{} - err error -} - -func ve(v interface{}, err error) valueError { - return valueError{v, err} -} - -var replyTests = []struct { - name interface{} - actual valueError - expected valueError -}{ - { - "ints([v1, v2])", - ve(redis.Ints([]interface{}{[]byte("4"), []byte("5")}, nil)), - ve([]int{4, 5}, nil), - }, - { - "ints(nil)", - ve(redis.Ints(nil, nil)), - ve([]int(nil), redis.ErrNil), - }, - { - "strings([v1, v2])", - ve(redis.Strings([]interface{}{[]byte("v1"), []byte("v2")}, nil)), - ve([]string{"v1", "v2"}, nil), - }, - { - "strings(nil)", - ve(redis.Strings(nil, nil)), - ve([]string(nil), redis.ErrNil), - }, - { - "values([v1, v2])", - ve(redis.Values([]interface{}{[]byte("v1"), []byte("v2")}, nil)), - ve([]interface{}{[]byte("v1"), []byte("v2")}, nil), - }, - { - "values(nil)", - ve(redis.Values(nil, nil)), - ve([]interface{}(nil), redis.ErrNil), - }, - { - "float64(1.0)", - ve(redis.Float64([]byte("1.0"), nil)), - ve(float64(1.0), nil), - }, - { - "float64(nil)", - ve(redis.Float64(nil, nil)), - ve(float64(0.0), redis.ErrNil), - }, - { - "uint64(1)", - ve(redis.Uint64(int64(1), nil)), - ve(uint64(1), nil), - }, - { - "uint64(-1)", - ve(redis.Uint64(int64(-1), nil)), - ve(uint64(0), redis.ErrNegativeInt), - }, -} - -func TestReply(t *testing.T) { - for _, rt := range replyTests { - if rt.actual.err != rt.expected.err { - t.Errorf("%s returned err %v, want %v", rt.name, rt.actual.err, rt.expected.err) - continue - } - if !reflect.DeepEqual(rt.actual.v, rt.expected.v) { - t.Errorf("%s=%+v, want %+v", rt.name, rt.actual.v, rt.expected.v) - } - } -} - -// dial wraps DialTestDB() with a more suitable function name for examples. -func dial() (redis.Conn, error) { - return redistest.Dial() -} - -func ExampleBool() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Do("SET", "foo", 1) - exists, _ := redis.Bool(c.Do("EXISTS", "foo")) - fmt.Printf("%#v\n", exists) - // Output: - // true -} - -func ExampleInt() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Do("SET", "k1", 1) - n, _ := redis.Int(c.Do("GET", "k1")) - fmt.Printf("%#v\n", n) - n, _ = redis.Int(c.Do("INCR", "k1")) - fmt.Printf("%#v\n", n) - // Output: - // 1 - // 2 -} - -func ExampleInts() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Do("SADD", "set_with_integers", 4, 5, 6) - ints, _ := redis.Ints(c.Do("SMEMBERS", "set_with_integers")) - fmt.Printf("%#v\n", ints) - // Output: - // []int{4, 5, 6} -} - -func ExampleString() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Do("SET", "hello", "world") - s, err := redis.String(c.Do("GET", "hello")) - fmt.Printf("%#v\n", s) - // Output: - // "world" -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go deleted file mode 100644 index b57dd89695e..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/scan_test.go +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis_test - -import ( - "fmt" - "github.com/garyburd/redigo/redis" - "math" - "reflect" - "testing" -) - -var scanConversionTests = []struct { - src interface{} - dest interface{} -}{ - {[]byte("-inf"), math.Inf(-1)}, - {[]byte("+inf"), math.Inf(1)}, - {[]byte("0"), float64(0)}, - {[]byte("3.14159"), float64(3.14159)}, - {[]byte("3.14"), float32(3.14)}, - {[]byte("-100"), int(-100)}, - {[]byte("101"), int(101)}, - {int64(102), int(102)}, - {[]byte("103"), uint(103)}, - {int64(104), uint(104)}, - {[]byte("105"), int8(105)}, - {int64(106), int8(106)}, - {[]byte("107"), uint8(107)}, - {int64(108), uint8(108)}, - {[]byte("0"), false}, - {int64(0), false}, - {[]byte("f"), false}, - {[]byte("1"), true}, - {int64(1), true}, - {[]byte("t"), true}, - {[]byte("hello"), "hello"}, - {[]byte("world"), []byte("world")}, - {[]interface{}{[]byte("foo")}, []interface{}{[]byte("foo")}}, - {[]interface{}{[]byte("foo")}, []string{"foo"}}, - {[]interface{}{[]byte("hello"), []byte("world")}, []string{"hello", "world"}}, - {[]interface{}{[]byte("bar")}, [][]byte{[]byte("bar")}}, - {[]interface{}{[]byte("1")}, []int{1}}, - {[]interface{}{[]byte("1"), []byte("2")}, []int{1, 2}}, - {[]interface{}{[]byte("1"), []byte("2")}, []float64{1, 2}}, - {[]interface{}{[]byte("1")}, []byte{1}}, - {[]interface{}{[]byte("1")}, []bool{true}}, -} - -func TestScanConversion(t *testing.T) { - for _, tt := range scanConversionTests { - values := []interface{}{tt.src} - dest := reflect.New(reflect.TypeOf(tt.dest)) - values, err := redis.Scan(values, dest.Interface()) - if err != nil { - t.Errorf("Scan(%v) returned error %v", tt, err) - continue - } - if !reflect.DeepEqual(tt.dest, dest.Elem().Interface()) { - t.Errorf("Scan(%v) returned %v, want %v", tt, dest.Elem().Interface(), tt.dest) - } - } -} - -var scanConversionErrorTests = []struct { - src interface{} - dest interface{} -}{ - {[]byte("1234"), byte(0)}, - {int64(1234), byte(0)}, - {[]byte("-1"), byte(0)}, - {int64(-1), byte(0)}, - {[]byte("junk"), false}, - {redis.Error("blah"), false}, -} - -func TestScanConversionError(t *testing.T) { - for _, tt := range scanConversionErrorTests { - values := []interface{}{tt.src} - dest := reflect.New(reflect.TypeOf(tt.dest)) - values, err := redis.Scan(values, dest.Interface()) - if err == nil { - t.Errorf("Scan(%v) did not return error", tt) - } - } -} - -func ExampleScan() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Send("HMSET", "album:1", "title", "Red", "rating", 5) - c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1) - c.Send("HMSET", "album:3", "title", "Beat") - c.Send("LPUSH", "albums", "1") - c.Send("LPUSH", "albums", "2") - c.Send("LPUSH", "albums", "3") - values, err := redis.Values(c.Do("SORT", "albums", - "BY", "album:*->rating", - "GET", "album:*->title", - "GET", "album:*->rating")) - if err != nil { - panic(err) - } - - for len(values) > 0 { - var title string - rating := -1 // initialize to illegal value to detect nil. - values, err = redis.Scan(values, &title, &rating) - if err != nil { - panic(err) - } - if rating == -1 { - fmt.Println(title, "not-rated") - } else { - fmt.Println(title, rating) - } - } - // Output: - // Beat not-rated - // Earthbound 1 - // Red 5 -} - -type s0 struct { - X int - Y int `redis:"y"` - Bt bool -} - -type s1 struct { - X int `redis:"-"` - I int `redis:"i"` - U uint `redis:"u"` - S string `redis:"s"` - P []byte `redis:"p"` - B bool `redis:"b"` - Bt bool - Bf bool - s0 -} - -var scanStructTests = []struct { - title string - reply []string - value interface{} -}{ - {"basic", - []string{"i", "-1234", "u", "5678", "s", "hello", "p", "world", "b", "t", "Bt", "1", "Bf", "0", "X", "123", "y", "456"}, - &s1{I: -1234, U: 5678, S: "hello", P: []byte("world"), B: true, Bt: true, Bf: false, s0: s0{X: 123, Y: 456}}, - }, -} - -func TestScanStruct(t *testing.T) { - for _, tt := range scanStructTests { - - var reply []interface{} - for _, v := range tt.reply { - reply = append(reply, []byte(v)) - } - - value := reflect.New(reflect.ValueOf(tt.value).Type().Elem()) - - if err := redis.ScanStruct(reply, value.Interface()); err != nil { - t.Fatalf("ScanStruct(%s) returned error %v", tt.title, err) - } - - if !reflect.DeepEqual(value.Interface(), tt.value) { - t.Fatalf("ScanStruct(%s) returned %v, want %v", tt.title, value.Interface(), tt.value) - } - } -} - -func TestBadScanStructArgs(t *testing.T) { - x := []interface{}{"A", "b"} - test := func(v interface{}) { - if err := redis.ScanStruct(x, v); err == nil { - t.Errorf("Expect error for ScanStruct(%T, %T)", x, v) - } - } - - test(nil) - - var v0 *struct{} - test(v0) - - var v1 int - test(&v1) - - x = x[:1] - v2 := struct{ A string }{} - test(&v2) -} - -var scanSliceTests = []struct { - src []interface{} - fieldNames []string - ok bool - dest interface{} -}{ - { - []interface{}{[]byte("1"), nil, []byte("-1")}, - nil, - true, - []int{1, 0, -1}, - }, - { - []interface{}{[]byte("1"), nil, []byte("2")}, - nil, - true, - []uint{1, 0, 2}, - }, - { - []interface{}{[]byte("-1")}, - nil, - false, - []uint{1}, - }, - { - []interface{}{[]byte("hello"), nil, []byte("world")}, - nil, - true, - [][]byte{[]byte("hello"), nil, []byte("world")}, - }, - { - []interface{}{[]byte("hello"), nil, []byte("world")}, - nil, - true, - []string{"hello", "", "world"}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - true, - []struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1")}, - nil, - false, - []struct{ A, B, C string }{{"a1", "b1", ""}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - true, - []*struct{ A, B string }{{"a1", "b1"}, {"a2", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - []string{"A", "B"}, - true, - []struct{ A, C, B string }{{"a1", "", "b1"}, {"a2", "", "b2"}}, - }, - { - []interface{}{[]byte("a1"), []byte("b1"), []byte("a2"), []byte("b2")}, - nil, - false, - []struct{}{}, - }, -} - -func TestScanSlice(t *testing.T) { - for _, tt := range scanSliceTests { - - typ := reflect.ValueOf(tt.dest).Type() - dest := reflect.New(typ) - - err := redis.ScanSlice(tt.src, dest.Interface(), tt.fieldNames...) - if tt.ok != (err == nil) { - t.Errorf("ScanSlice(%v, []%s, %v) returned error %v", tt.src, typ, tt.fieldNames, err) - continue - } - if tt.ok && !reflect.DeepEqual(dest.Elem().Interface(), tt.dest) { - t.Errorf("ScanSlice(src, []%s) returned %#v, want %#v", typ, dest.Elem().Interface(), tt.dest) - } - } -} - -func ExampleScanSlice() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - c.Send("HMSET", "album:1", "title", "Red", "rating", 5) - c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1) - c.Send("HMSET", "album:3", "title", "Beat", "rating", 4) - c.Send("LPUSH", "albums", "1") - c.Send("LPUSH", "albums", "2") - c.Send("LPUSH", "albums", "3") - values, err := redis.Values(c.Do("SORT", "albums", - "BY", "album:*->rating", - "GET", "album:*->title", - "GET", "album:*->rating")) - if err != nil { - panic(err) - } - - var albums []struct { - Title string - Rating int - } - if err := redis.ScanSlice(values, &albums); err != nil { - panic(err) - } - fmt.Printf("%v\n", albums) - // Output: - // [{Earthbound 1} {Beat 4} {Red 5}] -} - -var argsTests = []struct { - title string - actual redis.Args - expected redis.Args -}{ - {"struct ptr", - redis.Args{}.AddFlat(&struct { - I int `redis:"i"` - U uint `redis:"u"` - S string `redis:"s"` - P []byte `redis:"p"` - Bt bool - Bf bool - }{ - -1234, 5678, "hello", []byte("world"), true, false, - }), - redis.Args{"i", int(-1234), "u", uint(5678), "s", "hello", "p", []byte("world"), "Bt", true, "Bf", false}, - }, - {"struct", - redis.Args{}.AddFlat(struct{ I int }{123}), - redis.Args{"I", 123}, - }, - {"slice", - redis.Args{}.Add(1).AddFlat([]string{"a", "b", "c"}).Add(2), - redis.Args{1, "a", "b", "c", 2}, - }, -} - -func TestArgs(t *testing.T) { - for _, tt := range argsTests { - if !reflect.DeepEqual(tt.actual, tt.expected) { - t.Fatalf("%s is %v, want %v", tt.title, tt.actual, tt.expected) - } - } -} - -func ExampleArgs() { - c, err := dial() - if err != nil { - panic(err) - } - defer c.Close() - - var p1, p2 struct { - Title string `redis:"title"` - Author string `redis:"author"` - Body string `redis:"body"` - } - - p1.Title = "Example" - p1.Author = "Gary" - p1.Body = "Hello" - - if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil { - panic(err) - } - - m := map[string]string{ - "title": "Example2", - "author": "Steve", - "body": "Map", - } - - if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil { - panic(err) - } - - for _, id := range []string{"id1", "id2"} { - - v, err := redis.Values(c.Do("HGETALL", id)) - if err != nil { - panic(err) - } - - if err := redis.ScanStruct(v, &p2); err != nil { - panic(err) - } - - fmt.Printf("%+v\n", p2) - } - - // Output: - // {Title:Example Author:Gary Body:Hello} - // {Title:Example2 Author:Steve Body:Map} -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go deleted file mode 100644 index c9635bf08e3..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/script_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis_test - -import ( - "fmt" - "reflect" - "testing" - "time" - - "github.com/garyburd/redigo/internal/redistest" - "github.com/garyburd/redigo/redis" -) - -func ExampleScript(c redis.Conn, reply interface{}, err error) { - // Initialize a package-level variable with a script. - var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`) - - // In a function, use the script Do method to evaluate the script. The Do - // method optimistically uses the EVALSHA command. If the script is not - // loaded, then the Do method falls back to the EVAL command. - reply, err = getScript.Do(c, "foo") -} - -func TestScript(t *testing.T) { - c, err := redistest.Dial() - if err != nil { - t.Fatalf("error connection to database, %v", err) - } - defer c.Close() - - // To test fall back in Do, we make script unique by adding comment with current time. - script := fmt.Sprintf("--%d\nreturn {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", time.Now().UnixNano()) - s := redis.NewScript(2, script) - reply := []interface{}{[]byte("key1"), []byte("key2"), []byte("arg1"), []byte("arg2")} - - v, err := s.Do(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.Do(c, ...) returned %v", err) - } - - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.Do(c, ..); = %v, want %v", v, reply) - } - - err = s.Load(c) - if err != nil { - t.Errorf("s.Load(c) returned %v", err) - } - - err = s.SendHash(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.SendHash(c, ...) returned %v", err) - } - - err = c.Flush() - if err != nil { - t.Errorf("c.Flush() returned %v", err) - } - - v, err = c.Receive() - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.SendHash(c, ..); c.Receive() = %v, want %v", v, reply) - } - - err = s.Send(c, "key1", "key2", "arg1", "arg2") - if err != nil { - t.Errorf("s.Send(c, ...) returned %v", err) - } - - err = c.Flush() - if err != nil { - t.Errorf("c.Flush() returned %v", err) - } - - v, err = c.Receive() - if !reflect.DeepEqual(v, reply) { - t.Errorf("s.Send(c, ..); c.Receive() = %v, want %v", v, reply) - } - -} diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go deleted file mode 100644 index b959a11f4f7..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/test_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2012 Gary Burd -// -// 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 redis - -import ( - "bufio" - "net" - "time" -) - -func SetNowFunc(f func() time.Time) { - nowFunc = f -} - -type nopCloser struct{ net.Conn } - -func (nopCloser) Close() error { return nil } - -// NewConnBufio is a hook for tests. -func NewConnBufio(rw bufio.ReadWriter) Conn { - return &conn{br: rw.Reader, bw: rw.Writer, conn: nopCloser{}} -} - -var ( - ErrNegativeInt = errNegativeInt -) diff --git a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go b/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go deleted file mode 100644 index 1d86ee6ce8c..00000000000 --- a/Godeps/_workspace/src/github.com/garyburd/redigo/redis/zpop_example_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2013 Gary Burd -// -// 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 redis_test - -import ( - "fmt" - "github.com/garyburd/redigo/redis" -) - -// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands. -func zpop(c redis.Conn, key string) (result string, err error) { - - defer func() { - // Return connection to normal state on error. - if err != nil { - c.Do("DISCARD") - } - }() - - // Loop until transaction is successful. - for { - if _, err := c.Do("WATCH", key); err != nil { - return "", err - } - - members, err := redis.Strings(c.Do("ZRANGE", key, 0, 0)) - if err != nil { - return "", err - } - if len(members) != 1 { - return "", redis.ErrNil - } - - c.Send("MULTI") - c.Send("ZREM", key, members[0]) - queued, err := c.Do("EXEC") - if err != nil { - return "", err - } - - if queued != nil { - result = members[0] - break - } - } - - return result, nil -} - -// zpopScript pops a value from a ZSET. -var zpopScript = redis.NewScript(1, ` - local r = redis.call('ZRANGE', KEYS[1], 0, 0) - if r ~= nil then - r = r[1] - redis.call('ZREM', KEYS[1], r) - end - return r -`) - -// This example implements ZPOP as described at -// http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting. -func Example_zpop() { - c, err := dial() - if err != nil { - fmt.Println(err) - return - } - defer c.Close() - - // Add test data using a pipeline. - - for i, member := range []string{"red", "blue", "green"} { - c.Send("ZADD", "zset", i, member) - } - if _, err := c.Do(""); err != nil { - fmt.Println(err) - return - } - - // Pop using WATCH/MULTI/EXEC - - v, err := zpop(c, "zset") - if err != nil { - fmt.Println(err) - return - } - fmt.Println(v) - - // Pop using a script. - - v, err = redis.String(zpopScript.Do(c, "zset")) - if err != nil { - fmt.Println(err) - return - } - fmt.Println(v) - - // Output: - // red - // blue -} diff --git a/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go b/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go deleted file mode 100644 index 0ae0954e901..00000000000 --- a/Godeps/_workspace/src/github.com/ghodss/yaml/yaml_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package yaml - -import ( - "fmt" - "math" - "reflect" - "strconv" - "testing" -) - -type MarshalTest struct { - A string - B int64 - // Would like to test float64, but it's not supported in go-yaml. - // (See https://github.com/go-yaml/yaml/issues/83.) - C float32 -} - -func TestMarshal(t *testing.T) { - f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) - s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) - - y, err := Marshal(s) - if err != nil { - t.Errorf("error marshaling YAML: %v", err) - } - - if !reflect.DeepEqual(y, e) { - t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", - string(e), string(y)) - } -} - -type UnmarshalString struct { - A string - True string -} - -type UnmarshalStringMap struct { - A map[string]string -} - -type UnmarshalNestedString struct { - A NestedString -} - -type NestedString struct { - A string -} - -type UnmarshalSlice struct { - A []NestedSlice -} - -type NestedSlice struct { - B string - C *string -} - -func TestUnmarshal(t *testing.T) { - y := []byte("a: 1") - s1 := UnmarshalString{} - e1 := UnmarshalString{A: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a: true") - s1 = UnmarshalString{} - e1 = UnmarshalString{A: "true"} - unmarshal(t, y, &s1, &e1) - - y = []byte("true: 1") - s1 = UnmarshalString{} - e1 = UnmarshalString{True: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a:\n a: 1") - s2 := UnmarshalNestedString{} - e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshal(t, y, &s2, &e2) - - y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") - s3 := UnmarshalSlice{} - e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshal(t, y, &s3, &e3) - - y = []byte("a:\n b: 1") - s4 := UnmarshalStringMap{} - e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshal(t, y, &s4, &e4) -} - -func unmarshal(t *testing.T, y []byte, s, e interface{}) { - err := Unmarshal(y, s) - if err != nil { - t.Errorf("error unmarshaling YAML: %v", err) - } - - if !reflect.DeepEqual(s, e) { - t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", - e, s) - } -} - -type Case struct { - input string - output string - // By default we test that reversing the output == input. But if there is a - // difference in the reversed output, you can optionally specify it here. - reverse *string -} - -type RunType int - -const ( - RunTypeJSONToYAML RunType = iota - RunTypeYAMLToJSON -) - -func TestJSONToYAML(t *testing.T) { - cases := []Case{ - { - `{"t":"a"}`, - "t: a\n", - nil, - }, { - `{"t":null}`, - "t: null\n", - nil, - }, - } - - runCases(t, RunTypeJSONToYAML, cases) -} - -func TestYAMLToJSON(t *testing.T) { - cases := []Case{ - { - "t: a\n", - `{"t":"a"}`, - nil, - }, { - "t: \n", - `{"t":null}`, - strPtr("t: null\n"), - }, { - "t: null\n", - `{"t":null}`, - nil, - }, { - "1: a\n", - `{"1":"a"}`, - strPtr("\"1\": a\n"), - }, { - "1000000000000000000000000000000000000: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "1e+36: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "\"1e+36\": a\n", - `{"1e+36":"a"}`, - nil, - }, { - "\"1.2\": a\n", - `{"1.2":"a"}`, - nil, - }, { - "- t: a\n", - `[{"t":"a"}]`, - nil, - }, { - "- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n", - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - nil, - }, { - `[{t: a}, {t: {b: 1, c: 2}}]`, - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - strPtr("- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n"), - }, { - "- t: \n", - `[{"t":null}]`, - strPtr("- t: null\n"), - }, { - "- t: null\n", - `[{"t":null}]`, - nil, - }, - } - - // Cases that should produce errors. - _ = []Case{ - { - "~: a", - `{"null":"a"}`, - nil, - }, { - "a: !!binary gIGC\n", - "{\"a\":\"\x80\x81\x82\"}", - nil, - }, - } - - runCases(t, RunTypeYAMLToJSON, cases) -} - -func runCases(t *testing.T, runType RunType, cases []Case) { - var f func([]byte) ([]byte, error) - var invF func([]byte) ([]byte, error) - var msg string - var invMsg string - if runType == RunTypeJSONToYAML { - f = JSONToYAML - invF = YAMLToJSON - msg = "JSON to YAML" - invMsg = "YAML back to JSON" - } else { - f = YAMLToJSON - invF = JSONToYAML - msg = "YAML to JSON" - invMsg = "JSON back to YAML" - } - - for _, c := range cases { - // Convert the string. - t.Logf("converting %s\n", c.input) - output, err := f([]byte(c.input)) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) - } - - // Check it against the expected output. - if string(output) != c.output { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - msg, c.input, c.output, string(output)) - } - - // Set the string that we will compare the reversed output to. - reverse := c.input - // If a special reverse string was specified, use that instead. - if c.reverse != nil { - reverse = *c.reverse - } - - // Reverse the output. - input, err := invF(output) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) - } - - // Check the reverse is equal to the input (or to *c.reverse). - if string(input) != reverse { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - invMsg, string(output), reverse, string(input)) - } - } - -} - -// To be able to easily fill in the *Case.reverse string above. -func strPtr(s string) *string { - return &s -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/conn_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/conn_test.go deleted file mode 100644 index a2b14e8cc46..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/conn_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package dbus - -import "testing" - -func TestSessionBus(t *testing.T) { - _, err := SessionBus() - if err != nil { - t.Error(err) - } -} - -func TestSystemBus(t *testing.T) { - _, err := SystemBus() - if err != nil { - t.Error(err) - } -} - -func TestSend(t *testing.T) { - bus, err := SessionBus() - if err != nil { - t.Error(err) - } - ch := make(chan *Call, 1) - msg := &Message{ - Type: TypeMethodCall, - Flags: 0, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant(bus.Names()[0]), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/DBus")), - FieldInterface: MakeVariant("org.freedesktop.DBus.Peer"), - FieldMember: MakeVariant("Ping"), - }, - } - call := bus.Send(msg, ch) - <-ch - if call.Err != nil { - t.Error(call.Err) - } -} - -type server struct{} - -func (server) Double(i int64) (int64, *Error) { - return 2 * i, nil -} - -func BenchmarkCall(b *testing.B) { - b.StopTimer() - var s string - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - name := bus.Names()[0] - obj := bus.BusObject() - b.StartTimer() - for i := 0; i < b.N; i++ { - err := obj.Call("org.freedesktop.DBus.GetNameOwner", 0, name).Store(&s) - if err != nil { - b.Fatal(err) - } - if s != name { - b.Errorf("got %s, wanted %s", s, name) - } - } -} - -func BenchmarkCallAsync(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - name := bus.Names()[0] - obj := bus.BusObject() - c := make(chan *Call, 50) - done := make(chan struct{}) - go func() { - for i := 0; i < b.N; i++ { - v := <-c - if v.Err != nil { - b.Error(v.Err) - } - s := v.Body[0].(string) - if s != name { - b.Errorf("got %s, wanted %s", s, name) - } - } - close(done) - }() - b.StartTimer() - for i := 0; i < b.N; i++ { - obj.Go("org.freedesktop.DBus.GetNameOwner", 0, c, name) - } - <-done -} - -func BenchmarkServe(b *testing.B) { - b.StopTimer() - srv, err := SessionBus() - if err != nil { - b.Fatal(err) - } - cli, err := SessionBusPrivate() - if err != nil { - b.Fatal(err) - } - if err = cli.Auth(nil); err != nil { - b.Fatal(err) - } - if err = cli.Hello(); err != nil { - b.Fatal(err) - } - benchmarkServe(b, srv, cli) -} - -func BenchmarkServeAsync(b *testing.B) { - b.StopTimer() - srv, err := SessionBus() - if err != nil { - b.Fatal(err) - } - cli, err := SessionBusPrivate() - if err != nil { - b.Fatal(err) - } - if err = cli.Auth(nil); err != nil { - b.Fatal(err) - } - if err = cli.Hello(); err != nil { - b.Fatal(err) - } - benchmarkServeAsync(b, srv, cli) -} - -func BenchmarkServeSameConn(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - - benchmarkServe(b, bus, bus) -} - -func BenchmarkServeSameConnAsync(b *testing.B) { - b.StopTimer() - bus, err := SessionBus() - if err != nil { - b.Fatal(err) - } - - benchmarkServeAsync(b, bus, bus) -} - -func benchmarkServe(b *testing.B, srv, cli *Conn) { - var r int64 - var err error - dest := srv.Names()[0] - srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") - obj := cli.Object(dest, "/org/guelfey/DBus/Test") - b.StartTimer() - for i := 0; i < b.N; i++ { - err = obj.Call("org.guelfey.DBus.Test.Double", 0, int64(i)).Store(&r) - if err != nil { - b.Fatal(err) - } - if r != 2*int64(i) { - b.Errorf("got %d, wanted %d", r, 2*int64(i)) - } - } -} - -func benchmarkServeAsync(b *testing.B, srv, cli *Conn) { - dest := srv.Names()[0] - srv.Export(server{}, "/org/guelfey/DBus/Test", "org.guelfey.DBus.Test") - obj := cli.Object(dest, "/org/guelfey/DBus/Test") - c := make(chan *Call, 50) - done := make(chan struct{}) - go func() { - for i := 0; i < b.N; i++ { - v := <-c - if v.Err != nil { - b.Fatal(v.Err) - } - i, r := v.Args[0].(int64), v.Body[0].(int64) - if 2*i != r { - b.Errorf("got %d, wanted %d", r, 2*i) - } - } - close(done) - }() - b.StartTimer() - for i := 0; i < b.N; i++ { - obj.Go("org.guelfey.DBus.Test.Double", 0, c, int64(i)) - } - <-done -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/examples_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/examples_test.go deleted file mode 100644 index 0218ac55986..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/examples_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package dbus - -import "fmt" - -func ExampleConn_Emit() { - conn, err := SessionBus() - if err != nil { - panic(err) - } - - conn.Emit("/foo/bar", "foo.bar.Baz", uint32(0xDAEDBEEF)) -} - -func ExampleObject_Call() { - var list []string - - conn, err := SessionBus() - if err != nil { - panic(err) - } - - err = conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&list) - if err != nil { - panic(err) - } - for _, v := range list { - fmt.Println(v) - } -} - -func ExampleObject_Go() { - conn, err := SessionBus() - if err != nil { - panic(err) - } - - ch := make(chan *Call, 10) - conn.BusObject().Go("org.freedesktop.DBus.ListActivatableNames", 0, ch) - select { - case call := <-ch: - if call.Err != nil { - panic(err) - } - list := call.Body[0].([]string) - for _, v := range list { - fmt.Println(v) - } - // put some other cases here - } -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/proto_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/proto_test.go deleted file mode 100644 index 608a770d41f..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/proto_test.go +++ /dev/null @@ -1,369 +0,0 @@ -package dbus - -import ( - "bytes" - "encoding/binary" - "io/ioutil" - "math" - "reflect" - "testing" -) - -var protoTests = []struct { - vs []interface{} - bigEndian []byte - littleEndian []byte -}{ - { - []interface{}{int32(0)}, - []byte{0, 0, 0, 0}, - []byte{0, 0, 0, 0}, - }, - { - []interface{}{true, false}, - []byte{0, 0, 0, 1, 0, 0, 0, 0}, - []byte{1, 0, 0, 0, 0, 0, 0, 0}, - }, - { - []interface{}{byte(0), uint16(12), int16(32), uint32(43)}, - []byte{0, 0, 0, 12, 0, 32, 0, 0, 0, 0, 0, 43}, - []byte{0, 0, 12, 0, 32, 0, 0, 0, 43, 0, 0, 0}, - }, - { - []interface{}{int64(-1), uint64(1<<64 - 1)}, - bytes.Repeat([]byte{255}, 16), - bytes.Repeat([]byte{255}, 16), - }, - { - []interface{}{math.Inf(+1)}, - []byte{0x7f, 0xf0, 0, 0, 0, 0, 0, 0}, - []byte{0, 0, 0, 0, 0, 0, 0xf0, 0x7f}, - }, - { - []interface{}{"foo"}, - []byte{0, 0, 0, 3, 'f', 'o', 'o', 0}, - []byte{3, 0, 0, 0, 'f', 'o', 'o', 0}, - }, - { - []interface{}{Signature{"ai"}}, - []byte{2, 'a', 'i', 0}, - []byte{2, 'a', 'i', 0}, - }, - { - []interface{}{[]int16{42, 256}}, - []byte{0, 0, 0, 4, 0, 42, 1, 0}, - []byte{4, 0, 0, 0, 42, 0, 0, 1}, - }, - { - []interface{}{MakeVariant("foo")}, - []byte{1, 's', 0, 0, 0, 0, 0, 3, 'f', 'o', 'o', 0}, - []byte{1, 's', 0, 0, 3, 0, 0, 0, 'f', 'o', 'o', 0}, - }, - { - []interface{}{MakeVariant(MakeVariant(Signature{"v"}))}, - []byte{1, 'v', 0, 1, 'g', 0, 1, 'v', 0}, - []byte{1, 'v', 0, 1, 'g', 0, 1, 'v', 0}, - }, - { - []interface{}{map[int32]bool{42: true}}, - []byte{0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 1}, - []byte{8, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 1, 0, 0, 0}, - }, - { - []interface{}{map[string]Variant{}, byte(42)}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - }, - { - []interface{}{[]uint64{}, byte(42)}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - []byte{0, 0, 0, 0, 0, 0, 0, 0, 42}, - }, -} - -func TestProto(t *testing.T) { - for i, v := range protoTests { - buf := new(bytes.Buffer) - bigEnc := newEncoder(buf, binary.BigEndian) - bigEnc.Encode(v.vs...) - marshalled := buf.Bytes() - if bytes.Compare(marshalled, v.bigEndian) != 0 { - t.Errorf("test %d (marshal be): got '%v', but expected '%v'\n", i+1, marshalled, - v.bigEndian) - } - buf.Reset() - litEnc := newEncoder(buf, binary.LittleEndian) - litEnc.Encode(v.vs...) - marshalled = buf.Bytes() - if bytes.Compare(marshalled, v.littleEndian) != 0 { - t.Errorf("test %d (marshal le): got '%v', but expected '%v'\n", i+1, marshalled, - v.littleEndian) - } - unmarshalled := reflect.MakeSlice(reflect.TypeOf(v.vs), - 0, 0) - for i := range v.vs { - unmarshalled = reflect.Append(unmarshalled, - reflect.New(reflect.TypeOf(v.vs[i]))) - } - bigDec := newDecoder(bytes.NewReader(v.bigEndian), binary.BigEndian) - vs, err := bigDec.Decode(SignatureOf(v.vs...)) - if err != nil { - t.Errorf("test %d (unmarshal be): %s\n", i+1, err) - continue - } - if !reflect.DeepEqual(vs, v.vs) { - t.Errorf("test %d (unmarshal be): got %#v, but expected %#v\n", i+1, vs, v.vs) - } - litDec := newDecoder(bytes.NewReader(v.littleEndian), binary.LittleEndian) - vs, err = litDec.Decode(SignatureOf(v.vs...)) - if err != nil { - t.Errorf("test %d (unmarshal le): %s\n", i+1, err) - continue - } - if !reflect.DeepEqual(vs, v.vs) { - t.Errorf("test %d (unmarshal le): got %#v, but expected %#v\n", i+1, vs, v.vs) - } - - } -} - -func TestProtoMap(t *testing.T) { - m := map[string]uint8{ - "foo": 23, - "bar": 2, - } - var n map[string]uint8 - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(m) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"a{sy}"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &n); err != nil { - t.Fatal(err) - } - if len(n) != 2 || n["foo"] != 23 || n["bar"] != 2 { - t.Error("got", n) - } -} - -func TestProtoVariantStruct(t *testing.T) { - var variant Variant - v := MakeVariant(struct { - A int32 - B int16 - }{1, 2}) - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(v) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"v"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &variant); err != nil { - t.Fatal(err) - } - sl := variant.Value().([]interface{}) - v1, v2 := sl[0].(int32), sl[1].(int16) - if v1 != int32(1) { - t.Error("got", v1, "as first int") - } - if v2 != int16(2) { - t.Error("got", v2, "as second int") - } -} - -func TestProtoStructTag(t *testing.T) { - type Bar struct { - A int32 - B chan interface{} `dbus:"-"` - C int32 - } - var bar1, bar2 Bar - bar1.A = 234 - bar2.C = 345 - buf := new(bytes.Buffer) - enc := newEncoder(buf, binary.LittleEndian) - enc.Encode(bar1) - dec := newDecoder(buf, binary.LittleEndian) - vs, err := dec.Decode(Signature{"(ii)"}) - if err != nil { - t.Fatal(err) - } - if err = Store(vs, &bar2); err != nil { - t.Fatal(err) - } - if bar1 != bar2 { - t.Error("struct tag test: got", bar2) - } -} - -func TestProtoStoreStruct(t *testing.T) { - var foo struct { - A int32 - B string - c chan interface{} - D interface{} `dbus:"-"` - } - src := []interface{}{[]interface{}{int32(42), "foo"}} - err := Store(src, &foo) - if err != nil { - t.Fatal(err) - } -} - -func TestProtoStoreNestedStruct(t *testing.T) { - var foo struct { - A int32 - B struct { - C string - D float64 - } - } - src := []interface{}{ - []interface{}{ - int32(42), - []interface{}{ - "foo", - 3.14, - }, - }, - } - err := Store(src, &foo) - if err != nil { - t.Fatal(err) - } -} - -func TestMessage(t *testing.T) { - buf := new(bytes.Buffer) - message := new(Message) - message.Type = TypeMethodCall - message.serial = 32 - message.Headers = map[HeaderField]Variant{ - FieldPath: MakeVariant(ObjectPath("/org/foo/bar")), - FieldMember: MakeVariant("baz"), - } - message.Body = make([]interface{}, 0) - err := message.EncodeTo(buf, binary.LittleEndian) - if err != nil { - t.Error(err) - } - _, err = DecodeMessage(buf) - if err != nil { - t.Error(err) - } -} - -func TestProtoStructInterfaces(t *testing.T) { - b := []byte{42} - vs, err := newDecoder(bytes.NewReader(b), binary.LittleEndian).Decode(Signature{"(y)"}) - if err != nil { - t.Fatal(err) - } - if vs[0].([]interface{})[0].(byte) != 42 { - t.Errorf("wrongs results (got %v)", vs) - } -} - -// ordinary org.freedesktop.DBus.Hello call -var smallMessage = &Message{ - Type: TypeMethodCall, - serial: 1, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant("org.freedesktop.DBus"), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/DBus")), - FieldInterface: MakeVariant("org.freedesktop.DBus"), - FieldMember: MakeVariant("Hello"), - }, -} - -// org.freedesktop.Notifications.Notify -var bigMessage = &Message{ - Type: TypeMethodCall, - serial: 2, - Headers: map[HeaderField]Variant{ - FieldDestination: MakeVariant("org.freedesktop.Notifications"), - FieldPath: MakeVariant(ObjectPath("/org/freedesktop/Notifications")), - FieldInterface: MakeVariant("org.freedesktop.Notifications"), - FieldMember: MakeVariant("Notify"), - FieldSignature: MakeVariant(Signature{"susssasa{sv}i"}), - }, - Body: []interface{}{ - "app_name", - uint32(0), - "dialog-information", - "Notification", - "This is the body of a notification", - []string{"ok", "Ok"}, - map[string]Variant{ - "sound-name": MakeVariant("dialog-information"), - }, - int32(-1), - }, -} - -func BenchmarkDecodeMessageSmall(b *testing.B) { - var err error - var rd *bytes.Reader - - b.StopTimer() - buf := new(bytes.Buffer) - err = smallMessage.EncodeTo(buf, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - decoded := buf.Bytes() - b.StartTimer() - for i := 0; i < b.N; i++ { - rd = bytes.NewReader(decoded) - _, err = DecodeMessage(rd) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkDecodeMessageBig(b *testing.B) { - var err error - var rd *bytes.Reader - - b.StopTimer() - buf := new(bytes.Buffer) - err = bigMessage.EncodeTo(buf, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - decoded := buf.Bytes() - b.StartTimer() - for i := 0; i < b.N; i++ { - rd = bytes.NewReader(decoded) - _, err = DecodeMessage(rd) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkEncodeMessageSmall(b *testing.B) { - var err error - for i := 0; i < b.N; i++ { - err = smallMessage.EncodeTo(ioutil.Discard, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkEncodeMessageBig(b *testing.B) { - var err error - for i := 0; i < b.N; i++ { - err = bigMessage.EncodeTo(ioutil.Discard, binary.LittleEndian) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/sig_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/sig_test.go deleted file mode 100644 index da37bc968e7..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/sig_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package dbus - -import ( - "testing" -) - -var sigTests = []struct { - vs []interface{} - sig Signature -}{ - { - []interface{}{new(int32)}, - Signature{"i"}, - }, - { - []interface{}{new(string)}, - Signature{"s"}, - }, - { - []interface{}{new(Signature)}, - Signature{"g"}, - }, - { - []interface{}{new([]int16)}, - Signature{"an"}, - }, - { - []interface{}{new(int16), new(uint32)}, - Signature{"nu"}, - }, - { - []interface{}{new(map[byte]Variant)}, - Signature{"a{yv}"}, - }, - { - []interface{}{new(Variant), new([]map[int32]string)}, - Signature{"vaa{is}"}, - }, -} - -func TestSig(t *testing.T) { - for i, v := range sigTests { - sig := SignatureOf(v.vs...) - if sig != v.sig { - t.Errorf("test %d: got %q, expected %q", i+1, sig.str, v.sig.str) - } - } -} - -var getSigTest = []interface{}{ - []struct { - b byte - i int32 - t uint64 - s string - }{}, - map[string]Variant{}, -} - -func BenchmarkGetSignatureSimple(b *testing.B) { - for i := 0; i < b.N; i++ { - SignatureOf("", int32(0)) - } -} - -func BenchmarkGetSignatureLong(b *testing.B) { - for i := 0; i < b.N; i++ { - SignatureOf(getSigTest...) - } -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/transport_unix_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/transport_unix_test.go deleted file mode 100644 index 302233fc65e..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/transport_unix_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package dbus - -import ( - "os" - "testing" -) - -const testString = `This is a test! -This text should be read from the file that is created by this test.` - -type unixFDTest struct{} - -func (t unixFDTest) Test(fd UnixFD) (string, *Error) { - var b [4096]byte - file := os.NewFile(uintptr(fd), "testfile") - defer file.Close() - n, err := file.Read(b[:]) - if err != nil { - return "", &Error{"com.github.guelfey.test.Error", nil} - } - return string(b[:n]), nil -} - -func TestUnixFDs(t *testing.T) { - conn, err := SessionBus() - if err != nil { - t.Fatal(err) - } - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - defer w.Close() - if _, err := w.Write([]byte(testString)); err != nil { - t.Fatal(err) - } - name := conn.Names()[0] - test := unixFDTest{} - conn.Export(test, "/com/github/guelfey/test", "com.github.guelfey.test") - var s string - obj := conn.Object(name, "/com/github/guelfey/test") - err = obj.Call("com.github.guelfey.test.Test", 0, UnixFD(r.Fd())).Store(&s) - if err != nil { - t.Fatal(err) - } - if s != testString { - t.Fatal("got", s, "wanted", testString) - } -} diff --git a/Godeps/_workspace/src/github.com/godbus/dbus/variant_test.go b/Godeps/_workspace/src/github.com/godbus/dbus/variant_test.go deleted file mode 100644 index da917c8e290..00000000000 --- a/Godeps/_workspace/src/github.com/godbus/dbus/variant_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package dbus - -import "reflect" -import "testing" - -var variantFormatTests = []struct { - v interface{} - s string -}{ - {int32(1), `1`}, - {"foo", `"foo"`}, - {ObjectPath("/org/foo"), `@o "/org/foo"`}, - {Signature{"i"}, `@g "i"`}, - {[]byte{}, `@ay []`}, - {[]int32{1, 2}, `[1, 2]`}, - {[]int64{1, 2}, `@ax [1, 2]`}, - {[][]int32{{3, 4}, {5, 6}}, `[[3, 4], [5, 6]]`}, - {[]Variant{MakeVariant(int32(1)), MakeVariant(1.0)}, `[<1>, <@d 1>]`}, - {map[string]int32{"one": 1, "two": 2}, `{"one": 1, "two": 2}`}, - {map[int32]ObjectPath{1: "/org/foo"}, `@a{io} {1: "/org/foo"}`}, - {map[string]Variant{}, `@a{sv} {}`}, -} - -func TestFormatVariant(t *testing.T) { - for i, v := range variantFormatTests { - if s := MakeVariant(v.v).String(); s != v.s { - t.Errorf("test %d: got %q, wanted %q", i+1, s, v.s) - } - } -} - -var variantParseTests = []struct { - s string - v interface{} -}{ - {"1", int32(1)}, - {"true", true}, - {"false", false}, - {"1.0", float64(1.0)}, - {"0x10", int32(16)}, - {"1e1", float64(10)}, - {`"foo"`, "foo"}, - {`"\a\b\f\n\r\t"`, "\x07\x08\x0c\n\r\t"}, - {`"\u00e4\U0001f603"`, "\u00e4\U0001f603"}, - {"[1]", []int32{1}}, - {"[1, 2, 3]", []int32{1, 2, 3}}, - {"@ai []", []int32{}}, - {"[1, 5.0]", []float64{1, 5.0}}, - {"[[1, 2], [3, 4.0]]", [][]float64{{1, 2}, {3, 4}}}, - {`[@o "/org/foo", "/org/bar"]`, []ObjectPath{"/org/foo", "/org/bar"}}, - {"<1>", MakeVariant(int32(1))}, - {"[<1>, <2.0>]", []Variant{MakeVariant(int32(1)), MakeVariant(2.0)}}, - {`[[], [""]]`, [][]string{{}, {""}}}, - {`@a{ss} {}`, map[string]string{}}, - {`{"foo": 1}`, map[string]int32{"foo": 1}}, - {`[{}, {"foo": "bar"}]`, []map[string]string{{}, {"foo": "bar"}}}, - {`{"a": <1>, "b": <"foo">}`, - map[string]Variant{"a": MakeVariant(int32(1)), "b": MakeVariant("foo")}}, - {`b''`, []byte{0}}, - {`b"abc"`, []byte{'a', 'b', 'c', 0}}, - {`b"\x01\0002\a\b\f\n\r\t"`, []byte{1, 2, 0x7, 0x8, 0xc, '\n', '\r', '\t', 0}}, - {`[[0], b""]`, [][]byte{{0}, {0}}}, - {"int16 0", int16(0)}, - {"byte 0", byte(0)}, -} - -func TestParseVariant(t *testing.T) { - for i, v := range variantParseTests { - nv, err := ParseVariant(v.s, Signature{}) - if err != nil { - t.Errorf("test %d: parsing failed: %s", i+1, err) - continue - } - if !reflect.DeepEqual(nv.value, v.v) { - t.Errorf("test %d: got %q, wanted %q", i+1, nv, v.v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/all_test.go deleted file mode 100644 index 5f27645ec07..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/all_test.go +++ /dev/null @@ -1,2156 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/gogo/protobuf/proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - wantErr error - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since there's an error, nothing should be written to buffer. - want: nil, - wantErr: errors.New("some marshal err"), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - wantErr: &RequiredNotSetError{}, - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - wantErr: nil, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if _, ok := err.(*RequiredNotSetError); ok { - // We're not in package proto, so we can only assert the type in this case. - err = &RequiredNotSetError{} - } - if !reflect.DeepEqual(test.wantErr, err) { - t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if strings.Index(err.Error(), "Label") < 0 { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if strings.Index(err.Error(), "{Unknown}") < 0 { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - _, err := Marshal((*GoEnum)(nil)) - if err != ErrNil { - t.Errorf("Marshal: got err %v, want ErrNil", err) - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m) - if err == nil { - t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/clone_test.go deleted file mode 100644 index f065210b894..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/clone_test.go +++ /dev/null @@ -1,267 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/equal_test.go deleted file mode 100644 index 7cb36d3785d..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/equal_test.go +++ /dev/null @@ -1,209 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - . "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -// Four identical base messages. -// The init function adds extensions to some of them. -var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} - -// Two messages with non-message extensions. -var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} -var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} - -func init() { - ext1 := &pb.Ext{Data: String("Kirk")} - ext2 := &pb.Ext{Data: String("Picard")} - - // messageWithExtension1a has ext1, but never marshals it. - if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1a failed: " + err.Error()) - } - - // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. - if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1b failed: " + err.Error()) - } - buf, err := Marshal(messageWithExtension1b) - if err != nil { - panic("Marshal of 1b failed: " + err.Error()) - } - messageWithExtension1b.Reset() - if err := Unmarshal(buf, messageWithExtension1b); err != nil { - panic("Unmarshal of 1b failed: " + err.Error()) - } - - // messageWithExtension2 has ext2. - if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { - panic("SetExtension on 2 failed: " + err.Error()) - } - - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { - panic("SetExtension on Int32-1 failed: " + err.Error()) - } - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { - panic("SetExtension on Int32-2 failed: " + err.Error()) - } -} - -var EqualTests = []struct { - desc string - a, b Message - exp bool -}{ - {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, - {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, - {"nil vs nil", nil, nil, true}, - {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, - {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, - {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, - - {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, - {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, - {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, - {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, - - {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, - {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, - {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, - {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, - {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, - {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, - {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, - - { - "nested, different", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, - false, - }, - { - "nested, equal", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - true, - }, - - {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, - {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, - {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, - { - "repeated bytes", - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - true, - }, - - {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, - {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, - {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, - - {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, - {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, - - { - "message with group", - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - true, - }, - - { - "map same", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - true, - }, - { - "map different entry", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, - false, - }, - { - "map different key only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, - false, - }, - { - "map different value only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, - false, - }, - { - "oneof same", - &pb.Communique{Union: &pb.Communique_Number{Number: 41}}, - &pb.Communique{Union: &pb.Communique_Number{Number: 41}}, - true, - }, - { - "oneof one nil", - &pb.Communique{Union: &pb.Communique_Number{Number: 41}}, - &pb.Communique{}, - false, - }, - { - "oneof different", - &pb.Communique{Union: &pb.Communique_Number{Number: 41}}, - &pb.Communique{Union: &pb.Communique_Name{Name: "Bobby Tables"}}, - false, - }, -} - -func TestEqual(t *testing.T) { - for _, tc := range EqualTests { - if res := Equal(tc.a, tc.b); res != tc.exp { - t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/extensions_test.go deleted file mode 100644 index 86e3006d739..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/extensions_test.go +++ /dev/null @@ -1,292 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -func TestGetExtensionsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", ext1) - } - exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ - pb.E_Ext_More, - pb.E_Ext_Text, - }) - if err != nil { - t.Fatalf("GetExtensions() failed: %s", err) - } - if exts[0] != ext1 { - t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) - } - if exts[1] != nil { - t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) - } -} - -func TestGetExtensionStability(t *testing.T) { - check := func(m *pb.MyMessage) bool { - ext1, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - ext2, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - return ext1 == ext2 - } - msg := &pb.MyMessage{Count: proto.Int32(4)} - ext0 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { - t.Fatalf("Could not set ext1: %s", ext0) - } - if !check(msg) { - t.Errorf("GetExtension() not stable before marshaling") - } - bb, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Marshal() failed: %s", err) - } - msg1 := &pb.MyMessage{} - err = proto.Unmarshal(bb, msg1) - if err != nil { - t.Fatalf("Unmarshal() failed: %s", err) - } - if !check(msg1) { - t.Errorf("GetExtension() not stable after unmarshaling") - } -} - -func TestGetExtensionDefaults(t *testing.T) { - var setFloat64 float64 = 1 - var setFloat32 float32 = 2 - var setInt32 int32 = 3 - var setInt64 int64 = 4 - var setUint32 uint32 = 5 - var setUint64 uint64 = 6 - var setBool = true - var setBool2 = false - var setString = "Goodnight string" - var setBytes = []byte("Goodnight bytes") - var setEnum = pb.DefaultsMessage_TWO - - type testcase struct { - ext *proto.ExtensionDesc // Extension we are testing. - want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). - def interface{} // Expected value of extension after ClearExtension(). - } - tests := []testcase{ - {pb.E_NoDefaultDouble, setFloat64, nil}, - {pb.E_NoDefaultFloat, setFloat32, nil}, - {pb.E_NoDefaultInt32, setInt32, nil}, - {pb.E_NoDefaultInt64, setInt64, nil}, - {pb.E_NoDefaultUint32, setUint32, nil}, - {pb.E_NoDefaultUint64, setUint64, nil}, - {pb.E_NoDefaultSint32, setInt32, nil}, - {pb.E_NoDefaultSint64, setInt64, nil}, - {pb.E_NoDefaultFixed32, setUint32, nil}, - {pb.E_NoDefaultFixed64, setUint64, nil}, - {pb.E_NoDefaultSfixed32, setInt32, nil}, - {pb.E_NoDefaultSfixed64, setInt64, nil}, - {pb.E_NoDefaultBool, setBool, nil}, - {pb.E_NoDefaultBool, setBool2, nil}, - {pb.E_NoDefaultString, setString, nil}, - {pb.E_NoDefaultBytes, setBytes, nil}, - {pb.E_NoDefaultEnum, setEnum, nil}, - {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, - {pb.E_DefaultFloat, setFloat32, float32(3.14)}, - {pb.E_DefaultInt32, setInt32, int32(42)}, - {pb.E_DefaultInt64, setInt64, int64(43)}, - {pb.E_DefaultUint32, setUint32, uint32(44)}, - {pb.E_DefaultUint64, setUint64, uint64(45)}, - {pb.E_DefaultSint32, setInt32, int32(46)}, - {pb.E_DefaultSint64, setInt64, int64(47)}, - {pb.E_DefaultFixed32, setUint32, uint32(48)}, - {pb.E_DefaultFixed64, setUint64, uint64(49)}, - {pb.E_DefaultSfixed32, setInt32, int32(50)}, - {pb.E_DefaultSfixed64, setInt64, int64(51)}, - {pb.E_DefaultBool, setBool, true}, - {pb.E_DefaultBool, setBool2, true}, - {pb.E_DefaultString, setString, "Hello, string"}, - {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, - {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, - } - - checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { - val, err := proto.GetExtension(msg, test.ext) - if err != nil { - if valWant != nil { - return fmt.Errorf("GetExtension(): %s", err) - } - if want := proto.ErrMissingExtension; err != want { - return fmt.Errorf("Unexpected error: got %v, want %v", err, want) - } - return nil - } - - // All proto2 extension values are either a pointer to a value or a slice of values. - ty := reflect.TypeOf(val) - tyWant := reflect.TypeOf(test.ext.ExtensionType) - if got, want := ty, tyWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) - } - tye := ty.Elem() - tyeWant := tyWant.Elem() - if got, want := tye, tyeWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) - } - - // Check the name of the type of the value. - // If it is an enum it will be type int32 with the name of the enum. - if got, want := tye.Name(), tye.Name(); got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) - } - - // Check that value is what we expect. - // If we have a pointer in val, get the value it points to. - valExp := val - if ty.Kind() == reflect.Ptr { - valExp = reflect.ValueOf(val).Elem().Interface() - } - if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { - return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) - } - - return nil - } - - setTo := func(test testcase) interface{} { - setTo := reflect.ValueOf(test.want) - if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { - setTo = reflect.New(typ).Elem() - setTo.Set(reflect.New(setTo.Type().Elem())) - setTo.Elem().Set(reflect.ValueOf(test.want)) - } - return setTo.Interface() - } - - for _, test := range tests { - msg := &pb.DefaultsMessage{} - name := test.ext.Name - - // Check the initial value. - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - - // Set the per-type value and check value. - name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) - if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { - t.Errorf("%s: SetExtension(): %v", name, err) - continue - } - if err := checkVal(test, msg, test.want); err != nil { - t.Errorf("%s: %v", name, err) - continue - } - - // Set and check the value. - name += " (cleared)" - proto.ClearExtension(msg, test.ext) - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - } -} - -func TestExtensionsRoundTrip(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{ - Data: proto.String("hi"), - } - ext2 := &pb.Ext{ - Data: proto.String("there"), - } - exists := proto.HasExtension(msg, pb.E_Ext_More) - if exists { - t.Error("Extension More present unexpectedly") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Error(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { - t.Error(err) - } - e, err := proto.GetExtension(msg, pb.E_Ext_More) - if err != nil { - t.Error(err) - } - x, ok := e.(*pb.Ext) - if !ok { - t.Errorf("e has type %T, expected testdata.Ext", e) - } else if *x.Data != "there" { - t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) - } - proto.ClearExtension(msg, pb.E_Ext_More) - if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { - t.Errorf("got %v, expected ErrMissingExtension", e) - } - if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { - t.Error("expected bad extension error, got nil") - } - if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { - t.Error("expected extension err") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { - t.Error("expected some sort of type mismatch error, got nil") - } -} - -func TestNilExtension(t *testing.T) { - msg := &pb.MyMessage{ - Count: proto.Int32(1), - } - if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { - t.Fatal(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { - t.Error("expected SetExtension to fail due to a nil extension") - } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { - t.Errorf("expected error %v, got %v", want, err) - } - // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update - // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/message_set_test.go deleted file mode 100644 index 7c29bccf4b1..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &MessageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - m := make(map[int32]Extension) - if err := UnmarshalMessageSet(b, m); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := m[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", m) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_test.go deleted file mode 100644 index 6f9cddc3fa9..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/proto/proto3_proto" - tpb "github.com/gogo/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": {N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a1b..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size_test.go deleted file mode 100644 index f4b8b8e3a0a..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size_test.go +++ /dev/null @@ -1,147 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: {}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: {F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: {}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Communique{}}, - {"oneof zero int32", &pb.Communique{Union: &pb.Communique_Number{Number: 0}}}, - {"oneof int32", &pb.Communique{Union: &pb.Communique_Number{Number: 3}}}, - {"oneof string", &pb.Communique{Union: &pb.Communique_Name{Name: "Rhythmic Fman"}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/Makefile deleted file mode 100644 index 31d83277ccf..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -all: regenerate - -regenerate: - go install github.com/gogo/protobuf/protoc-min-version - protoc-min-version --version="3.0.0" --gogo_out=. test.proto - diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/golden_test.go deleted file mode 100644 index 8e84515377a..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/golden_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Verify that the compiler output for test.proto is unchanged. - -package testdata - -import ( - "crypto/sha1" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" -) - -// sum returns in string form (for easy comparison) the SHA-1 hash of the named file. -func sum(t *testing.T, name string) string { - data, err := ioutil.ReadFile(name) - if err != nil { - t.Fatal(err) - } - t.Logf("sum(%q): length is %d", name, len(data)) - hash := sha1.New() - _, err = hash.Write(data) - if err != nil { - t.Fatal(err) - } - return fmt.Sprintf("% x", hash.Sum(nil)) -} - -func run(t *testing.T, name string, args ...string) { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err := cmd.Run() - if err != nil { - t.Fatal(err) - } -} - -func TestGolden(t *testing.T) { - // Compute the original checksum. - goldenSum := sum(t, "test.pb.go") - // Run the proto compiler. - run(t, "protoc", "--gogo_out="+os.TempDir(), "test.proto") - newFile := filepath.Join(os.TempDir(), "test.pb.go") - defer os.Remove(newFile) - // Compute the new checksum. - newSum := sum(t, newFile) - // Verify - if newSum != goldenSum { - run(t, "diff", "-u", "test.pb.go", newFile) - t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go deleted file mode 100644 index 0c200f6a41c..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go +++ /dev/null @@ -1,2948 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: test.proto -// DO NOT EDIT! - -/* -Package testdata is a generated protocol buffer package. - -It is generated from these files: - test.proto - -It has these top-level messages: - GoEnum - GoTestField - GoTest - GoSkipTest - NonPackedTest - PackedTest - MaxTag - OldMessage - NewMessage - InnerMessage - OtherMessage - MyMessage - Ext - DefaultsMessage - MyMessageSet - Empty - MessageList - Strings - Defaults - SubDefaults - RepeatedEnum - MoreRepeated - GroupOld - GroupNew - FloatingPoint - MessageWithMap - Communique -*/ -package testdata - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} - -// An enum, for completeness. -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - // Basic types - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - // Groupings - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - // Table types - GoTest_TABLE GoTest_KIND = 11 - // Functions - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} - -type DefaultsMessage_DefaultsEnum int32 - -const ( - DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 - DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 - DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 -) - -var DefaultsMessage_DefaultsEnum_name = map[int32]string{ - 0: "ZERO", - 1: "ONE", - 2: "TWO", -} -var DefaultsMessage_DefaultsEnum_value = map[string]int32{ - "ZERO": 0, - "ONE": 1, - "TWO": 2, -} - -func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { - p := new(DefaultsMessage_DefaultsEnum) - *p = x - return p -} -func (x DefaultsMessage_DefaultsEnum) String() string { - return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) -} -func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") - if err != nil { - return err - } - *x = DefaultsMessage_DefaultsEnum(value) - return nil -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return FOO_FOO1 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req,name=Label" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req,name=Type" json:"Type,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - // Some typical parameters - Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"` - // Required, repeated and optional foreign fields. - RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField" json:"OptionalField,omitempty"` - // Required fields of all basic types - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` - // Repeated fields of all basic types - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` - // Optional fields of all basic types - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` - // Default-valued fields of all basic types - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - // Packed repeated fields (no string or bytes). - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return GoTest_VOID -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -// Required, repeated, and optional groups. -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } -func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RequiredGroup) ProtoMessage() {} - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } -func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RepeatedGroup) ProtoMessage() {} - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } -func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_OptionalGroup) ProtoMessage() {} - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } -func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest_SkipGroup) ProtoMessage() {} - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - // Maximum possible tag number. - LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *OldMessage) GetNum() int32 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - // This is an int32 in OldMessage. - Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *NewMessage) GetNum() int64 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` - // This field becomes [][]byte in the generated code. - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} - -var extRange_MyMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetRepInner() []*InnerMessage { - if m != nil { - return m.RepInner - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return MyMessage_RED -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } -func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*MyMessage_SomeGroup) ProtoMessage() {} - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "testdata.Ext.more", - Tag: "bytes,103,opt,name=more", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "testdata.Ext.text", - Tag: "bytes,104,opt,name=text", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "testdata.Ext.number", - Tag: "varint,105,opt,name=number", -} - -type DefaultsMessage struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } -func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } -func (*DefaultsMessage) ProtoMessage() {} - -var extRange_DefaultsMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_DefaultsMessage -} -func (m *DefaultsMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type MyMessageSet struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } -func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } -func (*MyMessageSet) ProtoMessage() {} - -func (m *MyMessageSet) Marshal() ([]byte, error) { - return proto.MarshalMessageSet(m.ExtensionMap()) -} -func (m *MyMessageSet) Unmarshal(buf []byte) error { - return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) -} -func (m *MyMessageSet) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(m.XXX_extensions) -} -func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) -} - -// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler -var _ proto.Marshaler = (*MyMessageSet)(nil) -var _ proto.Unmarshaler = (*MyMessageSet)(nil) - -var extRange_MyMessageSet = []proto.ExtensionRange{ - {100, 2147483646}, -} - -func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessageSet -} -func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep,name=Message" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } -func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } -func (*MessageList_Message) ProtoMessage() {} - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,name=F_String,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` - // More fields with crazy defaults. - F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,def=nan" json:"F_Nan,omitempty"` - // Sub-message. - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - // Redundant but explicit defaults. - StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -func (m *Defaults) GetStrZero() string { - if m != nil && m.StrZero != nil { - return *m.StrZero - } - return "" -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` - Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetInt64SPacked() []int64 { - if m != nil { - return m.Int64SPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -func (m *MoreRepeated) GetFixeds() []uint32 { - if m != nil { - return m.Fixeds - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,101,opt,name=G" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } -func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } -func (*GroupOld_G) ProtoMessage() {} - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,101,opt,name=G" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } -func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } -func (*GroupNew_G) ProtoMessage() {} - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type FloatingPoint struct { - F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } -func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } -func (*FloatingPoint) ProtoMessage() {} - -func (m *FloatingPoint) GetF() float64 { - if m != nil && m.F != nil { - return *m.F - } - return 0 -} - -type MessageWithMap struct { - NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} - -func (m *MessageWithMap) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -func (m *MessageWithMap) GetStrToStr() map[string]string { - if m != nil { - return m.StrToStr - } - return nil -} - -type Communique struct { - MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry" json:"make_me_cry,omitempty"` - // This is a oneof, called "union". - // - // Types that are valid to be assigned to Union: - // *Communique_Number - // *Communique_Name - // *Communique_Data - // *Communique_TempC - // *Communique_Col - // *Communique_Msg - Union isCommunique_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Communique) Reset() { *m = Communique{} } -func (m *Communique) String() string { return proto.CompactTextString(m) } -func (*Communique) ProtoMessage() {} - -type isCommunique_Union interface { - isCommunique_Union() -} - -type Communique_Number struct { - Number int32 `protobuf:"varint,5,opt,name=number,oneof"` -} -type Communique_Name struct { - Name string `protobuf:"bytes,6,opt,name=name,oneof"` -} -type Communique_Data struct { - Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` -} -type Communique_TempC struct { - TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,oneof"` -} -type Communique_Col struct { - Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"` -} -type Communique_Msg struct { - Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"` -} - -func (*Communique_Number) isCommunique_Union() {} -func (*Communique_Name) isCommunique_Union() {} -func (*Communique_Data) isCommunique_Union() {} -func (*Communique_TempC) isCommunique_Union() {} -func (*Communique_Col) isCommunique_Union() {} -func (*Communique_Msg) isCommunique_Union() {} - -func (m *Communique) GetUnion() isCommunique_Union { - if m != nil { - return m.Union - } - return nil -} - -func (m *Communique) GetMakeMeCry() bool { - if m != nil && m.MakeMeCry != nil { - return *m.MakeMeCry - } - return false -} - -func (m *Communique) GetNumber() int32 { - if x, ok := m.GetUnion().(*Communique_Number); ok { - return x.Number - } - return 0 -} - -func (m *Communique) GetName() string { - if x, ok := m.GetUnion().(*Communique_Name); ok { - return x.Name - } - return "" -} - -func (m *Communique) GetData() []byte { - if x, ok := m.GetUnion().(*Communique_Data); ok { - return x.Data - } - return nil -} - -func (m *Communique) GetTempC() float64 { - if x, ok := m.GetUnion().(*Communique_TempC); ok { - return x.TempC - } - return 0 -} - -func (m *Communique) GetCol() MyMessage_Color { - if x, ok := m.GetUnion().(*Communique_Col); ok { - return x.Col - } - return MyMessage_RED -} - -func (m *Communique) GetMsg() *Strings { - if x, ok := m.GetUnion().(*Communique_Msg); ok { - return x.Msg - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), []interface{}) { - return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, []interface{}{ - (*Communique_Number)(nil), - (*Communique_Name)(nil), - (*Communique_Data)(nil), - (*Communique_TempC)(nil), - (*Communique_Col)(nil), - (*Communique_Msg)(nil), - } -} - -func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Communique) - // union - switch x := m.Union.(type) { - case *Communique_Number: - _ = b.EncodeVarint(5<<3 | proto.WireVarint) - _ = b.EncodeVarint(uint64(x.Number)) - case *Communique_Name: - _ = b.EncodeVarint(6<<3 | proto.WireBytes) - _ = b.EncodeStringBytes(x.Name) - case *Communique_Data: - _ = b.EncodeVarint(7<<3 | proto.WireBytes) - _ = b.EncodeRawBytes(x.Data) - case *Communique_TempC: - _ = b.EncodeVarint(8<<3 | proto.WireFixed64) - _ = b.EncodeFixed64(math.Float64bits(x.TempC)) - case *Communique_Col: - _ = b.EncodeVarint(9<<3 | proto.WireVarint) - _ = b.EncodeVarint(uint64(x.Col)) - case *Communique_Msg: - _ = b.EncodeVarint(10<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Msg); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("Communique.Union has unexpected type %T", x) - } - return nil -} - -func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Communique) - switch tag { - case 5: // union.number - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Number{int32(x)} - return true, err - case 6: // union.name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &Communique_Name{x} - return true, err - case 7: // union.data - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Union = &Communique_Data{x} - return true, err - case 8: // union.temp_c - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Union = &Communique_TempC{math.Float64frombits(x)} - return true, err - case 9: // union.col - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Col{MyMessage_Color(x)} - return true, err - case 10: // union.msg - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Strings) - err := b.DecodeMessage(msg) - m.Union = &Communique_Msg{msg} - return true, err - default: - return false, nil - } -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "testdata.greeting", - Tag: "bytes,106,rep,name=greeting", -} - -var E_NoDefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 101, - Name: "testdata.no_default_double", - Tag: "fixed64,101,opt,name=no_default_double", -} - -var E_NoDefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 102, - Name: "testdata.no_default_float", - Tag: "fixed32,102,opt,name=no_default_float", -} - -var E_NoDefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 103, - Name: "testdata.no_default_int32", - Tag: "varint,103,opt,name=no_default_int32", -} - -var E_NoDefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 104, - Name: "testdata.no_default_int64", - Tag: "varint,104,opt,name=no_default_int64", -} - -var E_NoDefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 105, - Name: "testdata.no_default_uint32", - Tag: "varint,105,opt,name=no_default_uint32", -} - -var E_NoDefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 106, - Name: "testdata.no_default_uint64", - Tag: "varint,106,opt,name=no_default_uint64", -} - -var E_NoDefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 107, - Name: "testdata.no_default_sint32", - Tag: "zigzag32,107,opt,name=no_default_sint32", -} - -var E_NoDefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 108, - Name: "testdata.no_default_sint64", - Tag: "zigzag64,108,opt,name=no_default_sint64", -} - -var E_NoDefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 109, - Name: "testdata.no_default_fixed32", - Tag: "fixed32,109,opt,name=no_default_fixed32", -} - -var E_NoDefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 110, - Name: "testdata.no_default_fixed64", - Tag: "fixed64,110,opt,name=no_default_fixed64", -} - -var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 111, - Name: "testdata.no_default_sfixed32", - Tag: "fixed32,111,opt,name=no_default_sfixed32", -} - -var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 112, - Name: "testdata.no_default_sfixed64", - Tag: "fixed64,112,opt,name=no_default_sfixed64", -} - -var E_NoDefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 113, - Name: "testdata.no_default_bool", - Tag: "varint,113,opt,name=no_default_bool", -} - -var E_NoDefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 114, - Name: "testdata.no_default_string", - Tag: "bytes,114,opt,name=no_default_string", -} - -var E_NoDefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 115, - Name: "testdata.no_default_bytes", - Tag: "bytes,115,opt,name=no_default_bytes", -} - -var E_NoDefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 116, - Name: "testdata.no_default_enum", - Tag: "varint,116,opt,name=no_default_enum,enum=testdata.DefaultsMessage_DefaultsEnum", -} - -var E_DefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 201, - Name: "testdata.default_double", - Tag: "fixed64,201,opt,name=default_double,def=3.1415", -} - -var E_DefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 202, - Name: "testdata.default_float", - Tag: "fixed32,202,opt,name=default_float,def=3.14", -} - -var E_DefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 203, - Name: "testdata.default_int32", - Tag: "varint,203,opt,name=default_int32,def=42", -} - -var E_DefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 204, - Name: "testdata.default_int64", - Tag: "varint,204,opt,name=default_int64,def=43", -} - -var E_DefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 205, - Name: "testdata.default_uint32", - Tag: "varint,205,opt,name=default_uint32,def=44", -} - -var E_DefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 206, - Name: "testdata.default_uint64", - Tag: "varint,206,opt,name=default_uint64,def=45", -} - -var E_DefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 207, - Name: "testdata.default_sint32", - Tag: "zigzag32,207,opt,name=default_sint32,def=46", -} - -var E_DefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 208, - Name: "testdata.default_sint64", - Tag: "zigzag64,208,opt,name=default_sint64,def=47", -} - -var E_DefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 209, - Name: "testdata.default_fixed32", - Tag: "fixed32,209,opt,name=default_fixed32,def=48", -} - -var E_DefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 210, - Name: "testdata.default_fixed64", - Tag: "fixed64,210,opt,name=default_fixed64,def=49", -} - -var E_DefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 211, - Name: "testdata.default_sfixed32", - Tag: "fixed32,211,opt,name=default_sfixed32,def=50", -} - -var E_DefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 212, - Name: "testdata.default_sfixed64", - Tag: "fixed64,212,opt,name=default_sfixed64,def=51", -} - -var E_DefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 213, - Name: "testdata.default_bool", - Tag: "varint,213,opt,name=default_bool,def=1", -} - -var E_DefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 214, - Name: "testdata.default_string", - Tag: "bytes,214,opt,name=default_string,def=Hello, string", -} - -var E_DefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 215, - Name: "testdata.default_bytes", - Tag: "bytes,215,opt,name=default_bytes,def=Hello, bytes", -} - -var E_DefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 216, - Name: "testdata.default_enum", - Tag: "varint,216,opt,name=default_enum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", -} - -var E_X201 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 201, - Name: "testdata.x201", - Tag: "bytes,201,opt,name=x201", -} - -var E_X202 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 202, - Name: "testdata.x202", - Tag: "bytes,202,opt,name=x202", -} - -var E_X203 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 203, - Name: "testdata.x203", - Tag: "bytes,203,opt,name=x203", -} - -var E_X204 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 204, - Name: "testdata.x204", - Tag: "bytes,204,opt,name=x204", -} - -var E_X205 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 205, - Name: "testdata.x205", - Tag: "bytes,205,opt,name=x205", -} - -var E_X206 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 206, - Name: "testdata.x206", - Tag: "bytes,206,opt,name=x206", -} - -var E_X207 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 207, - Name: "testdata.x207", - Tag: "bytes,207,opt,name=x207", -} - -var E_X208 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 208, - Name: "testdata.x208", - Tag: "bytes,208,opt,name=x208", -} - -var E_X209 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 209, - Name: "testdata.x209", - Tag: "bytes,209,opt,name=x209", -} - -var E_X210 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 210, - Name: "testdata.x210", - Tag: "bytes,210,opt,name=x210", -} - -var E_X211 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 211, - Name: "testdata.x211", - Tag: "bytes,211,opt,name=x211", -} - -var E_X212 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 212, - Name: "testdata.x212", - Tag: "bytes,212,opt,name=x212", -} - -var E_X213 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 213, - Name: "testdata.x213", - Tag: "bytes,213,opt,name=x213", -} - -var E_X214 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 214, - Name: "testdata.x214", - Tag: "bytes,214,opt,name=x214", -} - -var E_X215 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 215, - Name: "testdata.x215", - Tag: "bytes,215,opt,name=x215", -} - -var E_X216 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 216, - Name: "testdata.x216", - Tag: "bytes,216,opt,name=x216", -} - -var E_X217 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 217, - Name: "testdata.x217", - Tag: "bytes,217,opt,name=x217", -} - -var E_X218 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 218, - Name: "testdata.x218", - Tag: "bytes,218,opt,name=x218", -} - -var E_X219 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 219, - Name: "testdata.x219", - Tag: "bytes,219,opt,name=x219", -} - -var E_X220 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 220, - Name: "testdata.x220", - Tag: "bytes,220,opt,name=x220", -} - -var E_X221 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 221, - Name: "testdata.x221", - Tag: "bytes,221,opt,name=x221", -} - -var E_X222 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 222, - Name: "testdata.x222", - Tag: "bytes,222,opt,name=x222", -} - -var E_X223 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 223, - Name: "testdata.x223", - Tag: "bytes,223,opt,name=x223", -} - -var E_X224 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 224, - Name: "testdata.x224", - Tag: "bytes,224,opt,name=x224", -} - -var E_X225 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 225, - Name: "testdata.x225", - Tag: "bytes,225,opt,name=x225", -} - -var E_X226 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 226, - Name: "testdata.x226", - Tag: "bytes,226,opt,name=x226", -} - -var E_X227 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 227, - Name: "testdata.x227", - Tag: "bytes,227,opt,name=x227", -} - -var E_X228 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 228, - Name: "testdata.x228", - Tag: "bytes,228,opt,name=x228", -} - -var E_X229 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 229, - Name: "testdata.x229", - Tag: "bytes,229,opt,name=x229", -} - -var E_X230 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 230, - Name: "testdata.x230", - Tag: "bytes,230,opt,name=x230", -} - -var E_X231 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 231, - Name: "testdata.x231", - Tag: "bytes,231,opt,name=x231", -} - -var E_X232 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 232, - Name: "testdata.x232", - Tag: "bytes,232,opt,name=x232", -} - -var E_X233 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 233, - Name: "testdata.x233", - Tag: "bytes,233,opt,name=x233", -} - -var E_X234 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 234, - Name: "testdata.x234", - Tag: "bytes,234,opt,name=x234", -} - -var E_X235 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 235, - Name: "testdata.x235", - Tag: "bytes,235,opt,name=x235", -} - -var E_X236 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 236, - Name: "testdata.x236", - Tag: "bytes,236,opt,name=x236", -} - -var E_X237 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 237, - Name: "testdata.x237", - Tag: "bytes,237,opt,name=x237", -} - -var E_X238 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 238, - Name: "testdata.x238", - Tag: "bytes,238,opt,name=x238", -} - -var E_X239 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 239, - Name: "testdata.x239", - Tag: "bytes,239,opt,name=x239", -} - -var E_X240 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 240, - Name: "testdata.x240", - Tag: "bytes,240,opt,name=x240", -} - -var E_X241 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 241, - Name: "testdata.x241", - Tag: "bytes,241,opt,name=x241", -} - -var E_X242 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 242, - Name: "testdata.x242", - Tag: "bytes,242,opt,name=x242", -} - -var E_X243 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 243, - Name: "testdata.x243", - Tag: "bytes,243,opt,name=x243", -} - -var E_X244 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 244, - Name: "testdata.x244", - Tag: "bytes,244,opt,name=x244", -} - -var E_X245 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 245, - Name: "testdata.x245", - Tag: "bytes,245,opt,name=x245", -} - -var E_X246 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 246, - Name: "testdata.x246", - Tag: "bytes,246,opt,name=x246", -} - -var E_X247 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 247, - Name: "testdata.x247", - Tag: "bytes,247,opt,name=x247", -} - -var E_X248 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 248, - Name: "testdata.x248", - Tag: "bytes,248,opt,name=x248", -} - -var E_X249 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 249, - Name: "testdata.x249", - Tag: "bytes,249,opt,name=x249", -} - -var E_X250 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 250, - Name: "testdata.x250", - Tag: "bytes,250,opt,name=x250", -} - -func init() { - proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) - proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) - proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) - proto.RegisterExtension(E_NoDefaultDouble) - proto.RegisterExtension(E_NoDefaultFloat) - proto.RegisterExtension(E_NoDefaultInt32) - proto.RegisterExtension(E_NoDefaultInt64) - proto.RegisterExtension(E_NoDefaultUint32) - proto.RegisterExtension(E_NoDefaultUint64) - proto.RegisterExtension(E_NoDefaultSint32) - proto.RegisterExtension(E_NoDefaultSint64) - proto.RegisterExtension(E_NoDefaultFixed32) - proto.RegisterExtension(E_NoDefaultFixed64) - proto.RegisterExtension(E_NoDefaultSfixed32) - proto.RegisterExtension(E_NoDefaultSfixed64) - proto.RegisterExtension(E_NoDefaultBool) - proto.RegisterExtension(E_NoDefaultString) - proto.RegisterExtension(E_NoDefaultBytes) - proto.RegisterExtension(E_NoDefaultEnum) - proto.RegisterExtension(E_DefaultDouble) - proto.RegisterExtension(E_DefaultFloat) - proto.RegisterExtension(E_DefaultInt32) - proto.RegisterExtension(E_DefaultInt64) - proto.RegisterExtension(E_DefaultUint32) - proto.RegisterExtension(E_DefaultUint64) - proto.RegisterExtension(E_DefaultSint32) - proto.RegisterExtension(E_DefaultSint64) - proto.RegisterExtension(E_DefaultFixed32) - proto.RegisterExtension(E_DefaultFixed64) - proto.RegisterExtension(E_DefaultSfixed32) - proto.RegisterExtension(E_DefaultSfixed64) - proto.RegisterExtension(E_DefaultBool) - proto.RegisterExtension(E_DefaultString) - proto.RegisterExtension(E_DefaultBytes) - proto.RegisterExtension(E_DefaultEnum) - proto.RegisterExtension(E_X201) - proto.RegisterExtension(E_X202) - proto.RegisterExtension(E_X203) - proto.RegisterExtension(E_X204) - proto.RegisterExtension(E_X205) - proto.RegisterExtension(E_X206) - proto.RegisterExtension(E_X207) - proto.RegisterExtension(E_X208) - proto.RegisterExtension(E_X209) - proto.RegisterExtension(E_X210) - proto.RegisterExtension(E_X211) - proto.RegisterExtension(E_X212) - proto.RegisterExtension(E_X213) - proto.RegisterExtension(E_X214) - proto.RegisterExtension(E_X215) - proto.RegisterExtension(E_X216) - proto.RegisterExtension(E_X217) - proto.RegisterExtension(E_X218) - proto.RegisterExtension(E_X219) - proto.RegisterExtension(E_X220) - proto.RegisterExtension(E_X221) - proto.RegisterExtension(E_X222) - proto.RegisterExtension(E_X223) - proto.RegisterExtension(E_X224) - proto.RegisterExtension(E_X225) - proto.RegisterExtension(E_X226) - proto.RegisterExtension(E_X227) - proto.RegisterExtension(E_X228) - proto.RegisterExtension(E_X229) - proto.RegisterExtension(E_X230) - proto.RegisterExtension(E_X231) - proto.RegisterExtension(E_X232) - proto.RegisterExtension(E_X233) - proto.RegisterExtension(E_X234) - proto.RegisterExtension(E_X235) - proto.RegisterExtension(E_X236) - proto.RegisterExtension(E_X237) - proto.RegisterExtension(E_X238) - proto.RegisterExtension(E_X239) - proto.RegisterExtension(E_X240) - proto.RegisterExtension(E_X241) - proto.RegisterExtension(E_X242) - proto.RegisterExtension(E_X243) - proto.RegisterExtension(E_X244) - proto.RegisterExtension(E_X245) - proto.RegisterExtension(E_X246) - proto.RegisterExtension(E_X247) - proto.RegisterExtension(E_X248) - proto.RegisterExtension(E_X249) - proto.RegisterExtension(E_X250) -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go.golden b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go.golden deleted file mode 100644 index 0387853d56c..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.pb.go.golden +++ /dev/null @@ -1,1737 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: test.proto -// DO NOT EDIT! - -package testdata - -import proto "github.com/gogo/protobuf/proto" -import json "encoding/json" -import math "math" - -import () - -// Reference proto, json, and math imports to suppress error if they are not otherwise used. -var _ = proto.Marshal -var _ = &json.SyntaxError{} -var _ = math.Inf - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x FOO) MarshalJSON() ([]byte, error) { - return json.Marshal(x.String()) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} - -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - GoTest_TABLE GoTest_KIND = 11 - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x GoTest_KIND) MarshalJSON() ([]byte, error) { - return json.Marshal(x.String()) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x MyMessage_Color) MarshalJSON() ([]byte, error) { - return json.Marshal(x.String()) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x Defaults_Color) MarshalJSON() ([]byte, error) { - return json.Marshal(x.String()) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x RepeatedEnum_Color) MarshalJSON() ([]byte, error) { - return json.Marshal(x.String()) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return 0 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"` - RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"` - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return 0 -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} - -var extRange_MyMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return 0 -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "testdata.Ext.more", - Tag: "bytes,103,opt,name=more", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "testdata.Ext.text", - Tag: "bytes,104,opt,name=text", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "testdata.Ext.number", - Tag: "varint,105,opt,name=number", -} - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` - F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"` - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,1,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,1,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "testdata.greeting", - Tag: "bytes,106,rep,name=greeting", -} - -func init() { - proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) - proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.proto deleted file mode 100644 index 3d1cbb675d5..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/test.proto +++ /dev/null @@ -1,494 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// A feature-rich test file for the protocol compiler and libraries. - -syntax = "proto2"; - -package testdata; - -enum FOO { FOO1 = 1; }; - -message GoEnum { - required FOO foo = 1; -} - -message GoTestField { - required string Label = 1; - required string Type = 2; -} - -message GoTest { - // An enum, for completeness. - enum KIND { - VOID = 0; - - // Basic types - BOOL = 1; - BYTES = 2; - FINGERPRINT = 3; - FLOAT = 4; - INT = 5; - STRING = 6; - TIME = 7; - - // Groupings - TUPLE = 8; - ARRAY = 9; - MAP = 10; - - // Table types - TABLE = 11; - - // Functions - FUNCTION = 12; // last tag - }; - - // Some typical parameters - required KIND Kind = 1; - optional string Table = 2; - optional int32 Param = 3; - - // Required, repeated and optional foreign fields. - required GoTestField RequiredField = 4; - repeated GoTestField RepeatedField = 5; - optional GoTestField OptionalField = 6; - - // Required fields of all basic types - required bool F_Bool_required = 10; - required int32 F_Int32_required = 11; - required int64 F_Int64_required = 12; - required fixed32 F_Fixed32_required = 13; - required fixed64 F_Fixed64_required = 14; - required uint32 F_Uint32_required = 15; - required uint64 F_Uint64_required = 16; - required float F_Float_required = 17; - required double F_Double_required = 18; - required string F_String_required = 19; - required bytes F_Bytes_required = 101; - required sint32 F_Sint32_required = 102; - required sint64 F_Sint64_required = 103; - - // Repeated fields of all basic types - repeated bool F_Bool_repeated = 20; - repeated int32 F_Int32_repeated = 21; - repeated int64 F_Int64_repeated = 22; - repeated fixed32 F_Fixed32_repeated = 23; - repeated fixed64 F_Fixed64_repeated = 24; - repeated uint32 F_Uint32_repeated = 25; - repeated uint64 F_Uint64_repeated = 26; - repeated float F_Float_repeated = 27; - repeated double F_Double_repeated = 28; - repeated string F_String_repeated = 29; - repeated bytes F_Bytes_repeated = 201; - repeated sint32 F_Sint32_repeated = 202; - repeated sint64 F_Sint64_repeated = 203; - - // Optional fields of all basic types - optional bool F_Bool_optional = 30; - optional int32 F_Int32_optional = 31; - optional int64 F_Int64_optional = 32; - optional fixed32 F_Fixed32_optional = 33; - optional fixed64 F_Fixed64_optional = 34; - optional uint32 F_Uint32_optional = 35; - optional uint64 F_Uint64_optional = 36; - optional float F_Float_optional = 37; - optional double F_Double_optional = 38; - optional string F_String_optional = 39; - optional bytes F_Bytes_optional = 301; - optional sint32 F_Sint32_optional = 302; - optional sint64 F_Sint64_optional = 303; - - // Default-valued fields of all basic types - optional bool F_Bool_defaulted = 40 [default=true]; - optional int32 F_Int32_defaulted = 41 [default=32]; - optional int64 F_Int64_defaulted = 42 [default=64]; - optional fixed32 F_Fixed32_defaulted = 43 [default=320]; - optional fixed64 F_Fixed64_defaulted = 44 [default=640]; - optional uint32 F_Uint32_defaulted = 45 [default=3200]; - optional uint64 F_Uint64_defaulted = 46 [default=6400]; - optional float F_Float_defaulted = 47 [default=314159.]; - optional double F_Double_defaulted = 48 [default=271828.]; - optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; - optional sint32 F_Sint32_defaulted = 402 [default = -32]; - optional sint64 F_Sint64_defaulted = 403 [default = -64]; - - // Packed repeated fields (no string or bytes). - repeated bool F_Bool_repeated_packed = 50 [packed=true]; - repeated int32 F_Int32_repeated_packed = 51 [packed=true]; - repeated int64 F_Int64_repeated_packed = 52 [packed=true]; - repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; - repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; - repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; - repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; - repeated float F_Float_repeated_packed = 57 [packed=true]; - repeated double F_Double_repeated_packed = 58 [packed=true]; - repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; - repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; - - // Required, repeated, and optional groups. - required group RequiredGroup = 70 { - required string RequiredField = 71; - }; - - repeated group RepeatedGroup = 80 { - required string RequiredField = 81; - }; - - optional group OptionalGroup = 90 { - required string RequiredField = 91; - }; -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -message GoSkipTest { - required int32 skip_int32 = 11; - required fixed32 skip_fixed32 = 12; - required fixed64 skip_fixed64 = 13; - required string skip_string = 14; - required group SkipGroup = 15 { - required int32 group_int32 = 16; - required string group_string = 17; - } -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -message NonPackedTest { - repeated int32 a = 1; -} - -message PackedTest { - repeated int32 b = 1 [packed=true]; -} - -message MaxTag { - // Maximum possible tag number. - optional string last_field = 536870911; -} - -message OldMessage { - message Nested { - optional string name = 1; - } - optional Nested nested = 1; - - optional int32 num = 2; -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -message NewMessage { - message Nested { - optional string name = 1; - optional string food_group = 2; - } - optional Nested nested = 1; - - // This is an int32 in OldMessage. - optional int64 num = 2; -} - -// Smaller tests for ASCII formatting. - -message InnerMessage { - required string host = 1; - optional int32 port = 2 [default=4000]; - optional bool connected = 3; -} - -message OtherMessage { - optional int64 key = 1; - optional bytes value = 2; - optional float weight = 3; - optional InnerMessage inner = 4; -} - -message MyMessage { - required int32 count = 1; - optional string name = 2; - optional string quote = 3; - repeated string pet = 4; - optional InnerMessage inner = 5; - repeated OtherMessage others = 6; - repeated InnerMessage rep_inner = 12; - - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color bikeshed = 7; - - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // This field becomes [][]byte in the generated code. - repeated bytes rep_bytes = 10; - - optional double bigfloat = 11; - - extensions 100 to max; -} - -message Ext { - extend MyMessage { - optional Ext more = 103; - optional string text = 104; - optional int32 number = 105; - } - - optional string data = 1; -} - -extend MyMessage { - repeated string greeting = 106; -} - -message DefaultsMessage { - enum DefaultsEnum { - ZERO = 0; - ONE = 1; - TWO = 2; - }; - extensions 100 to max; -} - -extend DefaultsMessage { - optional double no_default_double = 101; - optional float no_default_float = 102; - optional int32 no_default_int32 = 103; - optional int64 no_default_int64 = 104; - optional uint32 no_default_uint32 = 105; - optional uint64 no_default_uint64 = 106; - optional sint32 no_default_sint32 = 107; - optional sint64 no_default_sint64 = 108; - optional fixed32 no_default_fixed32 = 109; - optional fixed64 no_default_fixed64 = 110; - optional sfixed32 no_default_sfixed32 = 111; - optional sfixed64 no_default_sfixed64 = 112; - optional bool no_default_bool = 113; - optional string no_default_string = 114; - optional bytes no_default_bytes = 115; - optional DefaultsMessage.DefaultsEnum no_default_enum = 116; - - optional double default_double = 201 [default = 3.1415]; - optional float default_float = 202 [default = 3.14]; - optional int32 default_int32 = 203 [default = 42]; - optional int64 default_int64 = 204 [default = 43]; - optional uint32 default_uint32 = 205 [default = 44]; - optional uint64 default_uint64 = 206 [default = 45]; - optional sint32 default_sint32 = 207 [default = 46]; - optional sint64 default_sint64 = 208 [default = 47]; - optional fixed32 default_fixed32 = 209 [default = 48]; - optional fixed64 default_fixed64 = 210 [default = 49]; - optional sfixed32 default_sfixed32 = 211 [default = 50]; - optional sfixed64 default_sfixed64 = 212 [default = 51]; - optional bool default_bool = 213 [default = true]; - optional string default_string = 214 [default = "Hello, string"]; - optional bytes default_bytes = 215 [default = "Hello, bytes"]; - optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; -} - -message MyMessageSet { - option message_set_wire_format = true; - extensions 100 to max; -} - -message Empty { -} - -extend MyMessageSet { - optional Empty x201 = 201; - optional Empty x202 = 202; - optional Empty x203 = 203; - optional Empty x204 = 204; - optional Empty x205 = 205; - optional Empty x206 = 206; - optional Empty x207 = 207; - optional Empty x208 = 208; - optional Empty x209 = 209; - optional Empty x210 = 210; - optional Empty x211 = 211; - optional Empty x212 = 212; - optional Empty x213 = 213; - optional Empty x214 = 214; - optional Empty x215 = 215; - optional Empty x216 = 216; - optional Empty x217 = 217; - optional Empty x218 = 218; - optional Empty x219 = 219; - optional Empty x220 = 220; - optional Empty x221 = 221; - optional Empty x222 = 222; - optional Empty x223 = 223; - optional Empty x224 = 224; - optional Empty x225 = 225; - optional Empty x226 = 226; - optional Empty x227 = 227; - optional Empty x228 = 228; - optional Empty x229 = 229; - optional Empty x230 = 230; - optional Empty x231 = 231; - optional Empty x232 = 232; - optional Empty x233 = 233; - optional Empty x234 = 234; - optional Empty x235 = 235; - optional Empty x236 = 236; - optional Empty x237 = 237; - optional Empty x238 = 238; - optional Empty x239 = 239; - optional Empty x240 = 240; - optional Empty x241 = 241; - optional Empty x242 = 242; - optional Empty x243 = 243; - optional Empty x244 = 244; - optional Empty x245 = 245; - optional Empty x246 = 246; - optional Empty x247 = 247; - optional Empty x248 = 248; - optional Empty x249 = 249; - optional Empty x250 = 250; -} - -message MessageList { - repeated group Message = 1 { - required string name = 2; - required int32 count = 3; - } -} - -message Strings { - optional string string_field = 1; - optional bytes bytes_field = 2; -} - -message Defaults { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - optional bool F_Bool = 1 [default=true]; - optional int32 F_Int32 = 2 [default=32]; - optional int64 F_Int64 = 3 [default=64]; - optional fixed32 F_Fixed32 = 4 [default=320]; - optional fixed64 F_Fixed64 = 5 [default=640]; - optional uint32 F_Uint32 = 6 [default=3200]; - optional uint64 F_Uint64 = 7 [default=6400]; - optional float F_Float = 8 [default=314159.]; - optional double F_Double = 9 [default=271828.]; - optional string F_String = 10 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes = 11 [default="Bignose"]; - optional sint32 F_Sint32 = 12 [default=-32]; - optional sint64 F_Sint64 = 13 [default=-64]; - optional Color F_Enum = 14 [default=GREEN]; - - // More fields with crazy defaults. - optional float F_Pinf = 15 [default=inf]; - optional float F_Ninf = 16 [default=-inf]; - optional float F_Nan = 17 [default=nan]; - - // Sub-message. - optional SubDefaults sub = 18; - - // Redundant but explicit defaults. - optional string str_zero = 19 [default=""]; -} - -message SubDefaults { - optional int64 n = 1 [default=7]; -} - -message RepeatedEnum { - enum Color { - RED = 1; - } - repeated Color color = 1; -} - -message MoreRepeated { - repeated bool bools = 1; - repeated bool bools_packed = 2 [packed=true]; - repeated int32 ints = 3; - repeated int32 ints_packed = 4 [packed=true]; - repeated int64 int64s_packed = 7 [packed=true]; - repeated string strings = 5; - repeated fixed32 fixeds = 6; -} - -// GroupOld and GroupNew have the same wire format. -// GroupNew has a new field inside a group. - -message GroupOld { - optional group G = 101 { - optional int32 x = 2; - } -} - -message GroupNew { - optional group G = 101 { - optional int32 x = 2; - optional int32 y = 3; - } -} - -message FloatingPoint { - required double f = 1; -} - -message MessageWithMap { - map name_mapping = 1; - map msg_mapping = 2; - map byte_mapping = 3; - map str_to_str = 4; -} - -message Communique { - optional bool make_me_cry = 1; - - // This is a oneof, called "union". - oneof union { - int32 number = 5; - string name = 6; - bytes data = 7; - double temp_c = 8; - MyMessage.Color col = 9; - Strings msg = 10; - } -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_parser_test.go deleted file mode 100644 index 0ac8a51c5e9..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,523 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `byte_mapping:` - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - }, - ByteMapping: map[bool][]byte{ - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_test.go deleted file mode 100644 index 6524048428f..00000000000 --- a/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{Number: 4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - Msg: &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{Msg: nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - { - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/glog/glog_test.go b/Godeps/_workspace/src/github.com/golang/glog/glog_test.go deleted file mode 100644 index 0fb376e1fde..00000000000 --- a/Godeps/_workspace/src/github.com/golang/glog/glog_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package glog - -import ( - "bytes" - "fmt" - stdLog "log" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -// Test that shortHostname works as advertised. -func TestShortHostname(t *testing.T) { - for hostname, expect := range map[string]string{ - "": "", - "host": "host", - "host.google.com": "host", - } { - if got := shortHostname(hostname); expect != got { - t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) - } - } -} - -// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. -type flushBuffer struct { - bytes.Buffer -} - -func (f *flushBuffer) Flush() error { - return nil -} - -func (f *flushBuffer) Sync() error { - return nil -} - -// swap sets the log writers and returns the old array. -func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { - l.mu.Lock() - defer l.mu.Unlock() - old = l.file - for i, w := range writers { - logging.file[i] = w - } - return -} - -// newBuffers sets the log writers to all new byte buffers and returns the old array. -func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { - return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) -} - -// contents returns the specified log value as a string. -func contents(s severity) string { - return logging.file[s].(*flushBuffer).String() -} - -// contains reports whether the string is contained in the log. -func contains(s severity, str string, t *testing.T) bool { - return strings.Contains(contents(s), str) -} - -// setFlags configures the logging flags how the test expects them. -func setFlags() { - logging.toStderr = false -} - -// Test that Info works as advertised. -func TestInfo(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -func TestInfoDepth(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - - f := func() { InfoDepth(1, "depth-test1") } - - // The next three lines must stay together - _, _, wantLine, _ := runtime.Caller(0) - InfoDepth(0, "depth-test0") - f() - - msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") - if len(msgs) != 2 { - t.Fatalf("Got %d lines, expected 2", len(msgs)) - } - - for i, m := range msgs { - if !strings.HasPrefix(m, "I") { - t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) - } - w := fmt.Sprintf("depth-test%d", i) - if !strings.Contains(m, w) { - t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) - } - - // pull out the line number (between : and ]) - msg := m[strings.LastIndex(m, ":")+1:] - x := strings.Index(msg, "]") - if x < 0 { - t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) - continue - } - line, err := strconv.Atoi(msg[:x]) - if err != nil { - t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) - continue - } - wantLine++ - if wantLine != line { - t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) - } - } -} - -func init() { - CopyStandardLogTo("INFO") -} - -// Test that CopyStandardLogTo panics on bad input. -func TestCopyStandardLogToPanic(t *testing.T) { - defer func() { - if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { - t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) - } - }() - CopyStandardLogTo("LOG") -} - -// Test that using the standard log package logs to INFO. -func TestStandardLog(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - stdLog.Print("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that the header has the correct format. -func TestHeader(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer func(previous func() time.Time) { timeNow = previous }(timeNow) - timeNow = func() time.Time { - return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) - } - pid = 1234 - Info("test") - var line int - format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" - n, err := fmt.Sscanf(contents(infoLog), format, &line) - if n != 1 || err != nil { - t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) - } - // Scanf treats multiple spaces as equivalent to a single space, - // so check for correct space-padding also. - want := fmt.Sprintf(format, line) - if contents(infoLog) != want { - t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) - } -} - -// Test that an Error log goes to Warning and Info. -// Even in the Info log, the source character will be E, so the data should -// all be identical. -func TestError(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Error("test") - if !contains(errorLog, "E", t) { - t.Errorf("Error has wrong character: %q", contents(errorLog)) - } - if !contains(errorLog, "test", t) { - t.Error("Error failed") - } - str := contents(errorLog) - if !contains(warningLog, str, t) { - t.Error("Warning failed") - } - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a Warning log goes to Info. -// Even in the Info log, the source character will be W, so the data should -// all be identical. -func TestWarning(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Warning("test") - if !contains(warningLog, "W", t) { - t.Errorf("Warning has wrong character: %q", contents(warningLog)) - } - if !contains(warningLog, "test", t) { - t.Error("Warning failed") - } - str := contents(warningLog) - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a V log goes to Info. -func TestV(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.verbosity.Set("2") - defer logging.verbosity.Set("0") - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule enables a log in this file. -func TestVmoduleOn(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("glog_test=2") - defer logging.vmodule.Set("") - if !V(1) { - t.Error("V not enabled for 1") - } - if !V(2) { - t.Error("V not enabled for 2") - } - if V(3) { - t.Error("V enabled for 3") - } - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule of another file does not enable a log in this file. -func TestVmoduleOff(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("notthisfile=2") - defer logging.vmodule.Set("") - for i := 1; i <= 3; i++ { - if V(Level(i)) { - t.Errorf("V enabled for %d", i) - } - } - V(2).Info("test") - if contents(infoLog) != "" { - t.Error("V logged incorrectly") - } -} - -// vGlobs are patterns that match/don't match this file at V=2. -var vGlobs = map[string]bool{ - // Easy to test the numeric match here. - "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. - "glog_test=2": true, - "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. - // These all use 2 and check the patterns. All are true. - "*=2": true, - "?l*=2": true, - "????_*=2": true, - "??[mno]?_*t=2": true, - // These all use 2 and check the patterns. All are false. - "*x=2": false, - "m*=2": false, - "??_*=2": false, - "?[abc]?_*t=2": false, -} - -// Test that vmodule globbing works as advertised. -func testVmoduleGlob(pat string, match bool, t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer logging.vmodule.Set("") - logging.vmodule.Set(pat) - if V(2) != Verbose(match) { - t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) - } -} - -// Test that a vmodule globbing works as advertised. -func TestVmoduleGlob(t *testing.T) { - for glob, match := range vGlobs { - testVmoduleGlob(glob, match, t) - } -} - -func TestRollover(t *testing.T) { - setFlags() - var err error - defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) - logExitFunc = func(e error) { - err = e - } - defer func(previous uint64) { MaxSize = previous }(MaxSize) - MaxSize = 512 - - Info("x") // Be sure we have a file. - info, ok := logging.file[infoLog].(*syncBuffer) - if !ok { - t.Fatal("info wasn't created") - } - if err != nil { - t.Fatalf("info has initial error: %v", err) - } - fname0 := info.file.Name() - Info(strings.Repeat("x", int(MaxSize))) // force a rollover - if err != nil { - t.Fatalf("info has error after big write: %v", err) - } - - // Make sure the next log file gets a file name with a different - // time stamp. - // - // TODO: determine whether we need to support subsecond log - // rotation. C++ does not appear to handle this case (nor does it - // handle Daylight Savings Time properly). - time.Sleep(1 * time.Second) - - Info("x") // create a new file - if err != nil { - t.Fatalf("error after rotation: %v", err) - } - fname1 := info.file.Name() - if fname0 == fname1 { - t.Errorf("info.f.Name did not change: %v", fname0) - } - if info.nbytes >= MaxSize { - t.Errorf("file size was not reset: %d", info.nbytes) - } -} - -func TestLogBacktraceAt(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - // The peculiar style of this code simplifies line counting and maintenance of the - // tracing block below. - var infoLine string - setTraceLocation := func(file string, line int, ok bool, delta int) { - if !ok { - t.Fatal("could not get file:line") - } - _, file = filepath.Split(file) - infoLine = fmt.Sprintf("%s:%d", file, line+delta) - err := logging.traceLocation.Set(infoLine) - if err != nil { - t.Fatal("error setting log_backtrace_at: ", err) - } - } - { - // Start of tracing block. These lines know about each other's relative position. - _, file, line, ok := runtime.Caller(0) - setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. - Info("we want a stack trace here") - } - numAppearances := strings.Count(contents(infoLog), infoLine) - if numAppearances < 2 { - // Need 2 appearances, one in the log header and one in the trace: - // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here - // ... - // github.com/glog/glog_test.go:280 (0x41ba91) - // ... - // We could be more precise but that would require knowing the details - // of the traceback format, which may not be dependable. - t.Fatal("got no trace back; log is ", contents(infoLog)) - } -} - -func BenchmarkHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - buf, _, _ := logging.header(infoLog, 0) - logging.putBuffer(buf) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go b/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go deleted file mode 100644 index 98a2656e883..00000000000 --- a/Godeps/_workspace/src/github.com/golang/groupcache/lru/lru_test.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -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 - -import ( - "testing" -) - -type simpleStruct struct { - int - string -} - -type complexStruct struct { - int - simpleStruct -} - -var getTests = []struct { - name string - keyToAdd interface{} - keyToGet interface{} - expectedOk bool -}{ - {"string_hit", "myKey", "myKey", true}, - {"string_miss", "myKey", "nonsense", false}, - {"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, - {"simeple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, - {"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, - complexStruct{1, simpleStruct{2, "three"}}, true}, -} - -func TestGet(t *testing.T) { - for _, tt := range getTests { - lru := New(0) - lru.Add(tt.keyToAdd, 1234) - val, ok := lru.Get(tt.keyToGet) - if ok != tt.expectedOk { - t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) - } else if ok && val != 1234 { - t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) - } - } -} - -func TestRemove(t *testing.T) { - lru := New(0) - lru.Add("myKey", 1234) - if val, ok := lru.Get("myKey"); !ok { - t.Fatal("TestRemove returned no match") - } else if val != 1234 { - t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) - } - - lru.Remove("myKey") - if _, ok := lru.Get("myKey"); ok { - t.Fatal("TestRemove returned a removed entry") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 3fade175f72..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2059 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "./testdata" - . "github.com/golang/protobuf/proto" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f fakeMarshaler) Marshal() ([]byte, error) { - return f.b, f.err -} - -func (f fakeMarshaler) String() string { - return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) -} - -func (f fakeMarshaler) ProtoMessage() {} - -func (f fakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - wantErr error - }{ - { - name: "Marshaler that fails", - m: fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since there's an error, nothing should be written to buffer. - want: nil, - wantErr: errors.New("some marshal err"), - }, - { - name: "Marshaler that succeeds", - m: fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - wantErr: nil, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if !reflect.DeepEqual(test.wantErr, err) { - t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - if err := o.Marshal(pb); err != ErrRepeatedHasNil { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if strings.Index(err.Error(), "Label") < 0 { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if strings.Index(err.Error(), "{Unknown}") < 0 { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - _, err := Marshal((*GoEnum)(nil)) - if err != ErrNil { - t.Errorf("Marshal: got err %v, want ErrNil", err) - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index 1ac177d216d..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,227 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - pb "./testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go deleted file mode 100644 index cc25833ca44..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - pb "./testdata" - . "github.com/golang/protobuf/proto" -) - -// Four identical base messages. -// The init function adds extensions to some of them. -var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} -var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} - -// Two messages with non-message extensions. -var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} -var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} - -func init() { - ext1 := &pb.Ext{Data: String("Kirk")} - ext2 := &pb.Ext{Data: String("Picard")} - - // messageWithExtension1a has ext1, but never marshals it. - if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1a failed: " + err.Error()) - } - - // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. - if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { - panic("SetExtension on 1b failed: " + err.Error()) - } - buf, err := Marshal(messageWithExtension1b) - if err != nil { - panic("Marshal of 1b failed: " + err.Error()) - } - messageWithExtension1b.Reset() - if err := Unmarshal(buf, messageWithExtension1b); err != nil { - panic("Unmarshal of 1b failed: " + err.Error()) - } - - // messageWithExtension2 has ext2. - if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { - panic("SetExtension on 2 failed: " + err.Error()) - } - - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { - panic("SetExtension on Int32-1 failed: " + err.Error()) - } - if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { - panic("SetExtension on Int32-2 failed: " + err.Error()) - } -} - -var EqualTests = []struct { - desc string - a, b Message - exp bool -}{ - {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, - {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, - {"nil vs nil", nil, nil, true}, - {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, - {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, - {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, - - {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, - {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, - {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, - {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, - - {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, - {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, - {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, - {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, - {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, - {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, - {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, - - { - "nested, different", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, - false, - }, - { - "nested, equal", - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, - true, - }, - - {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, - {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, - {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, - { - "repeated bytes", - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, - true, - }, - - {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, - {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, - {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, - - {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, - {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, - - { - "message with group", - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - &pb.MyMessage{ - Count: Int32(1), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: Int32(5), - }, - }, - true, - }, - - { - "map same", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - true, - }, - { - "map different entry", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, - false, - }, - { - "map different key only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, - false, - }, - { - "map different value only", - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, - &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, - false, - }, -} - -func TestEqual(t *testing.T) { - for _, tc := range EqualTests { - if res := Equal(tc.a, tc.b); res != tc.exp { - t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go deleted file mode 100644 index 451ad871a23..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - pb "./testdata" - "github.com/golang/protobuf/proto" -) - -func TestGetExtensionsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", ext1) - } - exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ - pb.E_Ext_More, - pb.E_Ext_Text, - }) - if err != nil { - t.Fatalf("GetExtensions() failed: %s", err) - } - if exts[0] != ext1 { - t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) - } - if exts[1] != nil { - t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) - } -} - -func TestGetExtensionStability(t *testing.T) { - check := func(m *pb.MyMessage) bool { - ext1, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - ext2, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - return ext1 == ext2 - } - msg := &pb.MyMessage{Count: proto.Int32(4)} - ext0 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { - t.Fatalf("Could not set ext1: %s", ext0) - } - if !check(msg) { - t.Errorf("GetExtension() not stable before marshaling") - } - bb, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Marshal() failed: %s", err) - } - msg1 := &pb.MyMessage{} - err = proto.Unmarshal(bb, msg1) - if err != nil { - t.Fatalf("Unmarshal() failed: %s", err) - } - if !check(msg1) { - t.Errorf("GetExtension() not stable after unmarshaling") - } -} - -func TestExtensionsRoundTrip(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{ - Data: proto.String("hi"), - } - ext2 := &pb.Ext{ - Data: proto.String("there"), - } - exists := proto.HasExtension(msg, pb.E_Ext_More) - if exists { - t.Error("Extension More present unexpectedly") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Error(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { - t.Error(err) - } - e, err := proto.GetExtension(msg, pb.E_Ext_More) - if err != nil { - t.Error(err) - } - x, ok := e.(*pb.Ext) - if !ok { - t.Errorf("e has type %T, expected testdata.Ext", e) - } else if *x.Data != "there" { - t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) - } - proto.ClearExtension(msg, pb.E_Ext_More) - if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { - t.Errorf("got %v, expected ErrMissingExtension", e) - } - if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { - t.Error("expected bad extension error, got nil") - } - if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { - t.Error("expected extension err") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { - t.Error("expected some sort of type mismatch error, got nil") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 7c29bccf4b1..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &MessageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - m := make(map[int32]Extension) - if err := UnmarshalMessageSet(b, m); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := m[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", m) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index d4c96a9e730..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - pb "./proto3_proto" - "github.com/golang/protobuf/proto" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a1b..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index e5f92d6b90a..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "testing" - - proto3pb "./proto3_proto" - pb "./testdata" - . "github.com/golang/protobuf/proto" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile deleted file mode 100644 index fc288628a75..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -include ../../Make.protobuf - -all: regenerate - -regenerate: - rm -f test.pb.go - make test.pb.go - -# The following rules are just aids to development. Not needed for typical testing. - -diff: regenerate - git diff test.pb.go - -restore: - cp test.pb.go.golden test.pb.go - -preserve: - cp test.pb.go test.pb.go.golden diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go deleted file mode 100644 index 7172d0e9698..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Verify that the compiler output for test.proto is unchanged. - -package testdata - -import ( - "crypto/sha1" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" -) - -// sum returns in string form (for easy comparison) the SHA-1 hash of the named file. -func sum(t *testing.T, name string) string { - data, err := ioutil.ReadFile(name) - if err != nil { - t.Fatal(err) - } - t.Logf("sum(%q): length is %d", name, len(data)) - hash := sha1.New() - _, err = hash.Write(data) - if err != nil { - t.Fatal(err) - } - return fmt.Sprintf("% x", hash.Sum(nil)) -} - -func run(t *testing.T, name string, args ...string) { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - err := cmd.Run() - if err != nil { - t.Fatal(err) - } -} - -func TestGolden(t *testing.T) { - // Compute the original checksum. - goldenSum := sum(t, "test.pb.go") - // Run the proto compiler. - run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") - newFile := filepath.Join(os.TempDir(), "test.pb.go") - defer os.Remove(newFile) - // Compute the new checksum. - newSum := sum(t, newFile) - // Verify - if newSum != goldenSum { - run(t, "diff", "-u", "test.pb.go", newFile) - t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go deleted file mode 100644 index f47d9e0e394..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go +++ /dev/null @@ -1,2389 +0,0 @@ -// Code generated by protoc-gen-go. -// source: test.proto -// DO NOT EDIT! - -/* -Package testdata is a generated protocol buffer package. - -It is generated from these files: - test.proto - -It has these top-level messages: - GoEnum - GoTestField - GoTest - GoSkipTest - NonPackedTest - PackedTest - MaxTag - OldMessage - NewMessage - InnerMessage - OtherMessage - MyMessage - Ext - MyMessageSet - Empty - MessageList - Strings - Defaults - SubDefaults - RepeatedEnum - MoreRepeated - GroupOld - GroupNew - FloatingPoint - MessageWithMap -*/ -package testdata - -import proto "github.com/golang/protobuf/proto" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = math.Inf - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} - -// An enum, for completeness. -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - // Basic types - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - // Groupings - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - // Table types - GoTest_TABLE GoTest_KIND = 11 - // Functions - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return FOO_FOO1 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - // Some typical parameters - Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"` - // Required, repeated and optional foreign fields. - RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"` - // Required fields of all basic types - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"` - // Repeated fields of all basic types - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"` - // Optional fields of all basic types - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"` - // Default-valued fields of all basic types - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - // Packed repeated fields (no string or bytes). - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return GoTest_VOID -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -// Required, repeated, and optional groups. -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } -func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RequiredGroup) ProtoMessage() {} - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } -func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RepeatedGroup) ProtoMessage() {} - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } -func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_OptionalGroup) ProtoMessage() {} - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } -func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest_SkipGroup) ProtoMessage() {} - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - // Maximum possible tag number. - LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *OldMessage) GetNum() int32 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - // This is an int32 in OldMessage. - Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *NewMessage) GetNum() int64 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` - // This field becomes [][]byte in the generated code. - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} - -var extRange_MyMessage = []proto.ExtensionRange{ - {100, 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetRepInner() []*InnerMessage { - if m != nil { - return m.RepInner - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return MyMessage_RED -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } -func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*MyMessage_SomeGroup) ProtoMessage() {} - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "testdata.Ext.more", - Tag: "bytes,103,opt,name=more", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "testdata.Ext.text", - Tag: "bytes,104,opt,name=text", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "testdata.Ext.number", - Tag: "varint,105,opt,name=number", -} - -type MyMessageSet struct { - XXX_extensions map[int32]proto.Extension `json:"-"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } -func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } -func (*MyMessageSet) ProtoMessage() {} - -func (m *MyMessageSet) Marshal() ([]byte, error) { - return proto.MarshalMessageSet(m.ExtensionMap()) -} -func (m *MyMessageSet) Unmarshal(buf []byte) error { - return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) -} -func (m *MyMessageSet) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(m.XXX_extensions) -} -func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) -} - -// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler -var _ proto.Marshaler = (*MyMessageSet)(nil) -var _ proto.Unmarshaler = (*MyMessageSet)(nil) - -var extRange_MyMessageSet = []proto.ExtensionRange{ - {100, 2147483646}, -} - -func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessageSet -} -func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension { - if m.XXX_extensions == nil { - m.XXX_extensions = make(map[int32]proto.Extension) - } - return m.XXX_extensions -} - -type Empty struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } -func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } -func (*MessageList_Message) ProtoMessage() {} - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` - // More fields with crazy defaults. - F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"` - // Sub-message. - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - // Redundant but explicit defaults. - StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -func (m *Defaults) GetStrZero() string { - if m != nil && m.StrZero != nil { - return *m.StrZero - } - return "" -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"` - Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetInt64SPacked() []int64 { - if m != nil { - return m.Int64SPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -func (m *MoreRepeated) GetFixeds() []uint32 { - if m != nil { - return m.Fixeds - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } -func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } -func (*GroupOld_G) ProtoMessage() {} - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,101,opt" json:"g,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } -func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } -func (*GroupNew_G) ProtoMessage() {} - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type FloatingPoint struct { - F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } -func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } -func (*FloatingPoint) ProtoMessage() {} - -func (m *FloatingPoint) GetF() float64 { - if m != nil && m.F != nil { - return *m.F - } - return 0 -} - -type MessageWithMap struct { - NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} - -func (m *MessageWithMap) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "testdata.greeting", - Tag: "bytes,106,rep,name=greeting", -} - -var E_X201 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 201, - Name: "testdata.x201", - Tag: "bytes,201,opt,name=x201", -} - -var E_X202 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 202, - Name: "testdata.x202", - Tag: "bytes,202,opt,name=x202", -} - -var E_X203 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 203, - Name: "testdata.x203", - Tag: "bytes,203,opt,name=x203", -} - -var E_X204 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 204, - Name: "testdata.x204", - Tag: "bytes,204,opt,name=x204", -} - -var E_X205 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 205, - Name: "testdata.x205", - Tag: "bytes,205,opt,name=x205", -} - -var E_X206 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 206, - Name: "testdata.x206", - Tag: "bytes,206,opt,name=x206", -} - -var E_X207 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 207, - Name: "testdata.x207", - Tag: "bytes,207,opt,name=x207", -} - -var E_X208 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 208, - Name: "testdata.x208", - Tag: "bytes,208,opt,name=x208", -} - -var E_X209 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 209, - Name: "testdata.x209", - Tag: "bytes,209,opt,name=x209", -} - -var E_X210 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 210, - Name: "testdata.x210", - Tag: "bytes,210,opt,name=x210", -} - -var E_X211 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 211, - Name: "testdata.x211", - Tag: "bytes,211,opt,name=x211", -} - -var E_X212 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 212, - Name: "testdata.x212", - Tag: "bytes,212,opt,name=x212", -} - -var E_X213 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 213, - Name: "testdata.x213", - Tag: "bytes,213,opt,name=x213", -} - -var E_X214 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 214, - Name: "testdata.x214", - Tag: "bytes,214,opt,name=x214", -} - -var E_X215 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 215, - Name: "testdata.x215", - Tag: "bytes,215,opt,name=x215", -} - -var E_X216 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 216, - Name: "testdata.x216", - Tag: "bytes,216,opt,name=x216", -} - -var E_X217 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 217, - Name: "testdata.x217", - Tag: "bytes,217,opt,name=x217", -} - -var E_X218 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 218, - Name: "testdata.x218", - Tag: "bytes,218,opt,name=x218", -} - -var E_X219 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 219, - Name: "testdata.x219", - Tag: "bytes,219,opt,name=x219", -} - -var E_X220 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 220, - Name: "testdata.x220", - Tag: "bytes,220,opt,name=x220", -} - -var E_X221 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 221, - Name: "testdata.x221", - Tag: "bytes,221,opt,name=x221", -} - -var E_X222 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 222, - Name: "testdata.x222", - Tag: "bytes,222,opt,name=x222", -} - -var E_X223 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 223, - Name: "testdata.x223", - Tag: "bytes,223,opt,name=x223", -} - -var E_X224 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 224, - Name: "testdata.x224", - Tag: "bytes,224,opt,name=x224", -} - -var E_X225 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 225, - Name: "testdata.x225", - Tag: "bytes,225,opt,name=x225", -} - -var E_X226 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 226, - Name: "testdata.x226", - Tag: "bytes,226,opt,name=x226", -} - -var E_X227 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 227, - Name: "testdata.x227", - Tag: "bytes,227,opt,name=x227", -} - -var E_X228 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 228, - Name: "testdata.x228", - Tag: "bytes,228,opt,name=x228", -} - -var E_X229 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 229, - Name: "testdata.x229", - Tag: "bytes,229,opt,name=x229", -} - -var E_X230 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 230, - Name: "testdata.x230", - Tag: "bytes,230,opt,name=x230", -} - -var E_X231 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 231, - Name: "testdata.x231", - Tag: "bytes,231,opt,name=x231", -} - -var E_X232 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 232, - Name: "testdata.x232", - Tag: "bytes,232,opt,name=x232", -} - -var E_X233 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 233, - Name: "testdata.x233", - Tag: "bytes,233,opt,name=x233", -} - -var E_X234 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 234, - Name: "testdata.x234", - Tag: "bytes,234,opt,name=x234", -} - -var E_X235 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 235, - Name: "testdata.x235", - Tag: "bytes,235,opt,name=x235", -} - -var E_X236 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 236, - Name: "testdata.x236", - Tag: "bytes,236,opt,name=x236", -} - -var E_X237 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 237, - Name: "testdata.x237", - Tag: "bytes,237,opt,name=x237", -} - -var E_X238 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 238, - Name: "testdata.x238", - Tag: "bytes,238,opt,name=x238", -} - -var E_X239 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 239, - Name: "testdata.x239", - Tag: "bytes,239,opt,name=x239", -} - -var E_X240 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 240, - Name: "testdata.x240", - Tag: "bytes,240,opt,name=x240", -} - -var E_X241 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 241, - Name: "testdata.x241", - Tag: "bytes,241,opt,name=x241", -} - -var E_X242 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 242, - Name: "testdata.x242", - Tag: "bytes,242,opt,name=x242", -} - -var E_X243 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 243, - Name: "testdata.x243", - Tag: "bytes,243,opt,name=x243", -} - -var E_X244 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 244, - Name: "testdata.x244", - Tag: "bytes,244,opt,name=x244", -} - -var E_X245 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 245, - Name: "testdata.x245", - Tag: "bytes,245,opt,name=x245", -} - -var E_X246 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 246, - Name: "testdata.x246", - Tag: "bytes,246,opt,name=x246", -} - -var E_X247 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 247, - Name: "testdata.x247", - Tag: "bytes,247,opt,name=x247", -} - -var E_X248 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 248, - Name: "testdata.x248", - Tag: "bytes,248,opt,name=x248", -} - -var E_X249 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 249, - Name: "testdata.x249", - Tag: "bytes,249,opt,name=x249", -} - -var E_X250 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 250, - Name: "testdata.x250", - Tag: "bytes,250,opt,name=x250", -} - -func init() { - proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) - proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) - proto.RegisterExtension(E_X201) - proto.RegisterExtension(E_X202) - proto.RegisterExtension(E_X203) - proto.RegisterExtension(E_X204) - proto.RegisterExtension(E_X205) - proto.RegisterExtension(E_X206) - proto.RegisterExtension(E_X207) - proto.RegisterExtension(E_X208) - proto.RegisterExtension(E_X209) - proto.RegisterExtension(E_X210) - proto.RegisterExtension(E_X211) - proto.RegisterExtension(E_X212) - proto.RegisterExtension(E_X213) - proto.RegisterExtension(E_X214) - proto.RegisterExtension(E_X215) - proto.RegisterExtension(E_X216) - proto.RegisterExtension(E_X217) - proto.RegisterExtension(E_X218) - proto.RegisterExtension(E_X219) - proto.RegisterExtension(E_X220) - proto.RegisterExtension(E_X221) - proto.RegisterExtension(E_X222) - proto.RegisterExtension(E_X223) - proto.RegisterExtension(E_X224) - proto.RegisterExtension(E_X225) - proto.RegisterExtension(E_X226) - proto.RegisterExtension(E_X227) - proto.RegisterExtension(E_X228) - proto.RegisterExtension(E_X229) - proto.RegisterExtension(E_X230) - proto.RegisterExtension(E_X231) - proto.RegisterExtension(E_X232) - proto.RegisterExtension(E_X233) - proto.RegisterExtension(E_X234) - proto.RegisterExtension(E_X235) - proto.RegisterExtension(E_X236) - proto.RegisterExtension(E_X237) - proto.RegisterExtension(E_X238) - proto.RegisterExtension(E_X239) - proto.RegisterExtension(E_X240) - proto.RegisterExtension(E_X241) - proto.RegisterExtension(E_X242) - proto.RegisterExtension(E_X243) - proto.RegisterExtension(E_X244) - proto.RegisterExtension(E_X245) - proto.RegisterExtension(E_X246) - proto.RegisterExtension(E_X247) - proto.RegisterExtension(E_X248) - proto.RegisterExtension(E_X249) - proto.RegisterExtension(E_X250) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto deleted file mode 100644 index 6cc755baef8..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto +++ /dev/null @@ -1,434 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// A feature-rich test file for the protocol compiler and libraries. - -syntax = "proto2"; - -package testdata; - -enum FOO { FOO1 = 1; }; - -message GoEnum { - required FOO foo = 1; -} - -message GoTestField { - required string Label = 1; - required string Type = 2; -} - -message GoTest { - // An enum, for completeness. - enum KIND { - VOID = 0; - - // Basic types - BOOL = 1; - BYTES = 2; - FINGERPRINT = 3; - FLOAT = 4; - INT = 5; - STRING = 6; - TIME = 7; - - // Groupings - TUPLE = 8; - ARRAY = 9; - MAP = 10; - - // Table types - TABLE = 11; - - // Functions - FUNCTION = 12; // last tag - }; - - // Some typical parameters - required KIND Kind = 1; - optional string Table = 2; - optional int32 Param = 3; - - // Required, repeated and optional foreign fields. - required GoTestField RequiredField = 4; - repeated GoTestField RepeatedField = 5; - optional GoTestField OptionalField = 6; - - // Required fields of all basic types - required bool F_Bool_required = 10; - required int32 F_Int32_required = 11; - required int64 F_Int64_required = 12; - required fixed32 F_Fixed32_required = 13; - required fixed64 F_Fixed64_required = 14; - required uint32 F_Uint32_required = 15; - required uint64 F_Uint64_required = 16; - required float F_Float_required = 17; - required double F_Double_required = 18; - required string F_String_required = 19; - required bytes F_Bytes_required = 101; - required sint32 F_Sint32_required = 102; - required sint64 F_Sint64_required = 103; - - // Repeated fields of all basic types - repeated bool F_Bool_repeated = 20; - repeated int32 F_Int32_repeated = 21; - repeated int64 F_Int64_repeated = 22; - repeated fixed32 F_Fixed32_repeated = 23; - repeated fixed64 F_Fixed64_repeated = 24; - repeated uint32 F_Uint32_repeated = 25; - repeated uint64 F_Uint64_repeated = 26; - repeated float F_Float_repeated = 27; - repeated double F_Double_repeated = 28; - repeated string F_String_repeated = 29; - repeated bytes F_Bytes_repeated = 201; - repeated sint32 F_Sint32_repeated = 202; - repeated sint64 F_Sint64_repeated = 203; - - // Optional fields of all basic types - optional bool F_Bool_optional = 30; - optional int32 F_Int32_optional = 31; - optional int64 F_Int64_optional = 32; - optional fixed32 F_Fixed32_optional = 33; - optional fixed64 F_Fixed64_optional = 34; - optional uint32 F_Uint32_optional = 35; - optional uint64 F_Uint64_optional = 36; - optional float F_Float_optional = 37; - optional double F_Double_optional = 38; - optional string F_String_optional = 39; - optional bytes F_Bytes_optional = 301; - optional sint32 F_Sint32_optional = 302; - optional sint64 F_Sint64_optional = 303; - - // Default-valued fields of all basic types - optional bool F_Bool_defaulted = 40 [default=true]; - optional int32 F_Int32_defaulted = 41 [default=32]; - optional int64 F_Int64_defaulted = 42 [default=64]; - optional fixed32 F_Fixed32_defaulted = 43 [default=320]; - optional fixed64 F_Fixed64_defaulted = 44 [default=640]; - optional uint32 F_Uint32_defaulted = 45 [default=3200]; - optional uint64 F_Uint64_defaulted = 46 [default=6400]; - optional float F_Float_defaulted = 47 [default=314159.]; - optional double F_Double_defaulted = 48 [default=271828.]; - optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; - optional sint32 F_Sint32_defaulted = 402 [default = -32]; - optional sint64 F_Sint64_defaulted = 403 [default = -64]; - - // Packed repeated fields (no string or bytes). - repeated bool F_Bool_repeated_packed = 50 [packed=true]; - repeated int32 F_Int32_repeated_packed = 51 [packed=true]; - repeated int64 F_Int64_repeated_packed = 52 [packed=true]; - repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; - repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; - repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; - repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; - repeated float F_Float_repeated_packed = 57 [packed=true]; - repeated double F_Double_repeated_packed = 58 [packed=true]; - repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; - repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; - - // Required, repeated, and optional groups. - required group RequiredGroup = 70 { - required string RequiredField = 71; - }; - - repeated group RepeatedGroup = 80 { - required string RequiredField = 81; - }; - - optional group OptionalGroup = 90 { - required string RequiredField = 91; - }; -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -message GoSkipTest { - required int32 skip_int32 = 11; - required fixed32 skip_fixed32 = 12; - required fixed64 skip_fixed64 = 13; - required string skip_string = 14; - required group SkipGroup = 15 { - required int32 group_int32 = 16; - required string group_string = 17; - } -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -message NonPackedTest { - repeated int32 a = 1; -} - -message PackedTest { - repeated int32 b = 1 [packed=true]; -} - -message MaxTag { - // Maximum possible tag number. - optional string last_field = 536870911; -} - -message OldMessage { - message Nested { - optional string name = 1; - } - optional Nested nested = 1; - - optional int32 num = 2; -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -message NewMessage { - message Nested { - optional string name = 1; - optional string food_group = 2; - } - optional Nested nested = 1; - - // This is an int32 in OldMessage. - optional int64 num = 2; -} - -// Smaller tests for ASCII formatting. - -message InnerMessage { - required string host = 1; - optional int32 port = 2 [default=4000]; - optional bool connected = 3; -} - -message OtherMessage { - optional int64 key = 1; - optional bytes value = 2; - optional float weight = 3; - optional InnerMessage inner = 4; -} - -message MyMessage { - required int32 count = 1; - optional string name = 2; - optional string quote = 3; - repeated string pet = 4; - optional InnerMessage inner = 5; - repeated OtherMessage others = 6; - repeated InnerMessage rep_inner = 12; - - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color bikeshed = 7; - - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // This field becomes [][]byte in the generated code. - repeated bytes rep_bytes = 10; - - optional double bigfloat = 11; - - extensions 100 to max; -} - -message Ext { - extend MyMessage { - optional Ext more = 103; - optional string text = 104; - optional int32 number = 105; - } - - optional string data = 1; -} - -extend MyMessage { - repeated string greeting = 106; -} - -message MyMessageSet { - option message_set_wire_format = true; - extensions 100 to max; -} - -message Empty { -} - -extend MyMessageSet { - optional Empty x201 = 201; - optional Empty x202 = 202; - optional Empty x203 = 203; - optional Empty x204 = 204; - optional Empty x205 = 205; - optional Empty x206 = 206; - optional Empty x207 = 207; - optional Empty x208 = 208; - optional Empty x209 = 209; - optional Empty x210 = 210; - optional Empty x211 = 211; - optional Empty x212 = 212; - optional Empty x213 = 213; - optional Empty x214 = 214; - optional Empty x215 = 215; - optional Empty x216 = 216; - optional Empty x217 = 217; - optional Empty x218 = 218; - optional Empty x219 = 219; - optional Empty x220 = 220; - optional Empty x221 = 221; - optional Empty x222 = 222; - optional Empty x223 = 223; - optional Empty x224 = 224; - optional Empty x225 = 225; - optional Empty x226 = 226; - optional Empty x227 = 227; - optional Empty x228 = 228; - optional Empty x229 = 229; - optional Empty x230 = 230; - optional Empty x231 = 231; - optional Empty x232 = 232; - optional Empty x233 = 233; - optional Empty x234 = 234; - optional Empty x235 = 235; - optional Empty x236 = 236; - optional Empty x237 = 237; - optional Empty x238 = 238; - optional Empty x239 = 239; - optional Empty x240 = 240; - optional Empty x241 = 241; - optional Empty x242 = 242; - optional Empty x243 = 243; - optional Empty x244 = 244; - optional Empty x245 = 245; - optional Empty x246 = 246; - optional Empty x247 = 247; - optional Empty x248 = 248; - optional Empty x249 = 249; - optional Empty x250 = 250; -} - -message MessageList { - repeated group Message = 1 { - required string name = 2; - required int32 count = 3; - } -} - -message Strings { - optional string string_field = 1; - optional bytes bytes_field = 2; -} - -message Defaults { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - optional bool F_Bool = 1 [default=true]; - optional int32 F_Int32 = 2 [default=32]; - optional int64 F_Int64 = 3 [default=64]; - optional fixed32 F_Fixed32 = 4 [default=320]; - optional fixed64 F_Fixed64 = 5 [default=640]; - optional uint32 F_Uint32 = 6 [default=3200]; - optional uint64 F_Uint64 = 7 [default=6400]; - optional float F_Float = 8 [default=314159.]; - optional double F_Double = 9 [default=271828.]; - optional string F_String = 10 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes = 11 [default="Bignose"]; - optional sint32 F_Sint32 = 12 [default=-32]; - optional sint64 F_Sint64 = 13 [default=-64]; - optional Color F_Enum = 14 [default=GREEN]; - - // More fields with crazy defaults. - optional float F_Pinf = 15 [default=inf]; - optional float F_Ninf = 16 [default=-inf]; - optional float F_Nan = 17 [default=nan]; - - // Sub-message. - optional SubDefaults sub = 18; - - // Redundant but explicit defaults. - optional string str_zero = 19 [default=""]; -} - -message SubDefaults { - optional int64 n = 1 [default=7]; -} - -message RepeatedEnum { - enum Color { - RED = 1; - } - repeated Color color = 1; -} - -message MoreRepeated { - repeated bool bools = 1; - repeated bool bools_packed = 2 [packed=true]; - repeated int32 ints = 3; - repeated int32 ints_packed = 4 [packed=true]; - repeated int64 int64s_packed = 7 [packed=true]; - repeated string strings = 5; - repeated fixed32 fixeds = 6; -} - -// GroupOld and GroupNew have the same wire format. -// GroupNew has a new field inside a group. - -message GroupOld { - optional group G = 101 { - optional int32 x = 2; - } -} - -message GroupNew { - optional group G = 101 { - optional int32 x = 2; - optional int32 y = 3; - } -} - -message FloatingPoint { - required double f = 1; -} - -message MessageWithMap { - map name_mapping = 1; - map msg_mapping = 2; - map byte_mapping = 3; -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index e5ee8b92263..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,509 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - proto3pb "./proto3_proto" - . "./testdata" - . "github.com/golang/protobuf/proto" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0"`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:>` + - `byte_mapping:` - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 707bedd0006..00000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,436 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "./proto3_proto" - pb "./testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; current map format is the same as a repeated struct - { - &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}}, - `name_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/api/versions_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/api/versions_test.go deleted file mode 100644 index 82675703f29..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/api/versions_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package api - -import ( - "io" - "net/http" - "reflect" - "testing" - "time" - - "github.com/google/cadvisor/events" - info "github.com/google/cadvisor/info/v1" - "github.com/google/cadvisor/info/v2" - "github.com/stretchr/testify/assert" -) - -// returns an http.Request pointer for an input url test string -func makeHTTPRequest(requestURL string, t *testing.T) *http.Request { - dummyReader, _ := io.Pipe() - r, err := http.NewRequest("GET", requestURL, dummyReader) - assert.Nil(t, err) - return r -} - -func TestGetEventRequestBasicRequest(t *testing.T) { - r := makeHTTPRequest("http://localhost:8080/api/v1.3/events?oom_events=true&stream=false&max_events=20", t) - expectedQuery := events.NewRequest() - expectedQuery.EventType = map[info.EventType]bool{ - info.EventOom: true, - } - expectedQuery.MaxEventsReturned = 20 - - receivedQuery, stream, err := getEventRequest(r) - - if !reflect.DeepEqual(expectedQuery, receivedQuery) { - t.Errorf("expected %#v but received %#v", expectedQuery, receivedQuery) - } - assert.False(t, stream) - assert.Nil(t, err) -} - -func TestGetEventEmptyRequest(t *testing.T) { - r := makeHTTPRequest("", t) - expectedQuery := events.NewRequest() - - receivedQuery, stream, err := getEventRequest(r) - - if !reflect.DeepEqual(expectedQuery, receivedQuery) { - t.Errorf("expected %#v but received %#v", expectedQuery, receivedQuery) - } - assert.False(t, stream) - assert.Nil(t, err) -} - -func TestGetEventRequestDoubleArgument(t *testing.T) { - r := makeHTTPRequest("http://localhost:8080/api/v1.3/events?stream=true&oom_events=true&oom_events=false", t) - expectedQuery := events.NewRequest() - expectedQuery.EventType = map[info.EventType]bool{ - info.EventOom: true, - } - - receivedQuery, stream, err := getEventRequest(r) - - if !reflect.DeepEqual(expectedQuery, receivedQuery) { - t.Errorf("expected %#v but received %#v", expectedQuery, receivedQuery) - } - assert.True(t, stream) - assert.Nil(t, err) -} - -func TestInstCpuStats(t *testing.T) { - tests := []struct { - last *info.ContainerStats - cur *info.ContainerStats - want *v2.CpuInstStats - }{ - // Last is missing - { - nil, - &info.ContainerStats{}, - nil, - }, - // Goes back in time - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(time.Second), - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - }, - nil, - }, - // Zero time delta - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - }, - nil, - }, - // Unexpectedly small time delta - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(30 * time.Millisecond), - }, - nil, - }, - // Different number of cpus - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - PerCpu: []uint64{100, 200}, - }, - }, - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(time.Second), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - PerCpu: []uint64{100, 200, 300}, - }, - }, - }, - nil, - }, - // Stat numbers decrease - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 300, - PerCpu: []uint64{100, 200}, - User: 250, - System: 50, - }, - }, - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(time.Second), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 200, - PerCpu: []uint64{100, 100}, - User: 150, - System: 50, - }, - }, - }, - nil, - }, - // One second elapsed - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 300, - PerCpu: []uint64{100, 200}, - User: 250, - System: 50, - }, - }, - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(time.Second), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 500, - PerCpu: []uint64{200, 300}, - User: 400, - System: 100, - }, - }, - }, - &v2.CpuInstStats{ - Usage: v2.CpuInstUsage{ - Total: 200, - PerCpu: []uint64{100, 100}, - User: 150, - System: 50, - }, - }, - }, - // Two seconds elapsed - { - &info.ContainerStats{ - Timestamp: time.Unix(100, 0), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 300, - PerCpu: []uint64{100, 200}, - User: 250, - System: 50, - }, - }, - }, - &info.ContainerStats{ - Timestamp: time.Unix(100, 0).Add(2 * time.Second), - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 500, - PerCpu: []uint64{200, 300}, - User: 400, - System: 100, - }, - }, - }, - &v2.CpuInstStats{ - Usage: v2.CpuInstUsage{ - Total: 100, - PerCpu: []uint64{50, 50}, - User: 75, - System: 25, - }, - }, - }, - } - for _, c := range tests { - got, err := instCpuStats(c.last, c.cur) - if err != nil { - if c.want == nil { - continue - } - t.Errorf("Unexpected error: %v", err) - } - assert.Equal(t, c.want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/cache/memory/memory_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/cache/memory/memory_test.go deleted file mode 100644 index 2bf48425fd3..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/cache/memory/memory_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package memory - -import ( - "testing" - "time" - - info "github.com/google/cadvisor/info/v1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const containerName = "/container" - -var ( - containerRef = info.ContainerReference{Name: containerName} - zero time.Time -) - -// Make stats with the specified identifier. -func makeStat(i int) *info.ContainerStats { - return &info.ContainerStats{ - Timestamp: zero.Add(time.Duration(i) * time.Second), - Cpu: info.CpuStats{ - LoadAverage: int32(i), - }, - } -} - -func getRecentStats(t *testing.T, memoryCache *InMemoryCache, numStats int) []*info.ContainerStats { - stats, err := memoryCache.RecentStats(containerName, zero, zero, numStats) - require.Nil(t, err) - return stats -} - -func TestAddStats(t *testing.T) { - memoryCache := New(60*time.Second, nil) - - assert := assert.New(t) - assert.Nil(memoryCache.AddStats(containerRef, makeStat(0))) - assert.Nil(memoryCache.AddStats(containerRef, makeStat(1))) - assert.Nil(memoryCache.AddStats(containerRef, makeStat(2))) - assert.Nil(memoryCache.AddStats(containerRef, makeStat(0))) - containerRef2 := info.ContainerReference{ - Name: "/container2", - } - assert.Nil(memoryCache.AddStats(containerRef2, makeStat(0))) - assert.Nil(memoryCache.AddStats(containerRef2, makeStat(1))) -} - -func TestRecentStatsNoRecentStats(t *testing.T) { - memoryCache := makeWithStats(0) - - _, err := memoryCache.RecentStats(containerName, zero, zero, 60) - assert.NotNil(t, err) -} - -// Make an instance of InMemoryCache with n stats. -func makeWithStats(n int) *InMemoryCache { - memoryCache := New(60*time.Second, nil) - - for i := 0; i < n; i++ { - memoryCache.AddStats(containerRef, makeStat(i)) - } - return memoryCache -} - -func TestRecentStatsGetZeroStats(t *testing.T) { - memoryCache := makeWithStats(10) - - assert.Len(t, getRecentStats(t, memoryCache, 0), 0) -} - -func TestRecentStatsGetSomeStats(t *testing.T) { - memoryCache := makeWithStats(10) - - assert.Len(t, getRecentStats(t, memoryCache, 5), 5) -} - -func TestRecentStatsGetAllStats(t *testing.T) { - memoryCache := makeWithStats(10) - - assert.Len(t, getRecentStats(t, memoryCache, -1), 10) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/collector/collector_manager_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/collector/collector_manager_test.go deleted file mode 100644 index 056e85476da..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/collector/collector_manager_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package collector - -import ( - "testing" - "time" - - "github.com/google/cadvisor/info/v1" - "github.com/stretchr/testify/assert" -) - -type fakeCollector struct { - nextCollectionTime time.Time - err error - collectedFrom int -} - -func (fc *fakeCollector) Collect(metric map[string][]v1.MetricVal) (time.Time, map[string][]v1.MetricVal, error) { - fc.collectedFrom++ - return fc.nextCollectionTime, metric, fc.err -} - -func (fc *fakeCollector) Name() string { - return "fake-collector" -} - -func (fc *fakeCollector) GetSpec() []v1.MetricSpec { - return []v1.MetricSpec{} -} - -func TestCollect(t *testing.T) { - cm := &GenericCollectorManager{} - - firstTime := time.Now().Add(-time.Hour) - secondTime := time.Now().Add(time.Hour) - f1 := &fakeCollector{ - nextCollectionTime: firstTime, - } - f2 := &fakeCollector{ - nextCollectionTime: secondTime, - } - - assert := assert.New(t) - assert.NoError(cm.RegisterCollector(f1)) - assert.NoError(cm.RegisterCollector(f2)) - - // First collection, everyone gets collected from. - nextTime, _, err := cm.Collect() - assert.Equal(firstTime, nextTime) - assert.NoError(err) - assert.Equal(1, f1.collectedFrom) - assert.Equal(1, f2.collectedFrom) - - f1.nextCollectionTime = time.Now().Add(2 * time.Hour) - - // Second collection, only the one that is ready gets collected from. - nextTime, _, err = cm.Collect() - assert.Equal(secondTime, nextTime) - assert.NoError(err) - assert.Equal(2, f1.collectedFrom) - assert.Equal(1, f2.collectedFrom) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/collector/generic_collector_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/collector/generic_collector_test.go deleted file mode 100644 index 04e9ed01f9e..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/collector/generic_collector_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package collector - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "testing" - - "github.com/google/cadvisor/info/v1" - "github.com/stretchr/testify/assert" -) - -func TestEmptyConfig(t *testing.T) { - assert := assert.New(t) - - emptyConfig := ` - { - "endpoint" : "http://localhost:8000/nginx_status", - "metrics_config" : [ - ] - } - ` - - //Create a temporary config file 'temp.json' with invalid json format - assert.NoError(ioutil.WriteFile("temp.json", []byte(emptyConfig), 0777)) - - configFile, err := ioutil.ReadFile("temp.json") - assert.NoError(err) - - _, err = NewCollector("tempCollector", configFile) - assert.Error(err) - - assert.NoError(os.Remove("temp.json")) -} - -func TestConfigWithErrors(t *testing.T) { - assert := assert.New(t) - - //Syntax error: Missed '"' after activeConnections - invalid := ` - { - "endpoint" : "http://localhost:8000/nginx_status", - "metrics_config" : [ - { - "name" : "activeConnections, - "metric_type" : "gauge", - "data_type" : "int", - "polling_frequency" : 10, - "regex" : "Active connections: ([0-9]+)" - } - ] - } - ` - - //Create a temporary config file 'temp.json' with invalid json format - assert.NoError(ioutil.WriteFile("temp.json", []byte(invalid), 0777)) - configFile, err := ioutil.ReadFile("temp.json") - assert.NoError(err) - - _, err = NewCollector("tempCollector", configFile) - assert.Error(err) - - assert.NoError(os.Remove("temp.json")) -} - -func TestConfigWithRegexErrors(t *testing.T) { - assert := assert.New(t) - - //Error: Missed operand for '+' in activeConnections regex - invalid := ` - { - "endpoint" : "host:port/nginx_status", - "metrics_config" : [ - { - "name" : "activeConnections", - "metric_type" : "gauge", - "data_type" : "int", - "polling_frequency" : 10, - "regex" : "Active connections: (+)" - }, - { - "name" : "reading", - "metric_type" : "gauge", - "data_type" : "int", - "polling_frequency" : 10, - "regex" : "Reading: ([0-9]+) .*" - } - ] - } - ` - - //Create a temporary config file 'temp.json' - assert.NoError(ioutil.WriteFile("temp.json", []byte(invalid), 0777)) - - configFile, err := ioutil.ReadFile("temp.json") - assert.NoError(err) - - _, err = NewCollector("tempCollector", configFile) - assert.Error(err) - - assert.NoError(os.Remove("temp.json")) -} - -func TestConfig(t *testing.T) { - assert := assert.New(t) - - //Create an nginx collector using the config file 'sample_config.json' - configFile, err := ioutil.ReadFile("config/sample_config.json") - assert.NoError(err) - - collector, err := NewCollector("nginx", configFile) - assert.NoError(err) - assert.Equal(collector.name, "nginx") - assert.Equal(collector.configFile.Endpoint, "http://localhost:8000/nginx_status") - assert.Equal(collector.configFile.MetricsConfig[0].Name, "activeConnections") -} - -func TestMetricCollection(t *testing.T) { - assert := assert.New(t) - - //Collect nginx metrics from a fake nginx endpoint - configFile, err := ioutil.ReadFile("config/sample_config.json") - assert.NoError(err) - - fakeCollector, err := NewCollector("nginx", configFile) - assert.NoError(err) - - tempServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "Active connections: 3\nserver accepts handled requests") - fmt.Fprintln(w, "5 5 32\nReading: 0 Writing: 1 Waiting: 2") - })) - defer tempServer.Close() - fakeCollector.configFile.Endpoint = tempServer.URL - - metrics := map[string][]v1.MetricVal{} - _, metrics, errMetric := fakeCollector.Collect(metrics) - assert.NoError(errMetric) - metricNames := []string{"activeConnections", "reading", "writing", "waiting"} - // activeConnections = 3 - assert.Equal(metrics[metricNames[0]][0].IntValue, 3) - assert.Equal(metrics[metricNames[0]][0].FloatValue, 0) - // reading = 0 - assert.Equal(metrics[metricNames[1]][0].IntValue, 0) - assert.Equal(metrics[metricNames[1]][0].FloatValue, 0) - // writing = 1 - assert.Equal(metrics[metricNames[2]][0].IntValue, 1) - assert.Equal(metrics[metricNames[2]][0].FloatValue, 0) - // waiting = 2 - assert.Equal(metrics[metricNames[3]][0].IntValue, 2) - assert.Equal(metrics[metricNames[3]][0].FloatValue, 0) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/collector/prometheus_collector_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/collector/prometheus_collector_test.go deleted file mode 100644 index 0ead785d468..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/collector/prometheus_collector_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package collector - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/google/cadvisor/info/v1" - "github.com/stretchr/testify/assert" -) - -func TestPrometheus(t *testing.T) { - assert := assert.New(t) - - //Create a prometheus collector using the config file 'sample_config_prometheus.json' - configFile, err := ioutil.ReadFile("config/sample_config_prometheus.json") - collector, err := NewPrometheusCollector("Prometheus", configFile) - assert.NoError(err) - assert.Equal(collector.name, "Prometheus") - assert.Equal(collector.configFile.Endpoint, "http://localhost:8080/metrics") - - tempServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - - text := "# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n" - text += "# TYPE go_gc_duration_seconds summary\n" - text += "go_gc_duration_seconds{quantile=\"0\"} 5.8348000000000004e-05\n" - text += "go_gc_duration_seconds{quantile=\"1\"} 0.000499764\n" - text += "# HELP go_goroutines Number of goroutines that currently exist.\n" - text += "# TYPE go_goroutines gauge\n" - text += "go_goroutines 16" - fmt.Fprintln(w, text) - })) - - defer tempServer.Close() - - collector.configFile.Endpoint = tempServer.URL - metrics := map[string][]v1.MetricVal{} - _, metrics, errMetric := collector.Collect(metrics) - - assert.NoError(errMetric) - - go_gc_duration := metrics["go_gc_duration_seconds"] - assert.Equal(go_gc_duration[0].FloatValue, 5.8348000000000004e-05) - assert.Equal(go_gc_duration[1].FloatValue, 0.000499764) - - goRoutines := metrics["go_goroutines"] - assert.Equal(goRoutines[0].FloatValue, 16) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/container/factory_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/container/factory_test.go deleted file mode 100644 index 8c4bb0429d7..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/container/factory_test.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package container - -import ( - "testing" - - "github.com/stretchr/testify/mock" -) - -type mockContainerHandlerFactory struct { - mock.Mock - Name string - CanHandleValue bool - CanAcceptValue bool -} - -func (self *mockContainerHandlerFactory) String() string { - return self.Name -} - -func (self *mockContainerHandlerFactory) DebugInfo() map[string][]string { - return map[string][]string{} -} - -func (self *mockContainerHandlerFactory) CanHandleAndAccept(name string) (bool, bool, error) { - return self.CanHandleValue, self.CanAcceptValue, nil -} - -func (self *mockContainerHandlerFactory) NewContainerHandler(name string, isHostNamespace bool) (ContainerHandler, error) { - args := self.Called(name) - return args.Get(0).(ContainerHandler), args.Error(1) -} - -const testContainerName = "/test" - -var mockFactory FactoryForMockContainerHandler - -func TestNewContainerHandler_FirstMatches(t *testing.T) { - ClearContainerHandlerFactories() - - // Register one allways yes factory. - allwaysYes := &mockContainerHandlerFactory{ - Name: "yes", - CanHandleValue: true, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(allwaysYes) - - // The yes factory should be asked to create the ContainerHandler. - mockContainer, err := mockFactory.NewContainerHandler(testContainerName, true) - if err != nil { - t.Error(err) - } - allwaysYes.On("NewContainerHandler", testContainerName).Return(mockContainer, nil) - - cont, _, err := NewContainerHandler(testContainerName, true) - if err != nil { - t.Error(err) - } - if cont == nil { - t.Error("Expected container to not be nil") - } -} - -func TestNewContainerHandler_SecondMatches(t *testing.T) { - ClearContainerHandlerFactories() - - // Register one allways no and one always yes factory. - allwaysNo := &mockContainerHandlerFactory{ - Name: "no", - CanHandleValue: false, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(allwaysNo) - allwaysYes := &mockContainerHandlerFactory{ - Name: "yes", - CanHandleValue: true, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(allwaysYes) - - // The yes factory should be asked to create the ContainerHandler. - mockContainer, err := mockFactory.NewContainerHandler(testContainerName, true) - if err != nil { - t.Error(err) - } - allwaysYes.On("NewContainerHandler", testContainerName).Return(mockContainer, nil) - - cont, _, err := NewContainerHandler(testContainerName, true) - if err != nil { - t.Error(err) - } - if cont == nil { - t.Error("Expected container to not be nil") - } -} - -func TestNewContainerHandler_NoneMatch(t *testing.T) { - ClearContainerHandlerFactories() - - // Register two allways no factories. - allwaysNo1 := &mockContainerHandlerFactory{ - Name: "no", - CanHandleValue: false, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(allwaysNo1) - allwaysNo2 := &mockContainerHandlerFactory{ - Name: "no", - CanHandleValue: false, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(allwaysNo2) - - _, _, err := NewContainerHandler(testContainerName, true) - if err == nil { - t.Error("Expected NewContainerHandler to fail") - } -} - -func TestNewContainerHandler_Accept(t *testing.T) { - ClearContainerHandlerFactories() - - // Register handler that can handle the container, but can't accept it. - cannotHandle := &mockContainerHandlerFactory{ - Name: "no", - CanHandleValue: false, - CanAcceptValue: true, - } - RegisterContainerHandlerFactory(cannotHandle) - cannotAccept := &mockContainerHandlerFactory{ - Name: "no", - CanHandleValue: true, - CanAcceptValue: false, - } - RegisterContainerHandlerFactory(cannotAccept) - - _, accept, err := NewContainerHandler(testContainerName, true) - if err != nil { - t.Error("Expected NewContainerHandler to succeed") - } - if accept == true { - t.Error("Expected NewContainerHandler to ignore the container.") - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/container/raw/container_hints_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/container/raw/container_hints_test.go deleted file mode 100644 index 83d32e74086..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/container/raw/container_hints_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package raw - -import ( - "testing" -) - -func TestGetContainerHintsFromFile(t *testing.T) { - cHints, err := getContainerHintsFromFile("test_resources/container_hints.json") - - if err != nil { - t.Fatalf("Error in unmarshalling: %s", err) - } - - if cHints.AllHosts[0].NetworkInterface.VethHost != "veth24031eth1" && - cHints.AllHosts[0].NetworkInterface.VethChild != "eth1" { - t.Errorf("Cannot find network interface in %s", cHints) - } - - correctMountDirs := [...]string{ - "/var/run/nm-sdc1", - "/var/run/nm-sdb3", - "/var/run/nm-sda3", - "/var/run/netns/root", - "/var/run/openvswitch/db.sock", - } - - if len(cHints.AllHosts[0].Mounts) == 0 { - t.Errorf("Cannot find any mounts") - } - - for i, mountDir := range cHints.AllHosts[0].Mounts { - if correctMountDirs[i] != mountDir.HostDir { - t.Errorf("Cannot find mount %s in %s", mountDir.HostDir, cHints) - } - } -} - -func TestFileNotExist(t *testing.T) { - _, err := getContainerHintsFromFile("/file_does_not_exist.json") - if err != nil { - t.Fatalf("getContainerHintsFromFile must not error for blank file: %s", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/events/handler_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/events/handler_test.go deleted file mode 100644 index abda4cbcff0..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/events/handler_test.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package events - -import ( - "testing" - "time" - - info "github.com/google/cadvisor/info/v1" - "github.com/stretchr/testify/assert" -) - -func createOldTime(t *testing.T) time.Time { - const longForm = "Jan 2, 2006 at 3:04pm (MST)" - linetime, err := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)") - if err != nil { - t.Fatalf("could not format time.Time object") - } else { - return linetime - } - return time.Now() -} - -// used to convert an OomInstance to an Event object -func makeEvent(inTime time.Time, containerName string) *info.Event { - return &info.Event{ - ContainerName: containerName, - Timestamp: inTime, - EventType: info.EventOom, - } -} - -// returns EventManager and Request to use in tests -func initializeScenario(t *testing.T) (*events, *Request, *info.Event, *info.Event) { - fakeEvent := makeEvent(createOldTime(t), "/") - fakeEvent2 := makeEvent(time.Now(), "/") - - return NewEventManager(DefaultStoragePolicy()), NewRequest(), fakeEvent, fakeEvent2 -} - -func checkNumberOfEvents(t *testing.T, numEventsExpected int, numEventsReceived int) { - if numEventsReceived != numEventsExpected { - t.Fatalf("Expected to return %v events but received %v", - numEventsExpected, numEventsReceived) - } -} - -func ensureProperEventReturned(t *testing.T, expectedEvent *info.Event, eventObjectFound *info.Event) { - if eventObjectFound != expectedEvent { - t.Errorf("Expected to find test object %v but found a different object: %v", - expectedEvent, eventObjectFound) - } -} - -func TestCheckIfIsSubcontainer(t *testing.T) { - myRequest := NewRequest() - myRequest.ContainerName = "/root" - rootRequest := NewRequest() - rootRequest.ContainerName = "/" - - sameContainerEvent := &info.Event{ - ContainerName: "/root", - } - subContainerEvent := &info.Event{ - ContainerName: "/root/subdir", - } - differentContainerEvent := &info.Event{ - ContainerName: "/root-completely-different-container", - } - - if checkIfIsSubcontainer(rootRequest, sameContainerEvent) { - t.Errorf("should not have found %v to be a subcontainer of %v", - sameContainerEvent, rootRequest) - } - if !checkIfIsSubcontainer(myRequest, sameContainerEvent) { - t.Errorf("should have found %v and %v had the same container name", - myRequest, sameContainerEvent) - } - if checkIfIsSubcontainer(myRequest, subContainerEvent) { - t.Errorf("should have found %v and %v had different containers", - myRequest, subContainerEvent) - } - - rootRequest.IncludeSubcontainers = true - myRequest.IncludeSubcontainers = true - - if !checkIfIsSubcontainer(rootRequest, sameContainerEvent) { - t.Errorf("should have found %v to be a subcontainer of %v", - sameContainerEvent.ContainerName, rootRequest.ContainerName) - } - if !checkIfIsSubcontainer(myRequest, sameContainerEvent) { - t.Errorf("should have found %v and %v had the same container", - myRequest.ContainerName, sameContainerEvent.ContainerName) - } - if !checkIfIsSubcontainer(myRequest, subContainerEvent) { - t.Errorf("should have found %v was a subcontainer of %v", - subContainerEvent.ContainerName, myRequest.ContainerName) - } - if checkIfIsSubcontainer(myRequest, differentContainerEvent) { - t.Errorf("should have found %v and %v had different containers", - myRequest.ContainerName, differentContainerEvent.ContainerName) - } -} - -func TestWatchEventsDetectsNewEvents(t *testing.T) { - myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) - myRequest.EventType[info.EventOom] = true - returnEventChannel, err := myEventHolder.WatchEvents(myRequest) - assert.Nil(t, err) - - myEventHolder.AddEvent(fakeEvent) - myEventHolder.AddEvent(fakeEvent2) - - startTime := time.Now() - go func() { - time.Sleep(5 * time.Second) - if time.Since(startTime) > (5 * time.Second) { - t.Errorf("Took too long to receive all the events") - } - }() - - eventsFound := 0 - go func() { - for event := range returnEventChannel.GetChannel() { - eventsFound += 1 - if eventsFound == 1 { - ensureProperEventReturned(t, fakeEvent, event) - } else if eventsFound == 2 { - ensureProperEventReturned(t, fakeEvent2, event) - break - } - } - }() -} - -func TestAddEventAddsEventsToEventManager(t *testing.T) { - myEventHolder, _, fakeEvent, _ := initializeScenario(t) - - myEventHolder.AddEvent(fakeEvent) - - checkNumberOfEvents(t, 1, len(myEventHolder.eventStore)) - ensureProperEventReturned(t, fakeEvent, myEventHolder.eventStore[info.EventOom].Get(0).(*info.Event)) -} - -func TestGetEventsForOneEvent(t *testing.T) { - myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) - myRequest.MaxEventsReturned = 1 - myRequest.EventType[info.EventOom] = true - - myEventHolder.AddEvent(fakeEvent) - myEventHolder.AddEvent(fakeEvent2) - - receivedEvents, err := myEventHolder.GetEvents(myRequest) - assert.Nil(t, err) - checkNumberOfEvents(t, 1, len(receivedEvents)) - ensureProperEventReturned(t, fakeEvent2, receivedEvents[0]) -} - -func TestGetEventsForTimePeriod(t *testing.T) { - myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) - myRequest.StartTime = time.Now().Add(-1 * time.Second * 10) - myRequest.EndTime = time.Now().Add(time.Second * 10) - myRequest.EventType[info.EventOom] = true - - myEventHolder.AddEvent(fakeEvent) - myEventHolder.AddEvent(fakeEvent2) - - receivedEvents, err := myEventHolder.GetEvents(myRequest) - assert.Nil(t, err) - - checkNumberOfEvents(t, 1, len(receivedEvents)) - ensureProperEventReturned(t, fakeEvent2, receivedEvents[0]) -} - -func TestGetEventsForNoTypeRequested(t *testing.T) { - myEventHolder, myRequest, fakeEvent, fakeEvent2 := initializeScenario(t) - - myEventHolder.AddEvent(fakeEvent) - myEventHolder.AddEvent(fakeEvent2) - - receivedEvents, err := myEventHolder.GetEvents(myRequest) - assert.Nil(t, err) - checkNumberOfEvents(t, 0, len(receivedEvents)) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/fs/fs_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/fs/fs_test.go deleted file mode 100644 index 2071f02d16b..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/fs/fs_test.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fs - -import ( - "testing" -) - -func TestGetDiskStatsMap(t *testing.T) { - diskStatsMap, err := getDiskStatsMap("test_resources/diskstats") - if err != nil { - t.Errorf("Error calling getDiskStatMap %s", err) - } - if len(diskStatsMap) != 30 { - t.Errorf("diskStatsMap %+v not valid", diskStatsMap) - } - keySet := map[string]string{ - "/dev/sda": "/dev/sda", - "/dev/sdb": "/dev/sdb", - "/dev/sdc": "/dev/sdc", - "/dev/sdd": "/dev/sdd", - "/dev/sde": "/dev/sde", - "/dev/sdf": "/dev/sdf", - "/dev/sdg": "/dev/sdg", - "/dev/sdh": "/dev/sdh", - "/dev/sdb1": "/dev/sdb1", - "/dev/sdb2": "/dev/sdb2", - "/dev/sda1": "/dev/sda1", - "/dev/sda2": "/dev/sda2", - "/dev/sdc1": "/dev/sdc1", - "/dev/sdc2": "/dev/sdc2", - "/dev/sdc3": "/dev/sdc3", - "/dev/sdc4": "/dev/sdc4", - "/dev/sdd1": "/dev/sdd1", - "/dev/sdd2": "/dev/sdd2", - "/dev/sdd3": "/dev/sdd3", - "/dev/sdd4": "/dev/sdd4", - "/dev/sde1": "/dev/sde1", - "/dev/sde2": "/dev/sde2", - "/dev/sdf1": "/dev/sdf1", - "/dev/sdf2": "/dev/sdf2", - "/dev/sdg1": "/dev/sdg1", - "/dev/sdg2": "/dev/sdg2", - "/dev/sdh1": "/dev/sdh1", - "/dev/sdh2": "/dev/sdh2", - "/dev/dm-0": "/dev/dm-0", - "/dev/dm-1": "/dev/dm-1", - } - - for device := range diskStatsMap { - if _, ok := keySet[device]; !ok { - t.Errorf("Cannot find device %s", device) - } - delete(keySet, device) - } - if len(keySet) != 0 { - t.Errorf("diskStatsMap %+v contains illegal keys %+v", diskStatsMap, keySet) - } -} - -func TestFileNotExist(t *testing.T) { - _, err := getDiskStatsMap("/file_does_not_exist") - if err != nil { - t.Fatalf("getDiskStatsMap must not error for absent file: %s", err) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go deleted file mode 100644 index 58dc79e3932..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/info/v1/container_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package v1 - -import ( - "testing" - "time" -) - -func TestStatsStartTime(t *testing.T) { - N := 10 - stats := make([]*ContainerStats, 0, N) - ct := time.Now() - for i := 0; i < N; i++ { - s := &ContainerStats{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - } - stats = append(stats, s) - } - cinfo := &ContainerInfo{ - ContainerReference: ContainerReference{ - Name: "/some/container", - }, - Stats: stats, - } - ref := ct.Add(time.Duration(N-1) * time.Second) - end := cinfo.StatsEndTime() - - if !ref.Equal(end) { - t.Errorf("end time is %v; should be %v", end, ref) - } -} - -func TestStatsEndTime(t *testing.T) { - N := 10 - stats := make([]*ContainerStats, 0, N) - ct := time.Now() - for i := 0; i < N; i++ { - s := &ContainerStats{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - } - stats = append(stats, s) - } - cinfo := &ContainerInfo{ - ContainerReference: ContainerReference{ - Name: "/some/container", - }, - Stats: stats, - } - ref := ct - start := cinfo.StatsStartTime() - - if !ref.Equal(start) { - t.Errorf("start time is %v; should be %v", start, ref) - } -} - -func createStats(cpuUsage, memUsage uint64, timestamp time.Time) *ContainerStats { - stats := &ContainerStats{} - stats.Cpu.Usage.PerCpu = []uint64{cpuUsage} - stats.Cpu.Usage.Total = cpuUsage - stats.Cpu.Usage.System = 0 - stats.Cpu.Usage.User = cpuUsage - stats.Memory.Usage = memUsage - stats.Timestamp = timestamp - return stats -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/manager/container_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/manager/container_test.go deleted file mode 100644 index c5bcabc6b74..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/manager/container_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Per-container manager. - -package manager - -import ( - "fmt" - "reflect" - "testing" - "time" - - "github.com/google/cadvisor/cache/memory" - "github.com/google/cadvisor/collector" - "github.com/google/cadvisor/container" - info "github.com/google/cadvisor/info/v1" - itest "github.com/google/cadvisor/info/v1/test" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const containerName = "/container" - -// Create a containerData instance for a test. -func setupContainerData(t *testing.T, spec info.ContainerSpec) (*containerData, *container.MockContainerHandler, *memory.InMemoryCache) { - mockHandler := container.NewMockContainerHandler(containerName) - mockHandler.On("GetSpec").Return( - spec, - nil, - ) - memoryCache := memory.New(60, nil) - ret, err := newContainerData(containerName, memoryCache, mockHandler, nil, false, &collector.GenericCollectorManager{}, 60*time.Second, true) - if err != nil { - t.Fatal(err) - } - return ret, mockHandler, memoryCache -} - -// Create a containerData instance for a test and add a default GetSpec mock. -func newTestContainerData(t *testing.T) (*containerData, *container.MockContainerHandler, *memory.InMemoryCache) { - spec := itest.GenerateRandomContainerSpec(4) - ret, mockHandler, memoryCache := setupContainerData(t, spec) - return ret, mockHandler, memoryCache -} - -func TestUpdateSubcontainers(t *testing.T) { - subcontainers := []info.ContainerReference{ - {Name: "/container/ee0103"}, - {Name: "/container/abcd"}, - {Name: "/container/something"}, - } - cd, mockHandler, _ := newTestContainerData(t) - mockHandler.On("ListContainers", container.ListSelf).Return( - subcontainers, - nil, - ) - - err := cd.updateSubcontainers() - if err != nil { - t.Fatal(err) - } - - if len(cd.info.Subcontainers) != len(subcontainers) { - t.Errorf("Received %v subcontainers, should be %v", len(cd.info.Subcontainers), len(subcontainers)) - } - - for _, sub := range cd.info.Subcontainers { - found := false - for _, sub2 := range subcontainers { - if sub.Name == sub2.Name { - found = true - } - } - if !found { - t.Errorf("Received unknown sub container %v", sub) - } - } - - mockHandler.AssertExpectations(t) -} - -func TestUpdateSubcontainersWithError(t *testing.T) { - cd, mockHandler, _ := newTestContainerData(t) - mockHandler.On("ListContainers", container.ListSelf).Return( - []info.ContainerReference{}, - fmt.Errorf("some error"), - ) - mockHandler.On("Exists").Return(true) - - assert.NotNil(t, cd.updateSubcontainers()) - assert.Empty(t, cd.info.Subcontainers, "subcontainers should not be populated on failure") - mockHandler.AssertExpectations(t) -} - -func TestUpdateSubcontainersWithErrorOnDeadContainer(t *testing.T) { - cd, mockHandler, _ := newTestContainerData(t) - mockHandler.On("ListContainers", container.ListSelf).Return( - []info.ContainerReference{}, - fmt.Errorf("some error"), - ) - mockHandler.On("Exists").Return(false) - - assert.Nil(t, cd.updateSubcontainers()) - mockHandler.AssertExpectations(t) -} - -func checkNumStats(t *testing.T, memoryCache *memory.InMemoryCache, numStats int) { - var empty time.Time - stats, err := memoryCache.RecentStats(containerName, empty, empty, -1) - require.Nil(t, err) - assert.Len(t, stats, numStats) -} - -func TestUpdateStats(t *testing.T) { - statsList := itest.GenerateRandomStats(1, 4, 1*time.Second) - stats := statsList[0] - - cd, mockHandler, memoryCache := newTestContainerData(t) - mockHandler.On("GetStats").Return( - stats, - nil, - ) - - err := cd.updateStats() - if err != nil { - t.Fatal(err) - } - - checkNumStats(t, memoryCache, 1) - mockHandler.AssertExpectations(t) -} - -func TestUpdateSpec(t *testing.T) { - spec := itest.GenerateRandomContainerSpec(4) - cd, mockHandler, _ := newTestContainerData(t) - mockHandler.On("GetSpec").Return( - spec, - nil, - ) - - err := cd.updateSpec() - if err != nil { - t.Fatal(err) - } - - mockHandler.AssertExpectations(t) -} - -func TestGetInfo(t *testing.T) { - spec := itest.GenerateRandomContainerSpec(4) - subcontainers := []info.ContainerReference{ - {Name: "/container/ee0103"}, - {Name: "/container/abcd"}, - {Name: "/container/something"}, - } - cd, mockHandler, _ := setupContainerData(t, spec) - mockHandler.On("ListContainers", container.ListSelf).Return( - subcontainers, - nil, - ) - mockHandler.Aliases = []string{"a1", "a2"} - - info, err := cd.GetInfo() - if err != nil { - t.Fatal(err) - } - - mockHandler.AssertExpectations(t) - - if len(info.Subcontainers) != len(subcontainers) { - t.Errorf("Received %v subcontainers, should be %v", len(info.Subcontainers), len(subcontainers)) - } - - for _, sub := range info.Subcontainers { - found := false - for _, sub2 := range subcontainers { - if sub.Name == sub2.Name { - found = true - } - } - if !found { - t.Errorf("Received unknown sub container %v", sub) - } - } - - if !reflect.DeepEqual(spec, info.Spec) { - t.Errorf("received wrong container spec") - } - - if info.Name != mockHandler.Name { - t.Errorf("received wrong container name: received %v; should be %v", info.Name, mockHandler.Name) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/manager/manager_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/manager/manager_test.go deleted file mode 100644 index b1600b88aa1..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/manager/manager_test.go +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Per-container manager. - -package manager - -import ( - "reflect" - "strings" - "testing" - "time" - - "github.com/google/cadvisor/cache/memory" - "github.com/google/cadvisor/collector" - "github.com/google/cadvisor/container" - "github.com/google/cadvisor/container/docker" - info "github.com/google/cadvisor/info/v1" - itest "github.com/google/cadvisor/info/v1/test" - "github.com/google/cadvisor/utils/sysfs/fakesysfs" -) - -// TODO(vmarmol): Refactor these tests. - -func createManagerAndAddContainers( - memoryCache *memory.InMemoryCache, - sysfs *fakesysfs.FakeSysFs, - containers []string, - f func(*container.MockContainerHandler), - t *testing.T, -) *manager { - container.ClearContainerHandlerFactories() - mif := &manager{ - containers: make(map[namespacedContainerName]*containerData), - quitChannels: make([]chan error, 0, 2), - memoryCache: memoryCache, - } - for _, name := range containers { - mockHandler := container.NewMockContainerHandler(name) - spec := itest.GenerateRandomContainerSpec(4) - mockHandler.On("GetSpec").Return( - spec, - nil, - ).Once() - cont, err := newContainerData(name, memoryCache, mockHandler, nil, false, &collector.GenericCollectorManager{}, 60*time.Second, true) - if err != nil { - t.Fatal(err) - } - mif.containers[namespacedContainerName{ - Name: name, - }] = cont - // Add Docker containers under their namespace. - if strings.HasPrefix(name, "/docker") { - mif.containers[namespacedContainerName{ - Namespace: docker.DockerNamespace, - Name: strings.TrimPrefix(name, "/docker/"), - }] = cont - } - f(mockHandler) - } - return mif -} - -// Expect a manager with the specified containers and query. Returns the manager, map of ContainerInfo objects, -// and map of MockContainerHandler objects.} -func expectManagerWithContainers(containers []string, query *info.ContainerInfoRequest, t *testing.T) (*manager, map[string]*info.ContainerInfo, map[string]*container.MockContainerHandler) { - infosMap := make(map[string]*info.ContainerInfo, len(containers)) - handlerMap := make(map[string]*container.MockContainerHandler, len(containers)) - - for _, container := range containers { - infosMap[container] = itest.GenerateRandomContainerInfo(container, 4, query, 1*time.Second) - } - - memoryCache := memory.New(time.Duration(query.NumStats)*time.Second, nil) - sysfs := &fakesysfs.FakeSysFs{} - m := createManagerAndAddContainers( - memoryCache, - sysfs, - containers, - func(h *container.MockContainerHandler) { - cinfo := infosMap[h.Name] - ref, err := h.ContainerReference() - if err != nil { - t.Error(err) - } - for _, stat := range cinfo.Stats { - err = memoryCache.AddStats(ref, stat) - if err != nil { - t.Error(err) - } - } - spec := cinfo.Spec - - h.On("ListContainers", container.ListSelf).Return( - []info.ContainerReference(nil), - nil, - ) - h.On("GetSpec").Return( - spec, - nil, - ) - handlerMap[h.Name] = h - }, - t, - ) - - return m, infosMap, handlerMap -} - -func TestGetContainerInfo(t *testing.T) { - containers := []string{ - "/c1", - "/c2", - } - - query := &info.ContainerInfoRequest{ - NumStats: 256, - } - - m, infosMap, handlerMap := expectManagerWithContainers(containers, query, t) - - returnedInfos := make(map[string]*info.ContainerInfo, len(containers)) - - for _, container := range containers { - cinfo, err := m.GetContainerInfo(container, query) - if err != nil { - t.Fatalf("Unable to get info for container %v: %v", container, err) - } - returnedInfos[container] = cinfo - } - - for container, handler := range handlerMap { - handler.AssertExpectations(t) - returned := returnedInfos[container] - expected := infosMap[container] - if !reflect.DeepEqual(returned, expected) { - t.Errorf("returned unexpected info for container %v; returned %+v; expected %+v", container, returned, expected) - } - } - -} - -func TestSubcontainersInfo(t *testing.T) { - containers := []string{ - "/c1", - "/c2", - } - - query := &info.ContainerInfoRequest{ - NumStats: 64, - } - - m, _, _ := expectManagerWithContainers(containers, query, t) - - result, err := m.SubcontainersInfo("/", query) - if err != nil { - t.Fatalf("expected to succeed: %s", err) - } - if len(result) != len(containers) { - t.Errorf("expected to received containers: %v, but received: %v", containers, result) - } - for _, res := range result { - found := false - for _, name := range containers { - if res.Name == name { - found = true - break - } - } - if !found { - t.Errorf("unexpected container %q in result, expected one of %v", res.Name, containers) - } - } -} - -func TestDockerContainersInfo(t *testing.T) { - containers := []string{ - "/docker/c1", - } - - query := &info.ContainerInfoRequest{ - NumStats: 2, - } - - m, _, _ := expectManagerWithContainers(containers, query, t) - - result, err := m.DockerContainer("c1", query) - if err != nil { - t.Fatalf("expected to succeed: %s", err) - } - if result.Name != containers[0] { - t.Errorf("Unexpected container %q in result. Expected container %q", result.Name, containers[0]) - } -} - -func TestNewNilManager(t *testing.T) { - _, err := New(nil, nil, 60*time.Second, true) - if err == nil { - t.Fatalf("Expected nil manager to return error") - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/metrics/prometheus_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/metrics/prometheus_test.go deleted file mode 100644 index 0bb6c5e1c87..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/metrics/prometheus_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metrics - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "regexp" - "strings" - "testing" - - info "github.com/google/cadvisor/info/v1" - "github.com/prometheus/client_golang/prometheus" -) - -type testSubcontainersInfoProvider struct{} - -func (p testSubcontainersInfoProvider) SubcontainersInfo(string, *info.ContainerInfoRequest) ([]*info.ContainerInfo, error) { - return []*info.ContainerInfo{ - { - ContainerReference: info.ContainerReference{ - Name: "testcontainer", - }, - Spec: info.ContainerSpec{ - Image: "test", - }, - Stats: []*info.ContainerStats{ - { - Cpu: info.CpuStats{ - Usage: info.CpuUsage{ - Total: 1, - PerCpu: []uint64{2, 3, 4, 5}, - User: 6, - System: 7, - }, - }, - Memory: info.MemoryStats{ - Usage: 8, - WorkingSet: 9, - ContainerData: info.MemoryStatsMemoryData{ - Pgfault: 10, - Pgmajfault: 11, - }, - HierarchicalData: info.MemoryStatsMemoryData{ - Pgfault: 12, - Pgmajfault: 13, - }, - }, - Network: info.NetworkStats{ - InterfaceStats: info.InterfaceStats{ - Name: "eth0", - RxBytes: 14, - RxPackets: 15, - RxErrors: 16, - RxDropped: 17, - TxBytes: 18, - TxPackets: 19, - TxErrors: 20, - TxDropped: 21, - }, - Interfaces: []info.InterfaceStats{ - { - Name: "eth0", - RxBytes: 14, - RxPackets: 15, - RxErrors: 16, - RxDropped: 17, - TxBytes: 18, - TxPackets: 19, - TxErrors: 20, - TxDropped: 21, - }, - }, - }, - Filesystem: []info.FsStats{ - { - Device: "sda1", - Limit: 22, - Usage: 23, - ReadsCompleted: 24, - ReadsMerged: 25, - SectorsRead: 26, - ReadTime: 27, - WritesCompleted: 28, - WritesMerged: 39, - SectorsWritten: 40, - WriteTime: 41, - IoInProgress: 42, - IoTime: 43, - WeightedIoTime: 44, - }, - { - Device: "sda2", - Limit: 37, - Usage: 38, - ReadsCompleted: 39, - ReadsMerged: 40, - SectorsRead: 41, - ReadTime: 42, - WritesCompleted: 43, - WritesMerged: 44, - SectorsWritten: 45, - WriteTime: 46, - IoInProgress: 47, - IoTime: 48, - WeightedIoTime: 49, - }, - }, - TaskStats: info.LoadStats{ - NrSleeping: 50, - NrRunning: 51, - NrStopped: 52, - NrUninterruptible: 53, - NrIoWait: 54, - }, - }, - }, - }, - }, nil -} - -func TestPrometheusCollector(t *testing.T) { - prometheus.MustRegister(NewPrometheusCollector(testSubcontainersInfoProvider{})) - - rw := httptest.NewRecorder() - prometheus.Handler().ServeHTTP(rw, &http.Request{}) - - metricsFile := "testdata/prometheus_metrics" - wantMetrics, err := ioutil.ReadFile(metricsFile) - if err != nil { - t.Fatalf("unable to read input test file %s", metricsFile) - } - - wantLines := strings.Split(string(wantMetrics), "\n") - gotLines := strings.Split(string(rw.Body.String()), "\n") - - // Until the Prometheus Go client library offers better testability - // (https://github.com/prometheus/client_golang/issues/58), we simply compare - // verbatim text-format metrics outputs, but ignore certain metric lines - // whose value depends on the current time or local circumstances. - includeRe := regexp.MustCompile("^(# HELP |# TYPE |)container_") - ignoreRe := regexp.MustCompile("^container_last_seen{") - for i, want := range wantLines { - if !includeRe.MatchString(want) || ignoreRe.MatchString(want) { - continue - } - if want != gotLines[i] { - t.Fatalf("want %s, got %s", want, gotLines[i]) - } - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/metrics/testdata/prometheus_metrics b/Godeps/_workspace/src/github.com/google/cadvisor/metrics/testdata/prometheus_metrics deleted file mode 100644 index 5e7de5efda8..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/metrics/testdata/prometheus_metrics +++ /dev/null @@ -1,155 +0,0 @@ -# HELP container_cpu_system_seconds_total Cumulative system cpu time consumed in seconds. -# TYPE container_cpu_system_seconds_total counter -container_cpu_system_seconds_total{id="testcontainer",image="test",name="testcontainer"} 7e-09 -# HELP container_cpu_usage_seconds_total Cumulative cpu time consumed per cpu in seconds. -# TYPE container_cpu_usage_seconds_total counter -container_cpu_usage_seconds_total{cpu="cpu00",id="testcontainer",image="test",name="testcontainer"} 2e-09 -container_cpu_usage_seconds_total{cpu="cpu01",id="testcontainer",image="test",name="testcontainer"} 3e-09 -container_cpu_usage_seconds_total{cpu="cpu02",id="testcontainer",image="test",name="testcontainer"} 4e-09 -container_cpu_usage_seconds_total{cpu="cpu03",id="testcontainer",image="test",name="testcontainer"} 5e-09 -# HELP container_cpu_user_seconds_total Cumulative user cpu time consumed in seconds. -# TYPE container_cpu_user_seconds_total counter -container_cpu_user_seconds_total{id="testcontainer",image="test",name="testcontainer"} 6e-09 -# HELP container_fs_io_current Number of I/Os currently in progress -# TYPE container_fs_io_current gauge -container_fs_io_current{device="sda1",id="testcontainer",image="test",name="testcontainer"} 42 -container_fs_io_current{device="sda2",id="testcontainer",image="test",name="testcontainer"} 47 -# HELP container_fs_io_time_seconds_total Cumulative count of seconds spent doing I/Os -# TYPE container_fs_io_time_seconds_total counter -container_fs_io_time_seconds_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 4.3e-08 -container_fs_io_time_seconds_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 4.8e-08 -# HELP container_fs_io_time_weighted_seconds_total Cumulative weighted I/O time in seconds -# TYPE container_fs_io_time_weighted_seconds_total counter -container_fs_io_time_weighted_seconds_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 4.4e-08 -container_fs_io_time_weighted_seconds_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 4.9e-08 -# HELP container_fs_limit_bytes Number of bytes that can be consumed by the container on this filesystem. -# TYPE container_fs_limit_bytes gauge -container_fs_limit_bytes{device="sda1",id="testcontainer",image="test",name="testcontainer"} 22 -container_fs_limit_bytes{device="sda2",id="testcontainer",image="test",name="testcontainer"} 37 -# HELP container_fs_read_seconds_total Cumulative count of seconds spent reading -# TYPE container_fs_read_seconds_total counter -container_fs_read_seconds_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 2.7e-08 -container_fs_read_seconds_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 4.2e-08 -# HELP container_fs_reads_merged_total Cumulative count of reads merged -# TYPE container_fs_reads_merged_total counter -container_fs_reads_merged_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 25 -container_fs_reads_merged_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 40 -# HELP container_fs_reads_total Cumulative count of reads completed -# TYPE container_fs_reads_total counter -container_fs_reads_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 24 -container_fs_reads_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 39 -# HELP container_fs_sector_reads_total Cumulative count of sector reads completed -# TYPE container_fs_sector_reads_total counter -container_fs_sector_reads_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 26 -container_fs_sector_reads_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 41 -# HELP container_fs_sector_writes_total Cumulative count of sector writes completed -# TYPE container_fs_sector_writes_total counter -container_fs_sector_writes_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 40 -container_fs_sector_writes_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 45 -# HELP container_fs_usage_bytes Number of bytes that are consumed by the container on this filesystem. -# TYPE container_fs_usage_bytes gauge -container_fs_usage_bytes{device="sda1",id="testcontainer",image="test",name="testcontainer"} 23 -container_fs_usage_bytes{device="sda2",id="testcontainer",image="test",name="testcontainer"} 38 -# HELP container_fs_write_seconds_total Cumulative count of seconds spent writing -# TYPE container_fs_write_seconds_total counter -container_fs_write_seconds_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 4.1e-08 -container_fs_write_seconds_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 4.6e-08 -# HELP container_fs_writes_merged_total Cumulative count of writes merged -# TYPE container_fs_writes_merged_total counter -container_fs_writes_merged_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 39 -container_fs_writes_merged_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 44 -# HELP container_fs_writes_total Cumulative count of writes completed -# TYPE container_fs_writes_total counter -container_fs_writes_total{device="sda1",id="testcontainer",image="test",name="testcontainer"} 28 -container_fs_writes_total{device="sda2",id="testcontainer",image="test",name="testcontainer"} 43 -# HELP container_last_seen Last time a container was seen by the exporter -# TYPE container_last_seen gauge -container_last_seen{id="testcontainer",image="test",name="testcontainer"} 1.426203694e+09 -# HELP container_memory_failures_total Cumulative count of memory allocation failures. -# TYPE container_memory_failures_total counter -container_memory_failures_total{id="testcontainer",image="test",name="testcontainer",scope="container",type="pgfault"} 10 -container_memory_failures_total{id="testcontainer",image="test",name="testcontainer",scope="container",type="pgmajfault"} 11 -container_memory_failures_total{id="testcontainer",image="test",name="testcontainer",scope="hierarchy",type="pgfault"} 12 -container_memory_failures_total{id="testcontainer",image="test",name="testcontainer",scope="hierarchy",type="pgmajfault"} 13 -# HELP container_memory_usage_bytes Current memory usage in bytes. -# TYPE container_memory_usage_bytes gauge -container_memory_usage_bytes{id="testcontainer",image="test",name="testcontainer"} 8 -# HELP container_memory_working_set_bytes Current working set in bytes. -# TYPE container_memory_working_set_bytes gauge -container_memory_working_set_bytes{id="testcontainer",image="test",name="testcontainer"} 9 -# HELP container_network_receive_bytes_total Cumulative count of bytes received -# TYPE container_network_receive_bytes_total counter -container_network_receive_bytes_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 14 -# HELP container_network_receive_errors_total Cumulative count of errors encountered while receiving -# TYPE container_network_receive_errors_total counter -container_network_receive_errors_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 16 -# HELP container_network_receive_packets_dropped_total Cumulative count of packets dropped while receiving -# TYPE container_network_receive_packets_dropped_total counter -container_network_receive_packets_dropped_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 17 -# HELP container_network_receive_packets_total Cumulative count of packets received -# TYPE container_network_receive_packets_total counter -container_network_receive_packets_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 15 -# HELP container_network_transmit_bytes_total Cumulative count of bytes transmitted -# TYPE container_network_transmit_bytes_total counter -container_network_transmit_bytes_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 18 -# HELP container_network_transmit_errors_total Cumulative count of errors encountered while transmitting -# TYPE container_network_transmit_errors_total counter -container_network_transmit_errors_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 20 -# HELP container_network_transmit_packets_dropped_total Cumulative count of packets dropped while transmitting -# TYPE container_network_transmit_packets_dropped_total counter -container_network_transmit_packets_dropped_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 21 -# HELP container_network_transmit_packets_total Cumulative count of packets transmitted -# TYPE container_network_transmit_packets_total counter -container_network_transmit_packets_total{id="testcontainer",image="test",interface="eth0",name="testcontainer"} 19 -# HELP container_scrape_error 1 if there was an error while getting container metrics, 0 otherwise -# TYPE container_scrape_error gauge -container_scrape_error 0 -# HELP container_tasks_state Number of tasks in given state -# TYPE container_tasks_state gauge -container_tasks_state{id="testcontainer",image="test",name="testcontainer",state="iowaiting"} 54 -container_tasks_state{id="testcontainer",image="test",name="testcontainer",state="running"} 51 -container_tasks_state{id="testcontainer",image="test",name="testcontainer",state="sleeping"} 50 -container_tasks_state{id="testcontainer",image="test",name="testcontainer",state="stopped"} 52 -container_tasks_state{id="testcontainer",image="test",name="testcontainer",state="uninterruptible"} 53 -# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. -# TYPE http_request_duration_microseconds summary -http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 0 -http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 0 -http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="prometheus"} 0 -http_request_duration_microseconds_count{handler="prometheus"} 0 -# HELP http_request_size_bytes The HTTP request sizes in bytes. -# TYPE http_request_size_bytes summary -http_request_size_bytes{handler="prometheus",quantile="0.5"} 0 -http_request_size_bytes{handler="prometheus",quantile="0.9"} 0 -http_request_size_bytes{handler="prometheus",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="prometheus"} 0 -http_request_size_bytes_count{handler="prometheus"} 0 -# HELP http_response_size_bytes The HTTP response sizes in bytes. -# TYPE http_response_size_bytes summary -http_response_size_bytes{handler="prometheus",quantile="0.5"} 0 -http_response_size_bytes{handler="prometheus",quantile="0.9"} 0 -http_response_size_bytes{handler="prometheus",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="prometheus"} 0 -http_response_size_bytes_count{handler="prometheus"} 0 -# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. -# TYPE process_cpu_seconds_total counter -process_cpu_seconds_total 0 -# HELP process_goroutines Number of goroutines that currently exist. -# TYPE process_goroutines gauge -process_goroutines 16 -# HELP process_max_fds Maximum number of open file descriptors. -# TYPE process_max_fds gauge -process_max_fds 1024 -# HELP process_open_fds Number of open file descriptors. -# TYPE process_open_fds gauge -process_open_fds 4 -# HELP process_resident_memory_bytes Resident memory size in bytes. -# TYPE process_resident_memory_bytes gauge -process_resident_memory_bytes 7.74144e+06 -# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. -# TYPE process_start_time_seconds gauge -process_start_time_seconds 1.42620369439e+09 -# HELP process_virtual_memory_bytes Virtual memory size in bytes. -# TYPE process_virtual_memory_bytes gauge -process_virtual_memory_bytes 1.16420608e+08 diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/storage/influxdb/influxdb_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/storage/influxdb/influxdb_test.go deleted file mode 100644 index d7261be79d7..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/storage/influxdb/influxdb_test.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// +build influxdb_test -// To run unit test: go test -tags influxdb_test - -package influxdb - -import ( - "fmt" - "reflect" - "testing" - "time" - - info "github.com/google/cadvisor/info/v1" - "github.com/google/cadvisor/storage" - "github.com/google/cadvisor/storage/test" - influxdb "github.com/influxdb/influxdb/client" -) - -// The duration in seconds for which stats will be buffered in the influxdb driver. -const kCacheDuration = 1 - -type influxDbTestStorageDriver struct { - count int - buffer int - base storage.StorageDriver -} - -func (self *influxDbTestStorageDriver) readyToFlush() bool { - if self.count >= self.buffer { - return true - } - return false -} - -func (self *influxDbTestStorageDriver) AddStats(ref info.ContainerReference, stats *info.ContainerStats) error { - self.count++ - return self.base.AddStats(ref, stats) -} - -func (self *influxDbTestStorageDriver) RecentStats(containerName string, numStats int) ([]*info.ContainerStats, error) { - return nil, nil -} - -func (self *influxDbTestStorageDriver) Percentiles(containerName string, cpuUsagePercentiles []int, memUsagePercentiles []int) (*info.ContainerStatsPercentiles, error) { - return self.base.Percentiles(containerName, cpuUsagePercentiles, memUsagePercentiles) -} - -func (self *influxDbTestStorageDriver) Samples(containerName string, numSamples int) ([]*info.ContainerStatsSample, error) { - return self.base.Samples(containerName, numSamples) -} - -func (self *influxDbTestStorageDriver) Close() error { - return self.base.Close() -} - -func (self *influxDbTestStorageDriver) StatsEq(a, b *info.ContainerStats) bool { - if !test.TimeEq(a.Timestamp, b.Timestamp, 10*time.Millisecond) { - return false - } - // Check only the stats populated in influxdb. - if a.Cpu.Usage.Total != b.Cpu.Usage.Total { - return false - } - - if a.Memory.Usage != b.Memory.Usage { - return false - } - - if a.Memory.WorkingSet != b.Memory.WorkingSet { - return false - } - - if !reflect.DeepEqual(a.Network, b.Network) { - return false - } - - if !reflect.DeepEqual(a.Filesystem, b.Filesystem) { - return false - } - return true -} - -func runStorageTest(f func(test.TestStorageDriver, *testing.T), t *testing.T, bufferCount int) { - machineName := "machineA" - tablename := "t" - database := "cadvisor" - username := "root" - password := "root" - hostname := "localhost:8086" - percentilesDuration := 10 * time.Minute - rootConfig := &influxdb.ClientConfig{ - Host: hostname, - Username: username, - Password: password, - IsSecure: false, - } - rootClient, err := influxdb.NewClient(rootConfig) - if err != nil { - t.Fatal(err) - } - // create the data base first. - rootClient.CreateDatabase(database) - config := &influxdb.ClientConfig{ - Host: hostname, - Username: username, - Password: password, - Database: database, - IsSecure: false, - } - client, err := influxdb.NewClient(config) - if err != nil { - t.Fatal(err) - } - client.DisableCompression() - deleteAll := fmt.Sprintf("drop series %v", tablename) - _, err = client.Query(deleteAll) - if err != nil { - t.Fatal(err) - } - // delete all data by the end of the call - defer client.Query(deleteAll) - - driver, err := New(machineName, - tablename, - database, - username, - password, - hostname, - false, - time.Duration(bufferCount), - percentilesDuration) - if err != nil { - t.Fatal(err) - } - testDriver := &influxDbTestStorageDriver{buffer: bufferCount} - driver.OverrideReadyToFlush(testDriver.readyToFlush) - testDriver.base = driver - - // generate another container's data on same machine. - test.StorageDriverFillRandomStatsFunc("containerOnSameMachine", 100, testDriver, t) - - // generate another container's data on another machine. - driverForAnotherMachine, err := New("machineB", - tablename, - database, - username, - password, - hostname, - false, - time.Duration(bufferCount), - percentilesDuration) - if err != nil { - t.Fatal(err) - } - defer driverForAnotherMachine.Close() - testDriverOtherMachine := &influxDbTestStorageDriver{buffer: bufferCount} - driverForAnotherMachine.OverrideReadyToFlush(testDriverOtherMachine.readyToFlush) - testDriverOtherMachine.base = driverForAnotherMachine - - test.StorageDriverFillRandomStatsFunc("containerOnAnotherMachine", 100, testDriverOtherMachine, t) - f(testDriver, t) -} - -func TestRetrievePartialRecentStats(t *testing.T) { - runStorageTest(test.StorageDriverTestRetrievePartialRecentStats, t, 20) -} - -func TestRetrieveAllRecentStats(t *testing.T) { - runStorageTest(test.StorageDriverTestRetrieveAllRecentStats, t, 10) -} - -func TestNoRecentStats(t *testing.T) { - runStorageTest(test.StorageDriverTestNoRecentStats, t, kCacheDuration) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/summary/buffer_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/summary/buffer_test.go deleted file mode 100644 index 357ede7c0a2..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/summary/buffer_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package summary - -import ( - "reflect" - "testing" - - info "github.com/google/cadvisor/info/v2" -) - -func createSample(i uint64) info.Usage { - usage := info.Usage{} - usage.PercentComplete = 100 - usage.Cpu = info.Percentiles{ - Present: true, - Mean: i * 50, - Max: i * 100, - Ninety: i * 90, - } - usage.Memory = info.Percentiles{ - Present: true, - Mean: i * 50 * 1024, - Max: i * 100 * 1024, - Ninety: i * 90 * 1024, - } - return usage -} - -func expectSize(t *testing.T, b *SamplesBuffer, expectedSize int) { - if b.Size() != expectedSize { - t.Errorf("Expected size %d, got %d", expectedSize, b.Size()) - } -} - -func expectElements(t *testing.T, b *SamplesBuffer, expected []info.Usage) { - - out := b.RecentStats(b.Size()) - if len(out) != len(expected) { - t.Errorf("Expected %d elements, got %d", len(expected), len(out)) - } - for i, el := range out { - if !reflect.DeepEqual(*el, expected[i]) { - t.Errorf("Expected elements %v, got %v", expected[i], *el) - } - } -} - -func TestEmpty(t *testing.T) { - b := NewSamplesBuffer(5) - expectSize(t, b, 0) - expectElements(t, b, []info.Usage{}) -} - -func TestAddSingleSample(t *testing.T) { - b := NewSamplesBuffer(5) - - sample := createSample(1) - b.Add(sample) - expectSize(t, b, 1) - expectElements(t, b, []info.Usage{sample}) -} - -func TestFullBuffer(t *testing.T) { - maxSize := 5 - b := NewSamplesBuffer(maxSize) - samples := []info.Usage{} - for i := 0; i < maxSize; i++ { - sample := createSample(uint64(i)) - samples = append(samples, sample) - b.Add(sample) - } - expectSize(t, b, maxSize) - expectElements(t, b, samples) -} - -func TestOverflow(t *testing.T) { - maxSize := 5 - overflow := 2 - b := NewSamplesBuffer(maxSize) - samples := []info.Usage{} - for i := 0; i < maxSize+overflow; i++ { - sample := createSample(uint64(i)) - if i >= overflow { - samples = append(samples, sample) - } - b.Add(sample) - } - expectSize(t, b, maxSize) - expectElements(t, b, samples) -} - -func TestReplaceAll(t *testing.T) { - maxSize := 5 - b := NewSamplesBuffer(maxSize) - samples := []info.Usage{} - for i := 0; i < maxSize*2; i++ { - sample := createSample(uint64(i)) - if i >= maxSize { - samples = append(samples, sample) - } - b.Add(sample) - } - expectSize(t, b, maxSize) - expectElements(t, b, samples) -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/summary/percentiles_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/summary/percentiles_test.go deleted file mode 100644 index 4dbe3665d35..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/summary/percentiles_test.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package summary - -import ( - "testing" - "time" - - info "github.com/google/cadvisor/info/v2" -) - -const Nanosecond = 1000000000 - -func assertPercentile(t *testing.T, s Uint64Slice, f float64, want uint64) { - if got := s.GetPercentile(f); got != want { - t.Errorf("GetPercentile(%f) is %d, should be %d.", f, got, want) - } -} - -func TestPercentile(t *testing.T) { - N := 100 - s := make(Uint64Slice, 0, N) - for i := N; i > 0; i-- { - s = append(s, uint64(i)) - } - assertPercentile(t, s, 0.2, 20) - assertPercentile(t, s, 0.7, 70) - assertPercentile(t, s, 0.9, 90) - N = 105 - for i := 101; i <= N; i++ { - s = append(s, uint64(i)) - } - // 90p should be between 94 and 95. Promoted to 95. - assertPercentile(t, s, 0.2, 21) - assertPercentile(t, s, 0.7, 74) - assertPercentile(t, s, 0.9, 95) -} - -func TestMean(t *testing.T) { - var i, N uint64 - N = 100 - mean := mean{count: 0, Mean: 0} - for i = 1; i < N; i++ { - mean.Add(i) - } - if mean.Mean != 50.0 { - t.Errorf("Mean is %f, should be 50.0", mean.Mean) - } -} - -func TestAggregates(t *testing.T) { - N := uint64(100) - var i uint64 - ct := time.Now() - stats := make([]*secondSample, 0, N) - for i = 1; i < N; i++ { - s := &secondSample{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - // cpu rate is 1 s/s - Cpu: i * Nanosecond, - // Memory grows by a KB every second. - Memory: i * 1024, - } - stats = append(stats, s) - } - usage := GetMinutePercentiles(stats) - // Cpu mean, max, and 90p should all be 1000 ms/s. - cpuExpected := info.Percentiles{ - Present: true, - Mean: 1000, - Max: 1000, - Fifty: 1000, - Ninety: 1000, - NinetyFive: 1000, - } - if usage.Cpu != cpuExpected { - t.Errorf("cpu stats are %+v. Expected %+v", usage.Cpu, cpuExpected) - } - memExpected := info.Percentiles{ - Present: true, - Mean: 50 * 1024, - Max: 99 * 1024, - Fifty: 50 * 1024, - Ninety: 90 * 1024, - NinetyFive: 95 * 1024, - } - if usage.Memory != memExpected { - t.Errorf("memory stats are mean %+v. Expected %+v", usage.Memory, memExpected) - } -} -func TestSamplesCloseInTimeIgnored(t *testing.T) { - N := uint64(100) - var i uint64 - ct := time.Now() - stats := make([]*secondSample, 0, N*2) - for i = 1; i < N; i++ { - s1 := &secondSample{ - Timestamp: ct.Add(time.Duration(i) * time.Second), - // cpu rate is 1 s/s - Cpu: i * Nanosecond, - // Memory grows by a KB every second. - Memory: i * 1024, - } - stats = append(stats, s1) - - // Add another dummy sample too close in time to the last one. - s2 := &secondSample{ - // Add extra millisecond. - Timestamp: ct.Add(time.Duration(i) * time.Second).Add(time.Duration(1) * time.Millisecond), - Cpu: i * 100 * Nanosecond, - Memory: i * 1024 * 1024, - } - stats = append(stats, s2) - } - usage := GetMinutePercentiles(stats) - // Cpu mean, max, and 90p should all be 1000 ms/s. All high-value samples are discarded. - cpuExpected := info.Percentiles{ - Present: true, - Mean: 1000, - Max: 1000, - Fifty: 1000, - Ninety: 1000, - NinetyFive: 1000, - } - if usage.Cpu != cpuExpected { - t.Errorf("cpu stats are %+v. Expected %+v", usage.Cpu, cpuExpected) - } - memExpected := info.Percentiles{ - Present: true, - Mean: 50 * 1024, - Max: 99 * 1024, - Fifty: 50 * 1024, - Ninety: 90 * 1024, - NinetyFive: 95 * 1024, - } - if usage.Memory != memExpected { - t.Errorf("memory stats are mean %+v. Expected %+v", usage.Memory, memExpected) - } -} - -func TestDerivedStats(t *testing.T) { - N := uint64(100) - var i uint64 - stats := make([]*info.Usage, 0, N) - for i = 1; i < N; i++ { - s := &info.Usage{ - PercentComplete: 100, - Cpu: info.Percentiles{ - Present: true, - Mean: i * Nanosecond, - Max: i * Nanosecond, - Fifty: i * Nanosecond, - Ninety: i * Nanosecond, - NinetyFive: i * Nanosecond, - }, - Memory: info.Percentiles{ - Present: true, - Mean: i * 1024, - Max: i * 1024, - Fifty: i * 1024, - Ninety: i * 1024, - NinetyFive: i * 1024, - }, - } - stats = append(stats, s) - } - usage := GetDerivedPercentiles(stats) - cpuExpected := info.Percentiles{ - Present: true, - Mean: 50 * Nanosecond, - Max: 99 * Nanosecond, - Fifty: 50 * Nanosecond, - Ninety: 90 * Nanosecond, - NinetyFive: 95 * Nanosecond, - } - if usage.Cpu != cpuExpected { - t.Errorf("cpu stats are %+v. Expected %+v", usage.Cpu, cpuExpected) - } - memExpected := info.Percentiles{ - Present: true, - Mean: 50 * 1024, - Max: 99 * 1024, - Fifty: 50 * 1024, - Ninety: 90 * 1024, - NinetyFive: 95 * 1024, - } - if usage.Memory != memExpected { - t.Errorf("memory stats are mean %+v. Expected %+v", usage.Memory, memExpected) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/testdata/cpuinfo b/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/testdata/cpuinfo deleted file mode 100644 index ca2b722a560..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/testdata/cpuinfo +++ /dev/null @@ -1,251 +0,0 @@ -processor : 0 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 0 -cpu cores : 6 -apicid : 0 -initial apicid : 0 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 1 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 1 -cpu cores : 6 -apicid : 2 -initial apicid : 2 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 2 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 2 -cpu cores : 6 -apicid : 4 -initial apicid : 4 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 3 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 3 -cpu cores : 6 -apicid : 16 -initial apicid : 16 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 4 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 4 -cpu cores : 6 -apicid : 18 -initial apicid : 18 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 5 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 5 -cpu cores : 6 -apicid : 20 -initial apicid : 20 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 6 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 2661.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 0 -cpu cores : 6 -apicid : 1 -initial apicid : 1 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 7 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 2661.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 1 -cpu cores : 6 -apicid : 3 -initial apicid : 3 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 8 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 0 -siblings : 6 -core id : 2 -cpu cores : 6 -apicid : 5 -initial apicid : 5 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 9 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 2661.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 3 -cpu cores : 6 -apicid : 17 -initial apicid : 17 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - -processor : 10 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 1596.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 4 -cpu cores : 6 -apicid : 19 -initial apicid : 19 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual -processor : 11 -cpu family : 6 -stepping : 2 -microcode : 0x10 -cpu MHz : 2661.000 -cache size : 12288 KB -physical id : 1 -siblings : 6 -core id : 5 -cpu cores : 6 -apicid : 21 -initial apicid : 21 -fpu : yes -fpu_exception : yes -cpuid level : 11 -wp : yes -bogomips : 5333.60 -clflush size : 64 -cache_alignment : 64 -address sizes : 40 bits physical, 48 bits virtual - diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/topology_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/topology_test.go deleted file mode 100644 index 0c3f158872d..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/utils/machine/topology_test.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package machine - -import ( - "io/ioutil" - "reflect" - "testing" - - info "github.com/google/cadvisor/info/v1" - "github.com/google/cadvisor/utils/sysfs" - "github.com/google/cadvisor/utils/sysfs/fakesysfs" -) - -func TestTopology(t *testing.T) { - testfile := "./testdata/cpuinfo" - testcpuinfo, err := ioutil.ReadFile(testfile) - if err != nil { - t.Fatalf("unable to read input test file %s", testfile) - } - sysFs := &fakesysfs.FakeSysFs{} - c := sysfs.CacheInfo{ - Size: 32 * 1024, - Type: "unified", - Level: 1, - Cpus: 2, - } - sysFs.SetCacheInfo(c) - topology, numCores, err := GetTopology(sysFs, string(testcpuinfo)) - if err != nil { - t.Errorf("failed to get topology for sample cpuinfo %s", string(testcpuinfo)) - } - - if numCores != 12 { - t.Errorf("Expected 12 cores, found %d", numCores) - } - expected_topology := []info.Node{} - numNodes := 2 - numCoresPerNode := 3 - numThreads := 2 - cache := info.Cache{ - Size: 32 * 1024, - Type: "unified", - Level: 1, - } - for i := 0; i < numNodes; i++ { - node := info.Node{Id: i} - // Copy over Memory from result. TODO(rjnagal): Use memory from fake. - node.Memory = topology[i].Memory - for j := 0; j < numCoresPerNode; j++ { - core := info.Core{Id: i*numCoresPerNode + j} - core.Caches = append(core.Caches, cache) - for k := 0; k < numThreads; k++ { - core.Threads = append(core.Threads, k*numCoresPerNode*numNodes+core.Id) - } - node.Cores = append(node.Cores, core) - } - expected_topology = append(expected_topology, node) - } - - if !reflect.DeepEqual(topology, expected_topology) { - t.Errorf("Expected topology %+v, got %+v", expected_topology, topology) - } -} - -func TestTopologyWithSimpleCpuinfo(t *testing.T) { - sysFs := &fakesysfs.FakeSysFs{} - c := sysfs.CacheInfo{ - Size: 32 * 1024, - Type: "unified", - Level: 1, - Cpus: 1, - } - sysFs.SetCacheInfo(c) - topology, numCores, err := GetTopology(sysFs, "processor\t: 0\n") - if err != nil { - t.Errorf("Expected cpuinfo with no topology data to succeed.") - } - node := info.Node{Id: 0} - core := info.Core{Id: 0} - core.Threads = append(core.Threads, 0) - cache := info.Cache{ - Size: 32 * 1024, - Type: "unified", - Level: 1, - } - core.Caches = append(core.Caches, cache) - node.Cores = append(node.Cores, core) - // Copy over Memory from result. TODO(rjnagal): Use memory from fake. - node.Memory = topology[0].Memory - expected := []info.Node{node} - if !reflect.DeepEqual(topology, expected) { - t.Errorf("Expected topology %+v, got %+v", expected, topology) - } - if numCores != 1 { - t.Errorf("Expected 1 core, found %d", numCores) - } -} - -func TestTopologyEmptyCpuinfo(t *testing.T) { - _, _, err := GetTopology(&fakesysfs.FakeSysFs{}, "") - if err == nil { - t.Errorf("Expected empty cpuinfo to fail.") - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/utils/oomparser/oomparser_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/utils/oomparser/oomparser_test.go deleted file mode 100644 index 7da55e61fe8..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/utils/oomparser/oomparser_test.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2015 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package oomparser - -import ( - "bufio" - "os" - "reflect" - "testing" - "time" -) - -const startLine = "Jan 21 22:01:49 localhost kernel: [62278.816267] ruby invoked oom-killer: gfp_mask=0x201da, order=0, oom_score_adj=0" -const endLine = "Jan 21 22:01:49 localhost kernel: [62279.421192] Killed process 19667 (evilprogram2) total-vm:1460016kB, anon-rss:1414008kB, file-rss:4kB" -const containerLine = "Jan 26 14:10:07 kateknister0.mtv.corp.google.com kernel: [1814368.465205] Task in /mem2 killed as a result of limit of /mem3" -const containerLogFile = "containerOomExampleLog.txt" -const systemLogFile = "systemOomExampleLog.txt" - -func createExpectedContainerOomInstance(t *testing.T) *OomInstance { - const longForm = "Jan _2 15:04:05 2006" - deathTime, err := time.ParseInLocation(longForm, "Jan 5 15:19:27 2015", time.Local) - if err != nil { - t.Fatalf("could not parse expected time when creating expected container oom instance. Had error %v", err) - return nil - } - return &OomInstance{ - Pid: 13536, - ProcessName: "memorymonster", - TimeOfDeath: deathTime, - ContainerName: "/mem2", - VictimContainerName: "/mem3", - } -} - -func createExpectedSystemOomInstance(t *testing.T) *OomInstance { - const longForm = "Jan _2 15:04:05 2006" - deathTime, err := time.ParseInLocation(longForm, "Jan 28 19:58:45 2015", time.Local) - if err != nil { - t.Fatalf("could not parse expected time when creating expected system oom instance. Had error %v", err) - return nil - } - return &OomInstance{ - Pid: 1532, - ProcessName: "badsysprogram", - TimeOfDeath: deathTime, - ContainerName: "/", - VictimContainerName: "/", - } -} - -func TestGetContainerName(t *testing.T) { - currentOomInstance := new(OomInstance) - err := getContainerName(startLine, currentOomInstance) - if err != nil { - t.Errorf("bad line fed to getContainerName should yield no error, but had error %v", err) - } - if currentOomInstance.ContainerName != "" { - t.Errorf("bad line fed to getContainerName yielded no container name but set it to %s", currentOomInstance.ContainerName) - } - err = getContainerName(containerLine, currentOomInstance) - if err != nil { - t.Errorf("container line fed to getContainerName should yield no error, but had error %v", err) - } - if currentOomInstance.ContainerName != "/mem2" { - t.Errorf("getContainerName should have set containerName to /mem2, not %s", currentOomInstance.ContainerName) - } - if currentOomInstance.VictimContainerName != "/mem3" { - t.Errorf("getContainerName should have set victimContainerName to /mem3, not %s", currentOomInstance.VictimContainerName) - } -} - -func TestGetProcessNamePid(t *testing.T) { - currentOomInstance := new(OomInstance) - couldParseLine, err := getProcessNamePid(startLine, currentOomInstance) - if err != nil { - t.Errorf("bad line fed to getProcessNamePid should yield no error, but had error %v", err) - } - if couldParseLine { - t.Errorf("bad line fed to getProcessNamePid should return false but returned %v", couldParseLine) - } - - const longForm = "Jan _2 15:04:05 2006" - correctTime, err := time.ParseInLocation(longForm, "Jan 21 22:01:49 2015", time.Local) - couldParseLine, err = getProcessNamePid(endLine, currentOomInstance) - if err != nil { - t.Errorf("good line fed to getProcessNamePid should yield no error, but had error %v", err) - } - if !couldParseLine { - t.Errorf("good line fed to getProcessNamePid should return true but returned %v", couldParseLine) - } - if currentOomInstance.ProcessName != "evilprogram2" { - t.Errorf("getProcessNamePid should have set processName to evilprogram2, not %s", currentOomInstance.ProcessName) - } - if currentOomInstance.Pid != 19667 { - t.Errorf("getProcessNamePid should have set PID to 19667, not %d", currentOomInstance.Pid) - } - if !correctTime.Equal(currentOomInstance.TimeOfDeath) { - t.Errorf("getProcessNamePid should have set date to %v, not %v", correctTime, currentOomInstance.TimeOfDeath) - } -} - -func TestCheckIfStartOfMessages(t *testing.T) { - couldParseLine := checkIfStartOfOomMessages(endLine) - if couldParseLine { - t.Errorf("bad line fed to checkIfStartOfMessages should return false but returned %v", couldParseLine) - } - couldParseLine = checkIfStartOfOomMessages(startLine) - if !couldParseLine { - t.Errorf("start line fed to checkIfStartOfMessages should return true but returned %v", couldParseLine) - } -} - -func TestStreamOomsContainer(t *testing.T) { - expectedContainerOomInstance := createExpectedContainerOomInstance(t) - helpTestStreamOoms(expectedContainerOomInstance, containerLogFile, t) -} - -func TestStreamOomsSystem(t *testing.T) { - expectedSystemOomInstance := createExpectedSystemOomInstance(t) - helpTestStreamOoms(expectedSystemOomInstance, systemLogFile, t) -} - -func helpTestStreamOoms(oomCheckInstance *OomInstance, sysFile string, t *testing.T) { - outStream := make(chan *OomInstance) - oomLog := mockOomParser(sysFile, t) - timeout := make(chan bool, 1) - go func() { - time.Sleep(1 * time.Second) - timeout <- true - }() - - go oomLog.StreamOoms(outStream) - - select { - case oomInstance := <-outStream: - if reflect.DeepEqual(*oomCheckInstance, *oomInstance) { - t.Errorf("wrong instance returned. Expected %v and got %v", - oomCheckInstance, oomInstance) - } - case <-timeout: - t.Error( - "timeout happened before oomInstance was found in test file") - } -} - -func mockOomParser(sysFile string, t *testing.T) *OomParser { - file, err := os.Open(sysFile) - if err != nil { - t.Errorf("had an error opening file: %v", err) - } - return &OomParser{ - ioreader: bufio.NewReader(file), - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/utils/sysinfo/sysinfo_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/utils/sysinfo/sysinfo_test.go deleted file mode 100644 index 97df16b9c99..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/utils/sysinfo/sysinfo_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package sysinfo - -import ( - "testing" - - info "github.com/google/cadvisor/info/v1" - "github.com/google/cadvisor/utils/sysfs" - "github.com/google/cadvisor/utils/sysfs/fakesysfs" -) - -func TestGetBlockDeviceInfo(t *testing.T) { - fakeSys := fakesysfs.FakeSysFs{} - disks, err := GetBlockDeviceInfo(&fakeSys) - if err != nil { - t.Errorf("expected call to GetBlockDeviceInfo() to succeed. Failed with %s", err) - } - if len(disks) != 1 { - t.Errorf("expected to get one disk entry. Got %d", len(disks)) - } - key := "8:0" - disk, ok := disks[key] - if !ok { - t.Fatalf("expected key 8:0 to exist in the disk map.") - } - if disk.Name != "sda" { - t.Errorf("expected to get disk named sda. Got %q", disk.Name) - } - size := uint64(1234567 * 512) - if disk.Size != size { - t.Errorf("expected to get disk size of %d. Got %d", size, disk.Size) - } - if disk.Scheduler != "cfq" { - t.Errorf("expected to get scheduler type of cfq. Got %q", disk.Scheduler) - } -} - -func TestGetNetworkDevices(t *testing.T) { - fakeSys := fakesysfs.FakeSysFs{} - fakeSys.SetEntryName("eth0") - devs, err := GetNetworkDevices(&fakeSys) - if err != nil { - t.Errorf("expected call to GetNetworkDevices() to succeed. Failed with %s", err) - } - if len(devs) != 1 { - t.Errorf("expected to get one network device. Got %d", len(devs)) - } - eth := devs[0] - if eth.Name != "eth0" { - t.Errorf("expected to find device with name eth0. Found name %q", eth.Name) - } - if eth.Mtu != 1024 { - t.Errorf("expected mtu to be set to 1024. Found %d", eth.Mtu) - } - if eth.Speed != 1000 { - t.Errorf("expected device speed to be set to 1000. Found %d", eth.Speed) - } - if eth.MacAddress != "42:01:02:03:04:f4" { - t.Errorf("expected mac address to be '42:01:02:03:04:f4'. Found %q", eth.MacAddress) - } -} - -func TestIgnoredNetworkDevices(t *testing.T) { - fakeSys := fakesysfs.FakeSysFs{} - ignoredDevices := []string{"veth1234", "lo", "docker0"} - for _, name := range ignoredDevices { - fakeSys.SetEntryName(name) - devs, err := GetNetworkDevices(&fakeSys) - if err != nil { - t.Errorf("expected call to GetNetworkDevices() to succeed. Failed with %s", err) - } - if len(devs) != 0 { - t.Errorf("expected dev %s to be ignored, but got info %+v", name, devs) - } - } -} - -func TestGetCacheInfo(t *testing.T) { - fakeSys := &fakesysfs.FakeSysFs{} - cacheInfo := sysfs.CacheInfo{ - Size: 1024, - Type: "Data", - Level: 3, - Cpus: 16, - } - fakeSys.SetCacheInfo(cacheInfo) - caches, err := GetCacheInfo(fakeSys, 0) - if err != nil { - t.Errorf("expected call to GetCacheInfo() to succeed. Failed with %s", err) - } - if len(caches) != 1 { - t.Errorf("expected to get one cache. Got %d", len(caches)) - } - if caches[0] != cacheInfo { - t.Errorf("expected to find cacheinfo %+v. Got %+v", cacheInfo, caches[0]) - } -} - -func TestGetNetworkStats(t *testing.T) { - expected_stats := info.InterfaceStats{ - Name: "eth0", - RxBytes: 1024, - RxPackets: 1024, - RxErrors: 1024, - RxDropped: 1024, - TxBytes: 1024, - TxPackets: 1024, - TxErrors: 1024, - TxDropped: 1024, - } - fakeSys := &fakesysfs.FakeSysFs{} - netStats, err := getNetworkStats("eth0", fakeSys) - if err != nil { - t.Errorf("call to getNetworkStats() failed with %s", err) - } - if expected_stats != netStats { - t.Errorf("expected to get stats %+v, got %+v", expected_stats, netStats) - } -} diff --git a/Godeps/_workspace/src/github.com/google/cadvisor/utils/timed_store_test.go b/Godeps/_workspace/src/github.com/google/cadvisor/utils/timed_store_test.go deleted file mode 100644 index 76b777820c4..00000000000 --- a/Godeps/_workspace/src/github.com/google/cadvisor/utils/timed_store_test.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func createTime(id int) time.Time { - var zero time.Time - return zero.Add(time.Duration(id+1) * time.Second) -} - -func expectSize(t *testing.T, sb *TimedStore, expectedSize int) { - if sb.Size() != expectedSize { - t.Errorf("Expected size %v, got %v", expectedSize, sb.Size()) - } -} - -func expectAllElements(t *testing.T, sb *TimedStore, expected []int) { - size := sb.Size() - els := make([]interface{}, size) - for i := 0; i < size; i++ { - els[i] = sb.Get(size - i - 1) - } - expectElements(t, []interface{}(els), expected) -} - -func expectElements(t *testing.T, actual []interface{}, expected []int) { - if len(actual) != len(expected) { - t.Errorf("Expected elements %v, got %v", expected, actual) - return - } - for i, el := range actual { - if el.(int) != expected[i] { - t.Errorf("Expected elements %v, got %v", expected, actual) - return - } - } -} - -func TestAdd(t *testing.T) { - sb := NewTimedStore(5*time.Second, 100) - - // Add 1. - sb.Add(createTime(0), 0) - expectSize(t, sb, 1) - expectAllElements(t, sb, []int{0}) - - // Fill the buffer. - for i := 1; i <= 5; i++ { - expectSize(t, sb, i) - sb.Add(createTime(i), i) - } - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{1, 2, 3, 4, 5}) - - // Add more than is available in the buffer - sb.Add(createTime(6), 6) - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{2, 3, 4, 5, 6}) - - // Replace all elements. - for i := 7; i <= 10; i++ { - sb.Add(createTime(i), i) - } - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{6, 7, 8, 9, 10}) -} - -func TestGet(t *testing.T) { - sb := NewTimedStore(5*time.Second, -1) - sb.Add(createTime(1), 1) - sb.Add(createTime(2), 2) - sb.Add(createTime(3), 3) - expectSize(t, sb, 3) - - assert := assert.New(t) - assert.Equal(sb.Get(0).(int), 3) - assert.Equal(sb.Get(1).(int), 2) - assert.Equal(sb.Get(2).(int), 1) -} - -func TestInTimeRange(t *testing.T) { - sb := NewTimedStore(5*time.Second, -1) - assert := assert.New(t) - - var empty time.Time - - // No elements. - assert.Empty(sb.InTimeRange(createTime(0), createTime(5), 10)) - assert.Empty(sb.InTimeRange(createTime(0), empty, 10)) - assert.Empty(sb.InTimeRange(empty, createTime(5), 10)) - assert.Empty(sb.InTimeRange(empty, empty, 10)) - - // One element. - sb.Add(createTime(1), 1) - expectSize(t, sb, 1) - expectElements(t, sb.InTimeRange(createTime(0), createTime(5), 10), []int{1}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(5), 10), []int{1}) - expectElements(t, sb.InTimeRange(createTime(0), createTime(1), 10), []int{1}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(1), 10), []int{1}) - assert.Empty(sb.InTimeRange(createTime(2), createTime(5), 10)) - - // Two element. - sb.Add(createTime(2), 2) - expectSize(t, sb, 2) - expectElements(t, sb.InTimeRange(createTime(0), createTime(5), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(5), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(0), createTime(2), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(2), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(1), 10), []int{1}) - expectElements(t, sb.InTimeRange(createTime(2), createTime(2), 10), []int{2}) - assert.Empty(sb.InTimeRange(createTime(3), createTime(5), 10)) - - // Many elements. - sb.Add(createTime(3), 3) - sb.Add(createTime(4), 4) - expectSize(t, sb, 4) - expectElements(t, sb.InTimeRange(createTime(0), createTime(5), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(0), createTime(5), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(5), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(0), createTime(4), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(4), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(0), createTime(2), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(1), createTime(2), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(createTime(2), createTime(3), 10), []int{2, 3}) - expectElements(t, sb.InTimeRange(createTime(3), createTime(4), 10), []int{3, 4}) - expectElements(t, sb.InTimeRange(createTime(3), createTime(5), 10), []int{3, 4}) - assert.Empty(sb.InTimeRange(createTime(5), createTime(5), 10)) - - // Start and end time ignores maxResults. - expectElements(t, sb.InTimeRange(createTime(1), createTime(5), 1), []int{1, 2, 3, 4}) - - // No start time. - expectElements(t, sb.InTimeRange(empty, createTime(5), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(empty, createTime(4), 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(empty, createTime(3), 10), []int{1, 2, 3}) - expectElements(t, sb.InTimeRange(empty, createTime(2), 10), []int{1, 2}) - expectElements(t, sb.InTimeRange(empty, createTime(1), 10), []int{1}) - - // No end time. - expectElements(t, sb.InTimeRange(createTime(0), empty, 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(1), empty, 10), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(2), empty, 10), []int{2, 3, 4}) - expectElements(t, sb.InTimeRange(createTime(3), empty, 10), []int{3, 4}) - expectElements(t, sb.InTimeRange(createTime(4), empty, 10), []int{4}) - - // No start or end time. - expectElements(t, sb.InTimeRange(empty, empty, 10), []int{1, 2, 3, 4}) - - // Start after data. - assert.Empty(sb.InTimeRange(createTime(5), createTime(5), 10)) - assert.Empty(sb.InTimeRange(createTime(5), empty, 10)) - - // End before data. - assert.Empty(sb.InTimeRange(createTime(0), createTime(0), 10)) - assert.Empty(sb.InTimeRange(empty, createTime(0), 10)) -} - -func TestInTimeRangeWithLimit(t *testing.T) { - sb := NewTimedStore(5*time.Second, -1) - sb.Add(createTime(1), 1) - sb.Add(createTime(2), 2) - sb.Add(createTime(3), 3) - sb.Add(createTime(4), 4) - expectSize(t, sb, 4) - - var empty time.Time - - // Limit cuts off from latest timestamp. - expectElements(t, sb.InTimeRange(empty, empty, 4), []int{1, 2, 3, 4}) - expectElements(t, sb.InTimeRange(empty, empty, 3), []int{2, 3, 4}) - expectElements(t, sb.InTimeRange(empty, empty, 2), []int{3, 4}) - expectElements(t, sb.InTimeRange(empty, empty, 1), []int{4}) - assert.Empty(t, sb.InTimeRange(empty, empty, 0)) -} - -func TestLimitedSize(t *testing.T) { - sb := NewTimedStore(time.Hour, 5) - - // Add 1. - sb.Add(createTime(0), 0) - expectSize(t, sb, 1) - expectAllElements(t, sb, []int{0}) - - // Fill the buffer. - for i := 1; i <= 5; i++ { - expectSize(t, sb, i) - sb.Add(createTime(i), i) - } - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{1, 2, 3, 4, 5}) - - // Add more than is available in the buffer - sb.Add(createTime(6), 6) - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{2, 3, 4, 5, 6}) - - // Replace all elements. - for i := 7; i <= 10; i++ { - sb.Add(createTime(i), i) - } - expectSize(t, sb, 5) - expectAllElements(t, sb, []int{6, 7, 8, 9, 10}) -} diff --git a/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go b/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go deleted file mode 100644 index 792707a3a15..00000000000 --- a/Godeps/_workspace/src/github.com/google/gofuzz/example_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz_test - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/google/gofuzz" -) - -func ExampleSimple() { - type MyType struct { - A string - B string - C int - D struct { - E float64 - } - } - - f := fuzz.New() - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 1000; i++ { - f.Fuzz(&object) - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 1000 unique objects. -} - -func ExampleCustom() { - type MyType struct { - A int - B string - } - - counter := 0 - f := fuzz.New().Funcs( - func(i *int, c fuzz.Continue) { - *i = counter - counter++ - }, - ) - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 100; i++ { - f.Fuzz(&object) - if object.A != i { - fmt.Printf("Unexpected value: %#v\n", object) - } - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 100 unique objects. -} - -func ExampleComplex() { - type OtherType struct { - A string - B string - } - type MyType struct { - Pointer *OtherType - Map map[string]OtherType - PointerMap *map[string]OtherType - Slice []OtherType - SlicePointer []*OtherType - PointerSlicePointer *[]*OtherType - } - - f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( - func(o *OtherType, c fuzz.Continue) { - o.A = "Foo" - o.B = "Bar" - }, - func(op **OtherType, c fuzz.Continue) { - *op = &OtherType{"A", "B"} - }, - func(m map[string]OtherType, c fuzz.Continue) { - m["Works Because"] = OtherType{ - "Fuzzer", - "Preallocated", - } - }, - ) - object := MyType{} - f.Fuzz(&object) - bytes, err := json.MarshalIndent(&object, "", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - fmt.Printf("%s\n", string(bytes)) - // Output: - // { - // "Pointer": { - // "A": "A", - // "B": "B" - // }, - // "Map": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "PointerMap": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "Slice": [ - // { - // "A": "Foo", - // "B": "Bar" - // } - // ], - // "SlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ], - // "PointerSlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ] - // } -} - -func ExampleMap() { - f := fuzz.New().NilChance(0).NumElements(1, 1) - var myMap map[struct{ A, B, C int }]string - f.Fuzz(&myMap) - fmt.Printf("myMap has %v element(s).\n", len(myMap)) - // Output: - // myMap has 1 element(s). -} - -func ExampleSingle() { - f := fuzz.New() - var i int - f.Fuzz(&i) - - // Technically, we'd expect this to fail one out of 2 billion attempts... - fmt.Printf("(i == 0) == %v", i == 0) - // Output: - // (i == 0) == false -} - -func ExampleEnum() { - type MyEnum string - const ( - A MyEnum = "A" - B MyEnum = "B" - ) - type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string - } - - f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - // Note c's embedded Rand allows for direct use. - // We could also use c.RandBool() here. - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, - ) - - for i := 0; i < 100; i++ { - var myObject MyInfo - f.Fuzz(&myObject) - switch myObject.Type { - case A: - if myObject.AInfo == nil { - fmt.Println("AInfo should have been set!") - } - if myObject.BInfo != nil { - fmt.Println("BInfo should NOT have been set!") - } - case B: - if myObject.BInfo == nil { - fmt.Println("BInfo should have been set!") - } - if myObject.AInfo != nil { - fmt.Println("AInfo should NOT have been set!") - } - default: - fmt.Println("Invalid enum value!") - } - } - // Output: -} diff --git a/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go b/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go deleted file mode 100644 index 12abc8f6598..00000000000 --- a/Godeps/_workspace/src/github.com/google/gofuzz/fuzz_test.go +++ /dev/null @@ -1,384 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz - -import ( - "reflect" - "testing" - "time" -) - -func TestFuzz_basic(t *testing.T) { - obj := &struct { - I int - I8 int8 - I16 int16 - I32 int32 - I64 int64 - U uint - U8 uint8 - U16 uint16 - U32 uint32 - U64 uint64 - Uptr uintptr - S string - B bool - T time.Time - }{} - - failed := map[string]int{} - for i := 0; i < 10; i++ { - New().Fuzz(obj) - - if n, v := "i", obj.I; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i8", obj.I8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i16", obj.I16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i32", obj.I32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i64", obj.I64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u", obj.U; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u8", obj.U8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u16", obj.U16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u32", obj.U32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u64", obj.U64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "uptr", obj.Uptr; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "s", obj.S; v == "" { - failed[n] = failed[n] + 1 - } - if n, v := "b", obj.B; v == false { - failed[n] = failed[n] + 1 - } - if n, v := "t", obj.T; v.IsZero() { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -func checkFailed(t *testing.T, failed map[string]int) { - for k, v := range failed { - if v > 8 { - t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) - } - } -} - -func TestFuzz_structptr(t *testing.T) { - obj := &struct { - A *struct { - S string - } - }{} - - f := New().NilChance(.5) - failed := map[string]int{} - for i := 0; i < 10; i++ { - f.Fuzz(obj) - - if n, v := "a not nil", obj.A; v == nil { - failed[n] = failed[n] + 1 - } - if n, v := "a nil", obj.A; v != nil { - failed[n] = failed[n] + 1 - } - if n, v := "as", obj.A; v == nil || v.S == "" { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest -// stage it ever got to. -func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { - maxStage := 0 - for i := 0; i < 20; i++ { - f.Fuzz(obj) - stage, passed := check() - if stage > maxStage { - maxStage = stage - } - if passed { - return - } - } - t.Errorf("Only ever got to stage %v", maxStage) -} - -func TestFuzz_structmap(t *testing.T) { - obj := &struct { - A map[struct { - S string - }]struct { - S2 string - } - B map[string]string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for k, v := range obj.A { - if k.S == "" { - return 3, false - } - if v.S2 == "" { - return 4, false - } - } - - if obj.B == nil { - return 5, false - } - if len(obj.B) == 0 { - return 6, false - } - for k, v := range obj.B { - if k == "" { - return 7, false - } - if v == "" { - return 8, false - } - } - return 9, true - }) -} - -func TestFuzz_structslice(t *testing.T) { - obj := &struct { - A []struct { - S string - } - B []string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for _, v := range obj.A { - if v.S == "" { - return 3, false - } - } - - if obj.B == nil { - return 4, false - } - if len(obj.B) == 0 { - return 5, false - } - for _, v := range obj.B { - if v == "" { - return 6, false - } - } - return 7, true - }) -} - -func TestFuzz_custom(t *testing.T) { - obj := &struct { - A string - B *string - C map[string]string - D *map[string]string - }{} - - testPhrase := "gotcalled" - testMap := map[string]string{"C": "D"} - f := New().Funcs( - func(s *string, c Continue) { - *s = testPhrase - }, - func(m map[string]string, c Continue) { - m["C"] = "D" - }, - ) - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A != testPhrase { - return 1, false - } - if obj.B == nil { - return 2, false - } - if *obj.B != testPhrase { - return 3, false - } - if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { - return 4, false - } - if obj.D == nil { - return 5, false - } - if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { - return 6, false - } - return 7, true - }) -} - -type SelfFuzzer string - -// Implement fuzz.Interface. -func (sf *SelfFuzzer) Fuzz(c Continue) { - *sf = selfFuzzerTestPhrase -} - -const selfFuzzerTestPhrase = "was fuzzed" - -func TestFuzz_interface(t *testing.T) { - f := New() - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != selfFuzzerTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != selfFuzzerTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_interfaceAndFunc(t *testing.T) { - const privateTestPhrase = "private phrase" - f := New().Funcs( - // This should take precedence over SelfFuzzer.Fuzz(). - func(s *SelfFuzzer, c Continue) { - *s = privateTestPhrase - }, - ) - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != privateTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != privateTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_noCustom(t *testing.T) { - type Inner struct { - Str string - } - type Outer struct { - Str string - In Inner - } - - testPhrase := "gotcalled" - f := New().Funcs( - func(outer *Outer, c Continue) { - outer.Str = testPhrase - c.Fuzz(&outer.In) - }, - func(inner *Inner, c Continue) { - inner.Str = testPhrase - }, - ) - c := Continue{f: f, Rand: f.r} - - // Fuzzer.Fuzz() - obj1 := Outer{} - f.Fuzz(&obj1) - if obj1.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj1.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.Fuzz() - obj2 := Outer{} - c.Fuzz(&obj2) - if obj2.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj2.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Fuzzer.FuzzNoCustom() - obj3 := Outer{} - f.FuzzNoCustom(&obj3) - if obj3.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj3.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.FuzzNoCustom() - obj4 := Outer{} - c.FuzzNoCustom(&obj4) - if obj4.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj4.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } -} diff --git a/Godeps/_workspace/src/github.com/gorilla/context/context_test.go b/Godeps/_workspace/src/github.com/gorilla/context/context_test.go deleted file mode 100644 index 9814c501e8a..00000000000 --- a/Godeps/_workspace/src/github.com/gorilla/context/context_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2012 The Gorilla 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 ( - "net/http" - "testing" -) - -type keyType int - -const ( - key1 keyType = iota - key2 -) - -func TestContext(t *testing.T) { - assertEqual := func(val interface{}, exp interface{}) { - if val != exp { - t.Errorf("Expected %v, got %v.", exp, val) - } - } - - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - - // Get() - assertEqual(Get(r, key1), nil) - - // Set() - Set(r, key1, "1") - assertEqual(Get(r, key1), "1") - assertEqual(len(data[r]), 1) - - Set(r, key2, "2") - assertEqual(Get(r, key2), "2") - assertEqual(len(data[r]), 2) - - //GetOk - value, ok := GetOk(r, key1) - assertEqual(value, "1") - assertEqual(ok, true) - - value, ok = GetOk(r, "not exists") - assertEqual(value, nil) - assertEqual(ok, false) - - Set(r, "nil value", nil) - value, ok = GetOk(r, "nil value") - assertEqual(value, nil) - assertEqual(ok, true) - - // GetAll() - values := GetAll(r) - assertEqual(len(values), 3) - - // GetAll() for empty request - values = GetAll(emptyR) - if values != nil { - t.Error("GetAll didn't return nil value for invalid request") - } - - // GetAllOk() - values, ok = GetAllOk(r) - assertEqual(len(values), 3) - assertEqual(ok, true) - - // GetAllOk() for empty request - values, ok = GetAllOk(emptyR) - assertEqual(value, nil) - assertEqual(ok, false) - - // Delete() - Delete(r, key1) - assertEqual(Get(r, key1), nil) - assertEqual(len(data[r]), 2) - - Delete(r, key2) - assertEqual(Get(r, key2), nil) - assertEqual(len(data[r]), 1) - - // Clear() - Clear(r) - assertEqual(len(data), 0) -} - -func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Get(r, key) - } - done <- struct{}{} - -} - -func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Set(r, key, value) - } - done <- struct{}{} - -} - -func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { - - b.StopTimer() - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - done := make(chan struct{}) - b.StartTimer() - - for i := 0; i < b.N; i++ { - wait := make(chan struct{}) - - for i := 0; i < numReaders; i++ { - go parallelReader(r, "test", iterations, wait, done) - } - - for i := 0; i < numWriters; i++ { - go parallelWriter(r, "test", "123", iterations, wait, done) - } - - close(wait) - - for i := 0; i < numReaders+numWriters; i++ { - <-done - } - - } - -} - -func BenchmarkMutexSameReadWrite1(b *testing.B) { - benchmarkMutex(b, 1, 1, 32) -} -func BenchmarkMutexSameReadWrite2(b *testing.B) { - benchmarkMutex(b, 2, 2, 32) -} -func BenchmarkMutexSameReadWrite4(b *testing.B) { - benchmarkMutex(b, 4, 4, 32) -} -func BenchmarkMutex1(b *testing.B) { - benchmarkMutex(b, 2, 8, 32) -} -func BenchmarkMutex2(b *testing.B) { - benchmarkMutex(b, 16, 4, 64) -} -func BenchmarkMutex3(b *testing.B) { - benchmarkMutex(b, 1, 2, 128) -} -func BenchmarkMutex4(b *testing.B) { - benchmarkMutex(b, 128, 32, 256) -} -func BenchmarkMutex5(b *testing.B) { - benchmarkMutex(b, 1024, 2048, 64) -} -func BenchmarkMutex6(b *testing.B) { - benchmarkMutex(b, 2048, 1024, 512) -} diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go deleted file mode 100644 index c5f97b2b2a8..00000000000 --- a/Godeps/_workspace/src/github.com/gorilla/mux/bench_test.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "net/http" - "testing" -) - -func BenchmarkMux(b *testing.B) { - router := new(Router) - handler := func(w http.ResponseWriter, r *http.Request) {} - router.HandleFunc("/v1/{v1}", handler) - - request, _ := http.NewRequest("GET", "/v1/anything", nil) - for i := 0; i < b.N; i++ { - router.ServeHTTP(nil, request) - } -} diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go deleted file mode 100644 index 075dedba48e..00000000000 --- a/Godeps/_workspace/src/github.com/gorilla/mux/mux_test.go +++ /dev/null @@ -1,1003 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "fmt" - "net/http" - "testing" - - "github.com/gorilla/context" -) - -type routeTest struct { - title string // title of the test - route *Route // the route being tested - request *http.Request // a request to test the route - vars map[string]string // the expected vars of the match - host string // the expected host of the match - path string // the expected path of the match - shouldMatch bool // whether the request is expected to match the route at all - shouldRedirect bool // whether the request should result in a redirect -} - -func TestHost(t *testing.T) { - // newRequestHost a new request with a method, url, and host header - newRequestHost := func(method, url, host string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - req.Host = host - return req - } - - tests := []routeTest{ - { - title: "Host route match", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with port, match", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: true, - }, - { - title: "Host route with port, wrong port in request URL", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route, match with host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc"), - request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), - vars: map[string]string{}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, - { - title: "Host route with port, wrong host in request header", - route: new(Route).Host("aaa.bbb.ccc:1234"), - request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), - vars: map[string]string{}, - host: "aaa.bbb.ccc:1234", - path: "", - shouldMatch: false, - }, - { - title: "Host route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with pattern, wrong host in request URL", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Host route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: true, - }, - { - title: "Host route with multiple patterns, wrong host in request URL", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, - host: "aaa.bbb.ccc", - path: "", - shouldMatch: false, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/a"), - vars: map[string]string{"category": "a"}, - host: "", - path: "/a", - shouldMatch: true, - }, - { - title: "Path route with single pattern with pipe, match", - route: new(Route).Path("/{category:a|b/c}"), - request: newRequest("GET", "http://localhost/b/c"), - vars: map[string]string{"category": "b/c"}, - host: "", - path: "/b/c", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns with pipe, match", - route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), - request: newRequest("GET", "http://localhost/a/product_name/1"), - vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, - host: "", - path: "/a/product_name/1", - shouldMatch: true, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPath(t *testing.T) { - tests := []routeTest{ - { - title: "Path route, match", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route, match with trailing slash in request and path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - }, - { - title: "Path route, do not match with trailing slash in path", - route: new(Route).Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "Path route, do not match with trailing slash in request", - route: new(Route).Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: false, - }, - { - title: "Path route, wrong path in request in request URL", - route: new(Route).Path("/111/222/333"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with pattern, match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with pattern, URL in request does not match", - route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Path route with multiple patterns, match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Path route with multiple patterns, URL in request does not match", - route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, - host: "", - path: "/111/222/333", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestPathPrefix(t *testing.T) { - tests := []routeTest{ - { - title: "PathPrefix route, match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - }, - { - title: "PathPrefix route, match substring", - route: new(Route).PathPrefix("/1"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{}, - host: "", - path: "/1", - shouldMatch: true, - }, - { - title: "PathPrefix route, URL prefix in request does not match", - route: new(Route).PathPrefix("/111"), - request: newRequest("GET", "http://localhost/1/2/3"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: false, - }, - { - title: "PathPrefix route with pattern, match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with pattern, URL prefix in request does not match", - route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - { - title: "PathPrefix route with multiple patterns, match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/222/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: true, - }, - { - title: "PathPrefix route with multiple patterns, URL prefix in request does not match", - route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), - request: newRequest("GET", "http://localhost/111/aaa/333"), - vars: map[string]string{"v1": "111", "v2": "222"}, - host: "", - path: "/111/222", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHostPath(t *testing.T) { - tests := []routeTest{ - { - title: "Host and Path route, match", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Host and Path route, wrong host in request URL", - route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Host and Path route with pattern, match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with pattern, URL in request does not match", - route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "bbb", "v2": "222"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - { - title: "Host and Path route with multiple patterns, match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: true, - }, - { - title: "Host and Path route with multiple patterns, URL in request does not match", - route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), - request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), - vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, - host: "aaa.bbb.ccc", - path: "/111/222/333", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestHeaders(t *testing.T) { - // newRequestHeaders creates a new request with a method, url, and headers - newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - for k, v := range headers { - req.Header.Add(k, v) - } - return req - } - - tests := []routeTest{ - { - title: "Headers route, match", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Headers route, bad header values", - route: new(Route).Headers("foo", "bar", "baz", "ding"), - request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } - -} - -func TestMethods(t *testing.T) { - tests := []routeTest{ - { - title: "Methods route, match GET", - route: new(Route).Methods("GET", "POST"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, match POST", - route: new(Route).Methods("GET", "POST"), - request: newRequest("POST", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Methods route, bad method", - route: new(Route).Methods("GET", "POST"), - request: newRequest("PUT", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestQueries(t *testing.T) { - tests := []routeTest{ - { - title: "Queries route, match", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, match with a query string out of order", - route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route, bad query", - route: new(Route).Queries("foo", "bar", "baz", "ding"), - request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - { - title: "Queries route with pattern, match", - route: new(Route).Queries("foo", "{v1}"), - request: newRequest("GET", "http://localhost?foo=bar"), - vars: map[string]string{"v1": "bar"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with multiple patterns, match", - route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), - request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=10"), - vars: map[string]string{"v1": "10"}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Queries route with regexp pattern, regexp does not match", - route: new(Route).Queries("foo", "{v1:[0-9]+}"), - request: newRequest("GET", "http://localhost?foo=a"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSchemes(t *testing.T) { - tests := []routeTest{ - // Schemes - { - title: "Schemes route, match https", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "https://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, match ftp", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "ftp://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "Schemes route, bad scheme", - route: new(Route).Schemes("https", "ftp"), - request: newRequest("GET", "http://localhost"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - for _, test := range tests { - testRoute(t, test) - } -} - -func TestMatcherFunc(t *testing.T) { - m := func(r *http.Request, m *RouteMatch) bool { - if r.URL.Host == "aaa.bbb.ccc" { - return true - } - return false - } - - tests := []routeTest{ - { - title: "MatchFunc route, match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.bbb.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: true, - }, - { - title: "MatchFunc route, non-match", - route: new(Route).MatcherFunc(m), - request: newRequest("GET", "http://aaa.222.ccc"), - vars: map[string]string{}, - host: "", - path: "", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestBuildVarsFunc(t *testing.T) { - tests := []routeTest{ - { - title: "BuildVarsFunc set on route", - route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "3" - vars["v2"] = "a" - return vars - }), - request: newRequest("GET", "http://localhost/111/2"), - path: "/111/3a", - shouldMatch: true, - }, - { - title: "BuildVarsFunc set on route and parent route", - route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v1"] = "2" - return vars - }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { - vars["v2"] = "b" - return vars - }), - request: newRequest("GET", "http://localhost/1/a"), - path: "/2/b", - shouldMatch: true, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestSubRouter(t *testing.T) { - subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() - subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() - - tests := []routeTest{ - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://aaa.google.com/bbb"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: true, - }, - { - route: subrouter1.Path("/{v2:[a-z]+}"), - request: newRequest("GET", "http://111.google.com/111"), - vars: map[string]string{"v1": "aaa", "v2": "bbb"}, - host: "aaa.google.com", - path: "/bbb", - shouldMatch: false, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: true, - }, - { - route: subrouter2.Path("/baz/{v2}"), - request: newRequest("GET", "http://localhost/foo/bar"), - vars: map[string]string{"v1": "bar", "v2": "ding"}, - host: "", - path: "/foo/bar/baz/ding", - shouldMatch: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -func TestNamedRoutes(t *testing.T) { - r1 := NewRouter() - r1.NewRoute().Name("a") - r1.NewRoute().Name("b") - r1.NewRoute().Name("c") - - r2 := r1.NewRoute().Subrouter() - r2.NewRoute().Name("d") - r2.NewRoute().Name("e") - r2.NewRoute().Name("f") - - r3 := r2.NewRoute().Subrouter() - r3.NewRoute().Name("g") - r3.NewRoute().Name("h") - r3.NewRoute().Name("i") - - if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { - t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) - } else if r1.Get("i") == nil { - t.Errorf("Subroute name not registered") - } -} - -func TestStrictSlash(t *testing.T) { - r := NewRouter() - r.StrictSlash(true) - - tests := []routeTest{ - { - title: "Redirect path without slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path with slash", - route: r.NewRoute().Path("/111/"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111/", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Redirect path with slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111/"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Do not redirect path without slash", - route: r.NewRoute().Path("/111"), - request: newRequest("GET", "http://localhost/111"), - vars: map[string]string{}, - host: "", - path: "/111", - shouldMatch: true, - shouldRedirect: false, - }, - { - title: "Propagate StrictSlash to subrouters", - route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), - request: newRequest("GET", "http://localhost/static/images"), - vars: map[string]string{}, - host: "", - path: "/static/images/", - shouldMatch: true, - shouldRedirect: true, - }, - { - title: "Ignore StrictSlash for path prefix", - route: r.NewRoute().PathPrefix("/static/"), - request: newRequest("GET", "http://localhost/static/logo.png"), - vars: map[string]string{}, - host: "", - path: "/static/", - shouldMatch: true, - shouldRedirect: false, - }, - } - - for _, test := range tests { - testRoute(t, test) - } -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -func getRouteTemplate(route *Route) string { - host, path := "none", "none" - if route.regexp != nil { - if route.regexp.host != nil { - host = route.regexp.host.template - } - if route.regexp.path != nil { - path = route.regexp.path.template - } - } - return fmt.Sprintf("Host: %v, Path: %v", host, path) -} - -func testRoute(t *testing.T, test routeTest) { - request := test.request - route := test.route - vars := test.vars - shouldMatch := test.shouldMatch - host := test.host - path := test.path - url := test.host + test.path - shouldRedirect := test.shouldRedirect - - var match RouteMatch - ok := route.Match(request, &match) - if ok != shouldMatch { - msg := "Should match" - if !shouldMatch { - msg = "Should not match" - } - t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) - return - } - if shouldMatch { - if test.vars != nil && !stringMapEqual(test.vars, match.Vars) { - t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) - return - } - if host != "" { - u, _ := test.route.URLHost(mapToPairs(match.Vars)...) - if host != u.Host { - t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route)) - return - } - } - if path != "" { - u, _ := route.URLPath(mapToPairs(match.Vars)...) - if path != u.Path { - t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route)) - return - } - } - if url != "" { - u, _ := route.URL(mapToPairs(match.Vars)...) - if url != u.Host+u.Path { - t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route)) - return - } - } - if shouldRedirect && match.Handler == nil { - t.Errorf("(%v) Did not redirect", test.title) - return - } - if !shouldRedirect && match.Handler != nil { - t.Errorf("(%v) Unexpected redirect", test.title) - return - } - } -} - -// Tests that the context is cleared or not cleared properly depending on -// the configuration of the router -func TestKeepContext(t *testing.T) { - func1 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - res := new(http.ResponseWriter) - r.ServeHTTP(*res, req) - - if _, ok := context.GetOk(req, "t"); ok { - t.Error("Context should have been cleared at end of request") - } - - r.KeepContext = true - - req, _ = http.NewRequest("GET", "http://localhost/", nil) - context.Set(req, "t", 1) - - r.ServeHTTP(*res, req) - if _, ok := context.GetOk(req, "t"); !ok { - t.Error("Context should NOT have been cleared at end of request") - } - -} - -type TestA301ResponseWriter struct { - hh http.Header - status int -} - -func (ho TestA301ResponseWriter) Header() http.Header { - return http.Header(ho.hh) -} - -func (ho TestA301ResponseWriter) Write(b []byte) (int, error) { - return 0, nil -} - -func (ho TestA301ResponseWriter) WriteHeader(code int) { - ho.status = code -} - -func Test301Redirect(t *testing.T) { - m := make(http.Header) - - func1 := func(w http.ResponseWriter, r *http.Request) {} - func2 := func(w http.ResponseWriter, r *http.Request) {} - - r := NewRouter() - r.HandleFunc("/api/", func2).Name("func2") - r.HandleFunc("/", func1).Name("func1") - - req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) - - res := TestA301ResponseWriter{ - hh: m, - status: 0, - } - r.ServeHTTP(&res, req) - - if "http://localhost/api/?abc=def" != res.hh["Location"][0] { - t.Errorf("Should have complete URL with query string") - } -} - -// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW -func TestSubrouterHeader(t *testing.T) { - expected := "func1 response" - func1 := func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, expected) - } - func2 := func(http.ResponseWriter, *http.Request) {} - - r := NewRouter() - s := r.Headers("SomeSpecialHeader", "").Subrouter() - s.HandleFunc("/", func1).Name("func1") - r.HandleFunc("/", func2).Name("func2") - - req, _ := http.NewRequest("GET", "http://localhost/", nil) - req.Header.Add("SomeSpecialHeader", "foo") - match := new(RouteMatch) - matched := r.Match(req, match) - if !matched { - t.Errorf("Should match request") - } - if match.Route.GetName() != "func1" { - t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) - } - resp := NewRecorder() - match.Handler.ServeHTTP(resp, req) - if resp.Body.String() != expected { - t.Errorf("Expecting %q", expected) - } -} - -// mapToPairs converts a string map to a slice of string pairs -func mapToPairs(m map[string]string) []string { - var i int - p := make([]string, len(m)*2) - for k, v := range m { - p[i] = k - p[i+1] = v - i += 2 - } - return p -} - -// stringMapEqual checks the equality of two string maps -func stringMapEqual(m1, m2 map[string]string) bool { - nil1 := m1 == nil - nil2 := m2 == nil - if nil1 != nil2 || len(m1) != len(m2) { - return false - } - for k, v := range m1 { - if v != m2[k] { - return false - } - } - return true -} - -// newRequest is a helper function to create a new request with a method and url -func newRequest(method, url string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - return req -} diff --git a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go b/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go deleted file mode 100644 index 1f7c190c0f9..00000000000 --- a/Godeps/_workspace/src/github.com/gorilla/mux/old_test.go +++ /dev/null @@ -1,714 +0,0 @@ -// Old tests ported to Go1. This is a mess. Want to drop it one day. - -// Copyright 2011 Gorilla 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 mux - -import ( - "bytes" - "net/http" - "testing" -) - -// ---------------------------------------------------------------------------- -// ResponseRecorder -// ---------------------------------------------------------------------------- -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// ResponseRecorder is an implementation of http.ResponseWriter that -// records its mutations for later inspection in tests. -type ResponseRecorder struct { - Code int // the HTTP response code from WriteHeader - HeaderMap http.Header // the HTTP response headers - Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to - Flushed bool -} - -// NewRecorder returns an initialized ResponseRecorder. -func NewRecorder() *ResponseRecorder { - return &ResponseRecorder{ - HeaderMap: make(http.Header), - Body: new(bytes.Buffer), - } -} - -// DefaultRemoteAddr is the default remote address to return in RemoteAddr if -// an explicit DefaultRemoteAddr isn't set on ResponseRecorder. -const DefaultRemoteAddr = "1.2.3.4" - -// Header returns the response headers. -func (rw *ResponseRecorder) Header() http.Header { - return rw.HeaderMap -} - -// Write always succeeds and writes to rw.Body, if not nil. -func (rw *ResponseRecorder) Write(buf []byte) (int, error) { - if rw.Body != nil { - rw.Body.Write(buf) - } - if rw.Code == 0 { - rw.Code = http.StatusOK - } - return len(buf), nil -} - -// WriteHeader sets rw.Code. -func (rw *ResponseRecorder) WriteHeader(code int) { - rw.Code = code -} - -// Flush sets rw.Flushed to true. -func (rw *ResponseRecorder) Flush() { - rw.Flushed = true -} - -// ---------------------------------------------------------------------------- - -func TestRouteMatchers(t *testing.T) { - var scheme, host, path, query, method string - var headers map[string]string - var resultVars map[bool]map[string]string - - router := NewRouter() - router.NewRoute().Host("{var1}.google.com"). - Path("/{var2:[a-z]+}/{var3:[0-9]+}"). - Queries("foo", "bar"). - Methods("GET"). - Schemes("https"). - Headers("x-requested-with", "XMLHttpRequest") - router.NewRoute().Host("www.{var4}.com"). - PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). - Queries("baz", "ding"). - Methods("POST"). - Schemes("http"). - Headers("Content-Type", "application/json") - - reset := func() { - // Everything match. - scheme = "https" - host = "www.google.com" - path = "/product/42" - query = "?foo=bar" - method = "GET" - headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} - resultVars = map[bool]map[string]string{ - true: {"var1": "www", "var2": "product", "var3": "42"}, - false: {}, - } - } - - reset2 := func() { - // Everything match. - scheme = "http" - host = "www.google.com" - path = "/foo/product/42/path/that/is/ignored" - query = "?baz=ding" - method = "POST" - headers = map[string]string{"Content-Type": "application/json"} - resultVars = map[bool]map[string]string{ - true: {"var4": "google", "var5": "product", "var6": "42"}, - false: {}, - } - } - - match := func(shouldMatch bool) { - url := scheme + "://" + host + path + query - request, _ := http.NewRequest(method, url, nil) - for key, value := range headers { - request.Header.Add(key, value) - } - - var routeMatch RouteMatch - matched := router.Match(request, &routeMatch) - if matched != shouldMatch { - // Need better messages. :) - if matched { - t.Errorf("Should match.") - } else { - t.Errorf("Should not match.") - } - } - - if matched { - currentRoute := routeMatch.Route - if currentRoute == nil { - t.Errorf("Expected a current route.") - } - vars := routeMatch.Vars - expectedVars := resultVars[shouldMatch] - if len(vars) != len(expectedVars) { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - for name, value := range vars { - if expectedVars[name] != value { - t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) - } - } - } - } - - // 1st route -------------------------------------------------------------- - - // Everything match. - reset() - match(true) - - // Scheme doesn't match. - reset() - scheme = "http" - match(false) - - // Host doesn't match. - reset() - host = "www.mygoogle.com" - match(false) - - // Path doesn't match. - reset() - path = "/product/notdigits" - match(false) - - // Query doesn't match. - reset() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset() - method = "POST" - match(false) - - // Header doesn't match. - reset() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset() - match(true) - - // 2nd route -------------------------------------------------------------- - - // Everything match. - reset2() - match(true) - - // Scheme doesn't match. - reset2() - scheme = "https" - match(false) - - // Host doesn't match. - reset2() - host = "sub.google.com" - match(false) - - // Path doesn't match. - reset2() - path = "/bar/product/42" - match(false) - - // Query doesn't match. - reset2() - query = "?foo=baz" - match(false) - - // Method doesn't match. - reset2() - method = "GET" - match(false) - - // Header doesn't match. - reset2() - headers = map[string]string{} - match(false) - - // Everything match, again. - reset2() - match(true) -} - -type headerMatcherTest struct { - matcher headerMatcher - headers map[string]string - result bool -} - -var headerMatcherTests = []headerMatcherTest{ - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": ""}), - headers: map[string]string{"X-Requested-With": "anything"}, - result: true, - }, - { - matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), - headers: map[string]string{}, - result: false, - }, -} - -type hostMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var hostMatcherTests = []hostMatcherTest{ - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://abc.def.ghi/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), - url: "http://a.b.c/", - vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, - result: false, - }, -} - -type methodMatcherTest struct { - matcher methodMatcher - method string - result bool -} - -var methodMatcherTests = []methodMatcherTest{ - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "GET", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "POST", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "PUT", - result: true, - }, - { - matcher: methodMatcher([]string{"GET", "POST", "PUT"}), - method: "DELETE", - result: false, - }, -} - -type pathMatcherTest struct { - matcher *Route - url string - vars map[string]string - result bool -} - -var pathMatcherTests = []pathMatcherTest{ - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/123/456/789", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: true, - }, - { - matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), - url: "http://localhost:8080/1/2/3", - vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, - result: false, - }, -} - -type schemeMatcherTest struct { - matcher schemeMatcher - url string - result bool -} - -var schemeMatcherTests = []schemeMatcherTest{ - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "http://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"http", "https"}), - url: "https://localhost:8080/", - result: true, - }, - { - matcher: schemeMatcher([]string{"https"}), - url: "http://localhost:8080/", - result: false, - }, - { - matcher: schemeMatcher([]string{"http"}), - url: "https://localhost:8080/", - result: false, - }, -} - -type urlBuildingTest struct { - route *Route - vars []string - url string -} - -var urlBuildingTests = []urlBuildingTest{ - { - route: new(Route).Host("foo.domain.com"), - vars: []string{}, - url: "http://foo.domain.com", - }, - { - route: new(Route).Host("{subdomain}.domain.com"), - vars: []string{"subdomain", "bar"}, - url: "http://bar.domain.com", - }, - { - route: new(Route).Host("foo.domain.com").Path("/articles"), - vars: []string{}, - url: "http://foo.domain.com/articles", - }, - { - route: new(Route).Path("/articles"), - vars: []string{}, - url: "/articles", - }, - { - route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"category", "technology", "id", "42"}, - url: "/articles/technology/42", - }, - { - route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), - vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, - url: "http://foo.domain.com/articles/technology/42", - }, -} - -func TestHeaderMatcher(t *testing.T) { - for _, v := range headerMatcherTests { - request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - for key, value := range v.headers { - request.Header.Add(key, value) - } - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, request.Header) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, request.Header) - } - } - } -} - -func TestHostMatcher(t *testing.T) { - for _, v := range hostMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestMethodMatcher(t *testing.T) { - for _, v := range methodMatcherTests { - request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.method) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.method) - } - } - } -} - -func TestPathMatcher(t *testing.T) { - for _, v := range pathMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - vars := routeMatch.Vars - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - if result { - if len(vars) != len(v.vars) { - t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) - } - for name, value := range vars { - if v.vars[name] != value { - t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) - } - } - } else { - if len(vars) != 0 { - t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) - } - } - } -} - -func TestSchemeMatcher(t *testing.T) { - for _, v := range schemeMatcherTests { - request, _ := http.NewRequest("GET", v.url, nil) - var routeMatch RouteMatch - result := v.matcher.Match(request, &routeMatch) - if result != v.result { - if v.result { - t.Errorf("%#v: should match %v.", v.matcher, v.url) - } else { - t.Errorf("%#v: should not match %v.", v.matcher, v.url) - } - } - } -} - -func TestUrlBuilding(t *testing.T) { - - for _, v := range urlBuildingTests { - u, _ := v.route.URL(v.vars...) - url := u.String() - if url != v.url { - t.Errorf("expected %v, got %v", v.url, url) - /* - reversePath := "" - reverseHost := "" - if v.route.pathTemplate != nil { - reversePath = v.route.pathTemplate.Reverse - } - if v.route.hostTemplate != nil { - reverseHost = v.route.hostTemplate.Reverse - } - - t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) - */ - } - } - - ArticleHandler := func(w http.ResponseWriter, r *http.Request) { - } - - router := NewRouter() - router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") - - url, _ := router.Get("article").URL("category", "technology", "id", "42") - expected := "/articles/technology/42" - if url.String() != expected { - t.Errorf("Expected %v, got %v", expected, url.String()) - } -} - -func TestMatchedRouteName(t *testing.T) { - routeName := "stock" - router := NewRouter() - route := router.NewRoute().Path("/products/").Name(routeName) - - url := "http://www.domain.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - retName := rv.Route.GetName() - if retName != routeName { - t.Errorf("Expected %q, got %q.", routeName, retName) - } -} - -func TestSubRouting(t *testing.T) { - // Example from docs. - router := NewRouter() - subrouter := router.NewRoute().Host("www.domain.com").Subrouter() - route := subrouter.NewRoute().Path("/products/").Name("products") - - url := "http://www.domain.com/products/" - request, _ := http.NewRequest("GET", url, nil) - var rv RouteMatch - ok := router.Match(request, &rv) - - if !ok || rv.Route != route { - t.Errorf("Expected same route, got %+v.", rv.Route) - } - - u, _ := router.Get("products").URL() - builtUrl := u.String() - // Yay, subroute aware of the domain when building! - if builtUrl != url { - t.Errorf("Expected %q, got %q.", url, builtUrl) - } -} - -func TestVariableNames(t *testing.T) { - route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") - if route.err == nil { - t.Errorf("Expected error for duplicated variable names") - } -} - -func TestRedirectSlash(t *testing.T) { - var route *Route - var routeMatch RouteMatch - r := NewRouter() - - r.StrictSlash(false) - route = r.NewRoute() - if route.strictSlash != false { - t.Errorf("Expected false redirectSlash.") - } - - r.StrictSlash(true) - route = r.NewRoute() - if route.strictSlash != true { - t.Errorf("Expected true redirectSlash.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}/") - request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars := routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp := NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { - t.Errorf("Expected redirect header.") - } - - route = new(Route) - route.strictSlash = true - route.Path("/{arg1}/{arg2:[0-9]+}") - request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) - routeMatch = RouteMatch{} - _ = route.Match(request, &routeMatch) - vars = routeMatch.Vars - if vars["arg1"] != "foo" { - t.Errorf("Expected foo.") - } - if vars["arg2"] != "123" { - t.Errorf("Expected 123.") - } - rsp = NewRecorder() - routeMatch.Handler.ServeHTTP(rsp, request) - if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { - t.Errorf("Expected redirect header.") - } -} - -// Test for the new regexp library, still not available in stable Go. -func TestNewRegexp(t *testing.T) { - var p *routeRegexp - var matches []string - - tests := map[string]map[string][]string{ - "/{foo:a{2}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": nil, - "/aaaa": nil, - }, - "/{foo:a{2,}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": {"aaaa"}, - }, - "/{foo:a{2,3}}": { - "/a": nil, - "/aa": {"aa"}, - "/aaa": {"aaa"}, - "/aaaa": nil, - }, - "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abcd": nil, - "/abc/ab": {"abc", "ab"}, - "/abc/abc": nil, - "/abcd/ab": nil, - }, - `/{foo:\w{3,}}/{bar:\d{2,}}`: { - "/a": nil, - "/ab": nil, - "/abc": nil, - "/abc/1": nil, - "/abc/12": {"abc", "12"}, - "/abcd/12": {"abcd", "12"}, - "/abcd/123": {"abcd", "123"}, - }, - } - - for pattern, paths := range tests { - p, _ = newRouteRegexp(pattern, false, false, false, false) - for path, result := range paths { - matches = p.regexp.FindStringSubmatch(path) - if result == nil { - if matches != nil { - t.Errorf("%v should not match %v.", pattern, path) - } - } else { - if len(matches) != len(result)+1 { - t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) - } else { - for k, v := range result { - if matches[k+1] != v { - t.Errorf("Expected %v, got %v.", v, matches[k+1]) - } - } - } - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go b/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go deleted file mode 100644 index 072bddb7925..00000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/mergo_test.go +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package mergo - -import ( - "gopkg.in/yaml.v1" - "io/ioutil" - "reflect" - "testing" -) - -type simpleTest struct { - Value int -} - -type complexTest struct { - St simpleTest - sz int - Id string -} - -type moreComplextText struct { - Ct complexTest - St simpleTest - Nt simpleTest -} - -type pointerTest struct { - C *simpleTest -} - -type sliceTest struct { - S []int -} - -func TestNil(t *testing.T) { - if err := Merge(nil, nil); err != ErrNilArguments { - t.Fail() - } -} - -func TestDifferentTypes(t *testing.T) { - a := simpleTest{42} - b := 42 - if err := Merge(&a, b); err != ErrDifferentArgumentsTypes { - t.Fail() - } -} - -func TestSimpleStruct(t *testing.T) { - a := simpleTest{} - b := simpleTest{42} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestComplexStruct(t *testing.T) { - a := complexTest{} - a.Id = "athing" - b := complexTest{simpleTest{42}, 1, "bthing"} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.St.Value != 42 { - t.Fatalf("b not merged in a properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value) - } - if a.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz) - } - if a.Id != b.Id { - t.Fatalf("a's field Id not merged properly: a.Id(%s) != b.Id(%s)", a.Id, b.Id) - } -} - -func TestPointerStruct(t *testing.T) { - s1 := simpleTest{} - s2 := simpleTest{19} - a := pointerTest{&s1} - b := pointerTest{&s2} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - //t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestPointerStructNil(t *testing.T) { - a := pointerTest{nil} - b := pointerTest{&simpleTest{19}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestSliceStruct(t *testing.T) { - a := sliceTest{} - b := sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) - } - - a = sliceTest{[]int{1}} - b = sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) - } -} - -func TestMaps(t *testing.T) { - m := map[string]simpleTest{ - "a": simpleTest{}, - "b": simpleTest{42}, - } - n := map[string]simpleTest{ - "a": simpleTest{16}, - "b": simpleTest{}, - "c": simpleTest{12}, - } - if err := Merge(&m, n); err != nil { - t.Fatalf(err.Error()) - } - if len(m) != 3 { - t.Fatalf(`n not merged in m properly, m must have 3 elements instead of %d`, len(m)) - } - if m["a"].Value != 0 { - t.Fatalf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value) - } - if m["b"].Value != 42 { - t.Fatalf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value) - } - if m["c"].Value != 12 { - t.Fatalf(`n not merged in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value) - } -} - -func TestYAMLMaps(t *testing.T) { - thing := loadYAML("testdata/thing.yml") - license := loadYAML("testdata/license.yml") - ft := thing["fields"].(map[interface{}]interface{}) - fl := license["fields"].(map[interface{}]interface{}) - expectedLength := len(ft) + len(fl) - if err := Merge(&license, thing); err != nil { - t.Fatal(err.Error()) - } - currentLength := len(license["fields"].(map[interface{}]interface{})) - if currentLength != expectedLength { - t.Fatalf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength) - } - fields := license["fields"].(map[interface{}]interface{}) - if _, ok := fields["id"]; !ok { - t.Fatalf(`thing not merged in license properly, license must have a new id field from thing`) - } -} - -func TestTwoPointerValues(t *testing.T) { - a := &simpleTest{} - b := &simpleTest{42} - if err := Merge(a, b); err != nil { - t.Fatalf(`Boom. You crossed the streams: %s`, err) - } -} - -func TestMap(t *testing.T) { - a := complexTest{} - a.Id = "athing" - c := moreComplextText{a, simpleTest{}, simpleTest{}} - b := map[string]interface{}{ - "ct": map[string]interface{}{ - "st": map[string]interface{}{ - "value": 42, - }, - "sz": 1, - "id": "bthing", - }, - "st": &simpleTest{144}, // Mapping a reference - "zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist) - "nt": simpleTest{3}, - } - if err := Map(&c, b); err != nil { - t.FailNow() - } - m := b["ct"].(map[string]interface{}) - n := m["st"].(map[string]interface{}) - o := b["st"].(*simpleTest) - p := b["nt"].(simpleTest) - if c.Ct.St.Value != 42 { - t.Fatalf("b not merged in a properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"]) - } - if c.St.Value != 144 { - t.Fatalf("b not merged in a properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value) - } - if c.Nt.Value != 3 { - t.Fatalf("b not merged in a properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value) - } - if c.Ct.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"]) - } - if c.Ct.Id != m["id"] { - t.Fatalf("a's field Id not merged properly: c.Ct.Id(%s) != b.Ct.Id(%s)", c.Ct.Id, m["id"]) - } -} - -func TestSimpleMap(t *testing.T) { - a := simpleTest{} - b := map[string]interface{}{ - "value": 42, - } - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"]) - } -} - -type pointerMapTest struct { - A int - hidden int - B *simpleTest -} - -func TestBackAndForth(t *testing.T) { - pt := pointerMapTest{42, 1, &simpleTest{66}} - m := make(map[string]interface{}) - if err := Map(&m, pt); err != nil { - t.FailNow() - } - var ( - v interface{} - ok bool - ) - if v, ok = m["a"]; v.(int) != pt.A || !ok { - t.Fatalf("pt not merged properly: m[`a`](%d) != pt.A(%d)", v, pt.A) - } - if v, ok = m["b"]; !ok { - t.Fatalf("pt not merged properly: B is missing in m") - } - var st *simpleTest - if st = v.(*simpleTest); st.Value != 66 { - t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") - } - bpt := pointerMapTest{} - if err := Map(&bpt, m); err != nil { - t.Fatal(err) - } - if bpt.A != pt.A { - t.Fatalf("pt not merged properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) - } - if bpt.hidden == pt.hidden { - t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) - } - if bpt.B.Value != pt.B.Value { - t.Fatalf("pt not merged properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) - } -} - -func loadYAML(path string) (m map[string]interface{}) { - m = make(map[string]interface{}) - raw, _ := ioutil.ReadFile(path) - _ = yaml.Unmarshal(raw, &m) - return -} diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml b/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml deleted file mode 100644 index 62fdb61ec32..00000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/license.yml +++ /dev/null @@ -1,3 +0,0 @@ -import: ../../../../fossene/db/schema/thing.yml -fields: - site: string diff --git a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml b/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml deleted file mode 100644 index c28eab0d058..00000000000 --- a/Godeps/_workspace/src/github.com/imdario/mergo/testdata/thing.yml +++ /dev/null @@ -1,5 +0,0 @@ -fields: - id: int - name: string - parent: ref "datu:thing" - status: enum(draft, public, private) diff --git a/Godeps/_workspace/src/github.com/jonboulle/clockwork/clockwork_test.go b/Godeps/_workspace/src/github.com/jonboulle/clockwork/clockwork_test.go deleted file mode 100644 index dcf49002fdf..00000000000 --- a/Godeps/_workspace/src/github.com/jonboulle/clockwork/clockwork_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package clockwork - -import ( - "reflect" - "testing" - "time" -) - -func TestFakeClockAfter(t *testing.T) { - fc := &fakeClock{} - - zero := fc.After(0) - select { - case <-zero: - default: - t.Errorf("zero did not return!") - } - one := fc.After(1) - two := fc.After(2) - six := fc.After(6) - ten := fc.After(10) - fc.Advance(1) - select { - case <-one: - default: - t.Errorf("one did not return!") - } - select { - case <-two: - t.Errorf("two returned prematurely!") - case <-six: - t.Errorf("six returned prematurely!") - case <-ten: - t.Errorf("ten returned prematurely!") - default: - } - fc.Advance(1) - select { - case <-two: - default: - t.Errorf("two did not return!") - } - select { - case <-six: - t.Errorf("six returned prematurely!") - case <-ten: - t.Errorf("ten returned prematurely!") - default: - } - fc.Advance(1) - select { - case <-six: - t.Errorf("six returned prematurely!") - case <-ten: - t.Errorf("ten returned prematurely!") - default: - } - fc.Advance(3) - select { - case <-six: - default: - t.Errorf("six did not return!") - } - select { - case <-ten: - t.Errorf("ten returned prematurely!") - default: - } - fc.Advance(100) - select { - case <-ten: - default: - t.Errorf("ten did not return!") - } -} - -func TestNotifyBlockers(t *testing.T) { - b1 := &blocker{1, make(chan struct{})} - b2 := &blocker{2, make(chan struct{})} - b3 := &blocker{5, make(chan struct{})} - b4 := &blocker{10, make(chan struct{})} - b5 := &blocker{10, make(chan struct{})} - bs := []*blocker{b1, b2, b3, b4, b5} - bs1 := notifyBlockers(bs, 2) - if n := len(bs1); n != 4 { - t.Fatalf("got %d blockers, want %d", n, 4) - } - select { - case <-b2.ch: - case <-time.After(time.Second): - t.Fatalf("timed out waiting for channel close!") - } - bs2 := notifyBlockers(bs1, 10) - if n := len(bs2); n != 2 { - t.Fatalf("got %d blockers, want %d", n, 2) - } - select { - case <-b4.ch: - case <-time.After(time.Second): - t.Fatalf("timed out waiting for channel close!") - } - select { - case <-b5.ch: - case <-time.After(time.Second): - t.Fatalf("timed out waiting for channel close!") - } -} - -func TestNewFakeClock(t *testing.T) { - fc := NewFakeClock() - now := fc.Now() - if now.IsZero() { - t.Fatalf("fakeClock.Now() fulfills IsZero") - } - - now2 := fc.Now() - if !reflect.DeepEqual(now, now2) { - t.Fatalf("fakeClock.Now() returned different value: want=%#v got=%#v", now, now2) - } -} diff --git a/Godeps/_workspace/src/github.com/jonboulle/clockwork/example_test.go b/Godeps/_workspace/src/github.com/jonboulle/clockwork/example_test.go deleted file mode 100644 index 6a41bd86bf8..00000000000 --- a/Godeps/_workspace/src/github.com/jonboulle/clockwork/example_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package clockwork - -import ( - "sync" - "testing" - "time" -) - -// my_func is an example of a time-dependent function, using an -// injected clock -func my_func(clock Clock, i *int) { - clock.Sleep(3 * time.Second) - *i += 1 -} - -// assert_state is an example of a state assertion in a test -func assert_state(t *testing.T, i, j int) { - if i != j { - t.Fatalf("i %d, j %d", i, j) - } -} - -// TestMyFunc tests my_func's behaviour with a FakeClock -func TestMyFunc(t *testing.T) { - var i int - c := NewFakeClock() - - var wg sync.WaitGroup - wg.Add(1) - go func() { - my_func(c, &i) - wg.Done() - }() - - // Wait until my_func is actually sleeping on the clock - c.BlockUntil(1) - - // Assert the initial state - assert_state(t, i, 0) - - // Now advance the clock forward in time - c.Advance(1 * time.Hour) - - // Wait until the function completes - wg.Wait() - - // Assert the final state - assert_state(t, i, 1) -} diff --git a/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go b/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go deleted file mode 100644 index 9438a66e3e4..00000000000 --- a/Godeps/_workspace/src/github.com/juju/ratelimit/ratelimit_test.go +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright 2014 Canonical Ltd. -// Licensed under the LGPLv3 with static-linking exception. -// See LICENCE file for details. - -package ratelimit - -import ( - gc "launchpad.net/gocheck" - - "testing" - "time" -) - -func TestPackage(t *testing.T) { - gc.TestingT(t) -} - -type rateLimitSuite struct{} - -var _ = gc.Suite(rateLimitSuite{}) - -type takeReq struct { - time time.Duration - count int64 - expectWait time.Duration -} - -var takeTests = []struct { - about string - fillInterval time.Duration - capacity int64 - reqs []takeReq -}{{ - about: "serial requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 0, - expectWait: 0, - }, { - time: 0, - count: 10, - expectWait: 0, - }, { - time: 0, - count: 1, - expectWait: 250 * time.Millisecond, - }, { - time: 250 * time.Millisecond, - count: 1, - expectWait: 250 * time.Millisecond, - }}, -}, { - about: "concurrent requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 0, - count: 2, - expectWait: 500 * time.Millisecond, - }, { - time: 0, - count: 2, - expectWait: 1000 * time.Millisecond, - }, { - time: 0, - count: 1, - expectWait: 1250 * time.Millisecond, - }}, -}, { - about: "more than capacity", - fillInterval: 1 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 20 * time.Millisecond, - count: 15, - expectWait: 5 * time.Millisecond, - }}, -}, { - about: "sub-quantum time", - fillInterval: 10 * time.Millisecond, - capacity: 10, - reqs: []takeReq{{ - time: 0, - count: 10, - expectWait: 0, - }, { - time: 7 * time.Millisecond, - count: 1, - expectWait: 3 * time.Millisecond, - }, { - time: 8 * time.Millisecond, - count: 1, - expectWait: 12 * time.Millisecond, - }}, -}, { - about: "within capacity", - fillInterval: 10 * time.Millisecond, - capacity: 5, - reqs: []takeReq{{ - time: 0, - count: 5, - expectWait: 0, - }, { - time: 60 * time.Millisecond, - count: 5, - expectWait: 0, - }, { - time: 60 * time.Millisecond, - count: 1, - expectWait: 10 * time.Millisecond, - }, { - time: 80 * time.Millisecond, - count: 2, - expectWait: 10 * time.Millisecond, - }}, -}} - -func (rateLimitSuite) TestTake(c *gc.C) { - for i, test := range takeTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - d, ok := tb.take(tb.startTime.Add(req.time), req.count, infinityDuration) - c.Assert(ok, gc.Equals, true) - if d != req.expectWait { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) - } - } - } -} - -func (rateLimitSuite) TestTakeMaxDuration(c *gc.C) { - for i, test := range takeTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - if req.expectWait > 0 { - d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait-1) - c.Assert(ok, gc.Equals, false) - c.Assert(d, gc.Equals, time.Duration(0)) - } - d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait) - c.Assert(ok, gc.Equals, true) - if d != req.expectWait { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) - } - } - } -} - -type takeAvailableReq struct { - time time.Duration - count int64 - expect int64 -} - -var takeAvailableTests = []struct { - about string - fillInterval time.Duration - capacity int64 - reqs []takeAvailableReq -}{{ - about: "serial requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 0, - expect: 0, - }, { - time: 0, - count: 10, - expect: 10, - }, { - time: 0, - count: 1, - expect: 0, - }, { - time: 250 * time.Millisecond, - count: 1, - expect: 1, - }}, -}, { - about: "concurrent requests", - fillInterval: 250 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 5, - expect: 5, - }, { - time: 0, - count: 2, - expect: 2, - }, { - time: 0, - count: 5, - expect: 3, - }, { - time: 0, - count: 1, - expect: 0, - }}, -}, { - about: "more than capacity", - fillInterval: 1 * time.Millisecond, - capacity: 10, - reqs: []takeAvailableReq{{ - time: 0, - count: 10, - expect: 10, - }, { - time: 20 * time.Millisecond, - count: 15, - expect: 10, - }}, -}, { - about: "within capacity", - fillInterval: 10 * time.Millisecond, - capacity: 5, - reqs: []takeAvailableReq{{ - time: 0, - count: 5, - expect: 5, - }, { - time: 60 * time.Millisecond, - count: 5, - expect: 5, - }, { - time: 70 * time.Millisecond, - count: 1, - expect: 1, - }}, -}} - -func (rateLimitSuite) TestTakeAvailable(c *gc.C) { - for i, test := range takeAvailableTests { - tb := NewBucket(test.fillInterval, test.capacity) - for j, req := range test.reqs { - d := tb.takeAvailable(tb.startTime.Add(req.time), req.count) - if d != req.expect { - c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expect) - } - } - } -} - -func (rateLimitSuite) TestPanics(c *gc.C) { - c.Assert(func() { NewBucket(0, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") - c.Assert(func() { NewBucket(-2, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") - c.Assert(func() { NewBucket(1, 0) }, gc.PanicMatches, "token bucket capacity is not > 0") - c.Assert(func() { NewBucket(1, -2) }, gc.PanicMatches, "token bucket capacity is not > 0") -} - -func isCloseTo(x, y, tolerance float64) bool { - return abs(x-y)/y < tolerance -} - -func (rateLimitSuite) TestRate(c *gc.C) { - tb := NewBucket(1, 1) - if !isCloseTo(tb.Rate(), 1e9, 0.00001) { - c.Fatalf("got %v want 1e9", tb.Rate()) - } - tb = NewBucket(2*time.Second, 1) - if !isCloseTo(tb.Rate(), 0.5, 0.00001) { - c.Fatalf("got %v want 0.5", tb.Rate()) - } - tb = NewBucketWithQuantum(100*time.Millisecond, 1, 5) - if !isCloseTo(tb.Rate(), 50, 0.00001) { - c.Fatalf("got %v want 50", tb.Rate()) - } -} - -func checkRate(c *gc.C, rate float64) { - tb := NewBucketWithRate(rate, 1<<62) - if !isCloseTo(tb.Rate(), rate, rateMargin) { - c.Fatalf("got %g want %v", tb.Rate(), rate) - } - d, ok := tb.take(tb.startTime, 1<<62, infinityDuration) - c.Assert(ok, gc.Equals, true) - c.Assert(d, gc.Equals, time.Duration(0)) - - // Check that the actual rate is as expected by - // asking for a not-quite multiple of the bucket's - // quantum and checking that the wait time - // correct. - d, ok = tb.take(tb.startTime, tb.quantum*2-tb.quantum/2, infinityDuration) - c.Assert(ok, gc.Equals, true) - expectTime := 1e9 * float64(tb.quantum) * 2 / rate - if !isCloseTo(float64(d), expectTime, rateMargin) { - c.Fatalf("rate %g: got %g want %v", rate, float64(d), expectTime) - } -} - -func (rateLimitSuite) TestNewWithRate(c *gc.C) { - for rate := float64(1); rate < 1e6; rate += 7 { - checkRate(c, rate) - } - for _, rate := range []float64{ - 1024 * 1024 * 1024, - 1e-5, - 0.9e-5, - 0.5, - 0.9, - 0.9e8, - 3e12, - 4e18, - } { - checkRate(c, rate) - checkRate(c, rate/3) - checkRate(c, rate*1.3) - } -} - -func BenchmarkWait(b *testing.B) { - tb := NewBucket(1, 16*1024) - for i := b.N - 1; i >= 0; i-- { - tb.Wait(1) - } -} 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 5aafa3af2d2..00000000000 --- a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go +++ /dev/null @@ -1,180 +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 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/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go deleted file mode 100644 index 094156e66c5..00000000000 --- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// 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 pbutil - -import ( - "bytes" - "math/rand" - "reflect" - "testing" - "testing/quick" - - "github.com/matttproud/golang_protobuf_extensions/pbtest" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -func TestWriteDelimited(t *testing.T) { - for _, test := range []struct { - msg Message - buf []byte - n int - err error - }{ - { - msg: &Empty{}, - n: 1, - buf: []byte{0}, - }, - { - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - n: 3, - buf: []byte{2, 8, 1}, - }, - { - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - }, - } { - var buf bytes.Buffer - if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err { - t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err) - } - if out := buf.Bytes(); !bytes.Equal(out, test.buf) { - t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf) - } - } -} - -func TestReadDelimited(t *testing.T) { - for _, test := range []struct { - buf []byte - msg Message - n int - err error - }{ - { - buf: []byte{0}, - msg: &Empty{}, - n: 1, - }, - { - n: 3, - buf: []byte{2, 8, 1}, - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - }, - { - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - }, - } { - msg := Clone(test.msg) - msg.Reset() - if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err { - t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err) - } - if !Equal(msg, test.msg) { - t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg) - } - } -} - -func TestEndToEndValid(t *testing.T) { - for _, test := range [][]Message{ - {&Empty{}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}}, - {&Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }}, - } { - var buf bytes.Buffer - var written int - for i, msg := range test { - n, err := WriteDelimited(&buf, msg) - if err != nil { - // Assumption: TestReadDelimited and TestWriteDelimited are sufficient - // and inputs for this test are explicitly exercised there. - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err) - } - written += n - } - var read int - for i, msg := range test { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - // Decide to do EOF checking? - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", test, read, written) - } - } -} - -// rndMessage generates a random valid Protocol Buffer message. -func rndMessage(r *rand.Rand) Message { - var t reflect.Type - switch v := rand.Intn(23); v { - // TODO(br): Uncomment the elements below once fix is incorporated, except - // for the elements marked as patently incompatible. - // case 0: - // t = reflect.TypeOf(&GoEnum{}) - // break - // case 1: - // t = reflect.TypeOf(&GoTestField{}) - // break - case 2: - t = reflect.TypeOf(&GoTest{}) - break - // case 3: - // t = reflect.TypeOf(&GoSkipTest{}) - // break - // case 4: - // t = reflect.TypeOf(&NonPackedTest{}) - // break - // case 5: - // t = reflect.TypeOf(&PackedTest{}) - // break - case 6: - t = reflect.TypeOf(&MaxTag{}) - break - case 7: - t = reflect.TypeOf(&OldMessage{}) - break - case 8: - t = reflect.TypeOf(&NewMessage{}) - break - case 9: - t = reflect.TypeOf(&InnerMessage{}) - break - case 10: - t = reflect.TypeOf(&OtherMessage{}) - break - case 11: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessage{}) - break - // case 12: - // t = reflect.TypeOf(&Ext{}) - // break - case 13: - // PATENTLY INVALID FOR FUZZ GENERATION - // t = reflect.TypeOf(&MyMessageSet{}) - break - // case 14: - // t = reflect.TypeOf(&Empty{}) - // break - // case 15: - // t = reflect.TypeOf(&MessageList{}) - // break - // case 16: - // t = reflect.TypeOf(&Strings{}) - // break - // case 17: - // t = reflect.TypeOf(&Defaults{}) - // break - // case 17: - // t = reflect.TypeOf(&SubDefaults{}) - // break - // case 18: - // t = reflect.TypeOf(&RepeatedEnum{}) - // break - case 19: - t = reflect.TypeOf(&MoreRepeated{}) - break - // case 20: - // t = reflect.TypeOf(&GroupOld{}) - // break - // case 21: - // t = reflect.TypeOf(&GroupNew{}) - // break - case 22: - t = reflect.TypeOf(&FloatingPoint{}) - break - default: - // TODO(br): Replace with an unreachable once fixed. - t = reflect.TypeOf(&GoTest{}) - break - } - if t == nil { - t = reflect.TypeOf(&GoTest{}) - } - v, ok := quick.Value(t, r) - if !ok { - panic("attempt to generate illegal item; consult item 11") - } - if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil { - panic(err) - } - return v.Interface().(Message) -} - -// rndMessages generates several random Protocol Buffer messages. -func rndMessages(r *rand.Rand) []Message { - n := r.Intn(128) - out := make([]Message, 0, n) - for i := 0; i < n; i++ { - out = append(out, rndMessage(r)) - } - return out -} - -func TestFuzz(t *testing.T) { - rnd := rand.New(rand.NewSource(42)) - check := func() bool { - messages := rndMessages(rnd) - var buf bytes.Buffer - var written int - for i, msg := range messages { - n, err := WriteDelimited(&buf, msg) - if err != nil { - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err) - } - written += n - } - var read int - for i, msg := range messages { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", messages, read, written) - } - return true - } - if err := quick.Check(check, nil); err != nil { - t.Fatal(err) - } -} diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go deleted file mode 100644 index d6d9b25594f..00000000000 --- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// http://github.com/golang/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package pbutil - -import ( - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go. - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/auth/sasl/authenticatee_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/auth/sasl/authenticatee_test.go deleted file mode 100644 index 366e1de77da..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/auth/sasl/authenticatee_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package sasl - -import ( - "testing" - "time" - - "github.com/gogo/protobuf/proto" - "github.com/mesos/mesos-go/auth/callback" - "github.com/mesos/mesos-go/auth/sasl/mech/crammd5" - mesos "github.com/mesos/mesos-go/mesosproto" - "github.com/mesos/mesos-go/messenger" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "golang.org/x/net/context" -) - -type MockTransport struct { - *messenger.MockedMessenger -} - -func (m *MockTransport) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { - return m.Called(mock.Anything, upid, msg).Error(0) -} - -func TestAuthticatee_validLogin(t *testing.T) { - assert := assert.New(t) - ctx := context.TODO() - client := upid.UPID{ - ID: "someFramework", - Host: "b.net", - Port: "789", - } - server := upid.UPID{ - ID: "serv", - Host: "a.com", - Port: "123", - } - tpid := upid.UPID{ - ID: "sasl_transport", - Host: "g.org", - Port: "456", - } - handler := callback.HandlerFunc(func(cb ...callback.Interface) error { - for _, c := range cb { - switch c := c.(type) { - case *callback.Name: - c.Set("foo") - case *callback.Password: - c.Set([]byte("bar")) - case *callback.Interprocess: - c.Set(server, client) - default: - return &callback.Unsupported{Callback: c} - } - } - return nil - }) - var transport *MockTransport - factory := transportFactoryFunc(func() messenger.Messenger { - transport = &MockTransport{messenger.NewMockedMessenger()} - transport.On("Install").Return(nil) - transport.On("UPID").Return(tpid) - transport.On("Start").Return(nil) - transport.On("Stop").Return(nil) - - mechMsg := make(chan struct{}) - stepMsg := make(chan struct{}) - - transport.On("Send", mock.Anything, &server, &mesos.AuthenticateMessage{ - Pid: proto.String(client.String()), - }).Return(nil).Run(func(_ mock.Arguments) { - defer close(mechMsg) - transport.Recv(&server, &mesos.AuthenticationMechanismsMessage{ - Mechanisms: []string{crammd5.Name}, - }) - }).Once() - - transport.On("Send", mock.Anything, &server, &mesos.AuthenticationStartMessage{ - Mechanism: proto.String(crammd5.Name), - }).Return(nil).Run(func(_ mock.Arguments) { - defer close(stepMsg) - <-mechMsg - transport.Recv(&server, &mesos.AuthenticationStepMessage{ - Data: []byte(`lsd;lfkgjs;dlfkgjs;dfklg`), - }) - }).Once() - - transport.On("Send", mock.Anything, &server, &mesos.AuthenticationStepMessage{ - Data: []byte(`foo cc7fd96cd80123ea844a7dba29a594ed`), - }).Return(nil).Run(func(_ mock.Arguments) { - <-stepMsg - transport.Recv(&server, &mesos.AuthenticationCompletedMessage{}) - }).Once() - - return transport - }) - login, err := makeAuthenticatee(handler, factory) - assert.Nil(err) - - err = login.Authenticate(ctx, handler) - assert.Nil(err) - assert.NotNil(transport) - time.Sleep(1 * time.Second) // wait for the authenticator to shut down - transport.AssertExpectations(t) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/factory_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/factory_test.go deleted file mode 100644 index 98dbb95bc37..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/factory_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package detector - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type testDetector string - -func (d testDetector) Start() error { return nil } -func (d testDetector) Detect(f MasterChanged) error { return nil } - -func (d testDetector) Done() <-chan struct{} { return make(<-chan struct{}) } -func (d testDetector) Cancel() {} - -// unregister a factory plugin according to its prefix. -// this is part of the testing module on purpose: during normal execution there -// should be no need to dynamically unregister plugins. -func Unregister(prefix string) { - pluginLock.Lock() - defer pluginLock.Unlock() - delete(plugins, prefix) -} - -func TestDetectorFactoryRegister(t *testing.T) { - prefix := "bbm:" - Register(prefix, func(spec string) (Master, error) { - return testDetector("Hello!"), nil - }) - defer Unregister(prefix) - - f, ok := MatchingPlugin(prefix) - - assert.True(t, ok) - assert.NotNil(t, f) -} - -func TestDectorFactoryNew_EmptySpec(t *testing.T) { - assert := assert.New(t) - m, err := New("") - assert.NotNil(err) - assert.Nil(m) -} - -func TestDectorFactoryNew_InvalidSpec(t *testing.T) { - assert := assert.New(t) - m, err := New("localhost") - assert.NotNil(err) - assert.Nil(m) -} - -func TestDectorFactoryNew_TrivialSpec(t *testing.T) { - assert := assert.New(t) - m, err := New("localhost:1") - assert.NoError(err) - assert.NotNil(m) - assert.IsType(&Standalone{}, m) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/standalone_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/standalone_test.go deleted file mode 100644 index d8879fabe02..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/standalone_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package detector - -import ( - "sync" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - mesos "github.com/mesos/mesos-go/mesosproto" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" - "golang.org/x/net/context" -) - -const ( - localhost = uint32(2130706433) // packed uint32 for 127.0.0.1 IPv4 -) - -func TestStandalone_nil(t *testing.T) { - d := NewStandalone(nil) - select { - case <-d.Done(): // expected - t.Fatalf("expected detector to stay alive since we haven't done anything with it") - case <-time.After(500 * time.Millisecond): - } - d.Detect(nil) - select { - case <-d.Done(): // expected - case <-time.After(1 * time.Second): - t.Fatalf("expected detector to shutdown since it has no master") - } -} - -func TestStandalone_pollerIncompleteInfo(t *testing.T) { - d := NewStandalone(&mesos.MasterInfo{}) - f := fetcherFunc(func(context.Context, string) (*upid.UPID, error) { - return nil, nil - }) - ch := make(chan struct{}) - go func() { - defer close(ch) - d.poller(f) - }() - select { - case <-ch: // expected - case <-time.After(1 * time.Second): - t.Fatalf("expected poller to shutdown since master info is incomplete") - } - select { - case <-d.Done(): // expected - case <-time.After(1 * time.Second): - t.Fatalf("expected detector to shutdown since it has no master") - } -} - -func TestStandalone_pollerFetched(t *testing.T) { - assert := assert.New(t) - // presence of IP address allows fecher to be called - d := NewStandalone(&mesos.MasterInfo{Ip: proto.Uint32(localhost)}) - defer d.Cancel() - - fetched := make(chan struct{}) - pid := &upid.UPID{ - ID: "foo@127.0.0.1:5050", - Host: "127.0.0.1", - Port: "5050", - } - f := fetcherFunc(func(ctx context.Context, addr string) (*upid.UPID, error) { - defer close(fetched) - assert.Equal("127.0.0.1:5050", addr) - return pid, nil - }) - - go d.poller(f) - - // fetch called - select { - case <-fetched: // expected - case <-time.After(1 * time.Second): - t.Fatalf("expected fetch") - } - - // read MasterInfo - select { - case mi := <-d.ch: - assert.Equal(mi, CreateMasterInfo(pid)) - case <-time.After(1 * time.Second): - t.Fatalf("expected poller to send master info") - } -} - -func TestStandalone_pollerFetchedMulti(t *testing.T) { - assert := assert.New(t) - // presence of IP address allows fecher to be called - d := NewStandalone(&mesos.MasterInfo{Ip: proto.Uint32(localhost)}) - defer d.Cancel() - d.leaderSyncInterval = 500 * time.Millisecond - - i := 0 - var wg sync.WaitGroup - wg.Add(4) - f := fetcherFunc(func(ctx context.Context, addr string) (*upid.UPID, error) { - defer func() { i++ }() - switch i { - case 0: - wg.Done() - assert.Equal("127.0.0.1:5050", addr) - return &upid.UPID{ID: "foo@127.0.0.1:5050", Host: "127.0.0.1", Port: "5050"}, nil - case 1: - wg.Done() - assert.Equal("127.0.0.1:5050", addr) - return &upid.UPID{ID: "foo@127.0.0.2:5050", Host: "127.0.0.2", Port: "5050"}, nil - case 2: - wg.Done() - return nil, context.DeadlineExceeded - case 3: - wg.Done() - assert.Equal("127.0.0.1:5050", addr) - return &upid.UPID{ID: "foo@127.0.0.3:5050", Host: "127.0.0.3", Port: "5050"}, nil - default: - d.Cancel() - return nil, context.Canceled - } - }) - - go d.poller(f) - - // fetches complete - ch := make(chan struct{}) - go func() { - defer close(ch) - wg.Wait() - }() - - changed := make(chan struct{}) - go func() { - defer close(changed) - for i := 0; i < 4; i++ { - if mi, ok := <-d.ch; !ok { - t.Fatalf("failed to read master info on cycle %v", i) - break - } else { - switch i { - case 0: - assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.1:5050", Host: "127.0.0.1", Port: "5050"}), mi) - case 1: - assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.2:5050", Host: "127.0.0.2", Port: "5050"}), mi) - case 2: - assert.Nil(mi) - case 3: - assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.3:5050", Host: "127.0.0.3", Port: "5050"}), mi) - } - } - } - }() - - started := time.Now() - select { - case <-ch: // expected - case <-time.After(3 * time.Second): - t.Fatalf("expected fetches all complete") - } - - select { - case <-changed: // expected - case <-time.After((3 * time.Second) - time.Now().Sub(started)): - t.Fatalf("expected to have received all master info changes") - } -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/detect_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/detect_test.go deleted file mode 100644 index 863e7caa3b3..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/detect_test.go +++ /dev/null @@ -1,528 +0,0 @@ -package zoo - -import ( - "fmt" - "sync" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - log "github.com/golang/glog" - "github.com/mesos/mesos-go/detector" - mesos "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/samuel/go-zookeeper/zk" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" -) - -const ( - zkurl = "zk://127.0.0.1:2181/mesos" - zkurl_bad = "zk://127.0.0.1:2181" - test_zk_path = "/test" -) - -func TestParseZk_single(t *testing.T) { - hosts, path, err := parseZk(zkurl) - assert.NoError(t, err) - assert.Equal(t, 1, len(hosts)) - assert.Equal(t, "/mesos", path) -} - -func TestParseZk_multi(t *testing.T) { - hosts, path, err := parseZk("zk://abc:1,def:2/foo") - assert.NoError(t, err) - assert.Equal(t, []string{"abc:1", "def:2"}, hosts) - assert.Equal(t, "/foo", path) -} - -func TestParseZk_multiIP(t *testing.T) { - hosts, path, err := parseZk("zk://10.186.175.156:2181,10.47.50.94:2181,10.0.92.171:2181/mesos") - assert.NoError(t, err) - assert.Equal(t, []string{"10.186.175.156:2181", "10.47.50.94:2181", "10.0.92.171:2181"}, hosts) - assert.Equal(t, "/mesos", path) -} - -type mockZkClient struct { - mock.Mock -} - -func (m *mockZkClient) stopped() (a <-chan struct{}) { - args := m.Called() - if x := args.Get(0); x != nil { - a = x.(<-chan struct{}) - } - return -} - -func (m *mockZkClient) stop() { - m.Called() -} - -func (m *mockZkClient) data(path string) (a []byte, b error) { - args := m.Called(path) - if x := args.Get(0); x != nil { - a = x.([]byte) - } - b = args.Error(1) - return -} - -func (m *mockZkClient) watchChildren(path string) (a string, b <-chan []string, c <-chan error) { - args := m.Called(path) - a = args.String(0) - if x := args.Get(1); x != nil { - b = x.(<-chan []string) - } - if x := args.Get(2); x != nil { - c = x.(<-chan error) - } - return -} - -// newMockZkClient returns a mocked implementation of zkInterface that implements expectations -// for stop() and stopped(); multiple calls to stop() are safe. -func newMockZkClient(initialChildren ...string) (mocked *mockZkClient, snaps chan []string, errs chan error) { - var doneOnce sync.Once - done := make(chan struct{}) - - mocked = &mockZkClient{} - mocked.On("stop").Return().Run(func(_ mock.Arguments) { doneOnce.Do(func() { close(done) }) }) - mocked.On("stopped").Return((<-chan struct{})(done)) - - if initialChildren != nil { - errs = make(chan error) // this is purposefully unbuffered (some tests depend on this) - snaps = make(chan []string, 1) - snaps <- initialChildren[:] - mocked.On("watchChildren", currentPath).Return( - test_zk_path, (<-chan []string)(snaps), (<-chan error)(errs)).Run( - func(_ mock.Arguments) { log.V(1).Infoln("watchChildren invoked") }) - } - return -} - -func newTestMasterInfo(id int) []byte { - miPb := util.NewMasterInfo(fmt.Sprintf("master(%d)@localhost:5050", id), 123456789, 400) - data, err := proto.Marshal(miPb) - if err != nil { - panic(err) - } - return data -} - -func TestMasterDetectorChildrenChanged(t *testing.T) { - md, err := NewMasterDetector(zkurl) - defer md.Cancel() - assert.NoError(t, err) - - path := test_zk_path - snapDetected := make(chan struct{}) - md.bootstrapFunc = func() error { - if md.client != nil { - return nil - } - log.V(1).Infoln("bootstrapping detector") - defer log.V(1).Infoln("bootstrapping detector ..finished") - - mocked, _, errs := newMockZkClient("info_0", "info_5", "info_10") - md.client = mocked - md.minDetectorCyclePeriod = 10 * time.Millisecond // we don't have all day! - - mocked.On("data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil) - - // wait for the first child snapshot to be processed before signaling end-of-watch - // (which is signalled by closing errs). - go func() { - defer close(errs) - select { - case <-snapDetected: - case <-md.Done(): - t.Errorf("detector died before child snapshot") - } - }() - return nil - } - - called := 0 - lostMaster := make(chan struct{}) - const expectedLeader = "master(0)@localhost:5050" - err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) { - //expect 2 calls in sequence: the first setting a master - //and the second clearing it - switch called++; called { - case 1: - defer close(snapDetected) - assert.NotNil(t, master) - assert.Equal(t, expectedLeader, master.GetId()) - case 2: - md.Cancel() - defer close(lostMaster) - assert.Nil(t, master) - default: - t.Errorf("unexpected notification call attempt %d", called) - } - })) - assert.NoError(t, err) - - fatalOn(t, 10*time.Second, lostMaster, "Waited too long for lost master") - - select { - case <-md.Done(): - assert.Equal(t, 2, called, "expected 2 detection callbacks instead of %d", called) - case <-time.After(time.Second * 10): - panic("Waited too long for detector shutdown...") - } -} - -// single connector instance, it's internal connection to zk is flappy -func TestMasterDetectorFlappyConnectionState(t *testing.T) { - md, err := NewMasterDetector(zkurl) - defer md.Cancel() - assert.NoError(t, err) - - const ITERATIONS = 3 - var wg sync.WaitGroup - wg.Add(1 + ITERATIONS) // +1 for the initial snapshot that's sent for the first watch - path := test_zk_path - - md.bootstrapFunc = func() error { - if md.client != nil { - return nil - } - log.V(1).Infoln("bootstrapping detector") - defer log.V(1).Infoln("bootstrapping detector ..finished") - - children := []string{"info_0", "info_5", "info_10"} - mocked, snaps, errs := newMockZkClient(children...) - md.client = mocked - md.minDetectorCyclePeriod = 10 * time.Millisecond // we don't have all day! - - mocked.On("data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil) - - // the first snapshot will be sent immediately and the detector will be awaiting en event. - // cycle through some connected/disconnected events but maintain the same snapshot - go func() { - defer close(errs) - for attempt := 0; attempt < ITERATIONS; attempt++ { - // send an error, should cause the detector to re-issue a watch - errs <- zk.ErrSessionExpired - // the detection loop issues another watch, so send it a snapshot.. - // send another snapshot - snaps <- children - } - }() - return nil - } - - called := 0 - lostMaster := make(chan struct{}) - const EXPECTED_CALLS = (ITERATIONS * 2) + 2 // +1 for initial snapshot, +1 for final lost-leader (close(errs)) - err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) { - called++ - log.V(3).Infof("detector invoked: called %d", called) - switch { - case called < EXPECTED_CALLS: - if master != nil { - wg.Done() - assert.Equal(t, master.GetId(), "master(0)@localhost:5050") - } - case called == EXPECTED_CALLS: - md.Cancel() - defer close(lostMaster) - assert.Nil(t, master) - default: - t.Errorf("unexpected notification call attempt %d", called) - } - })) - assert.NoError(t, err) - - fatalAfter(t, 10*time.Second, wg.Wait, "Waited too long for new-master alerts") - fatalOn(t, 3*time.Second, lostMaster, "Waited too long for lost master") - - select { - case <-md.Done(): - assert.Equal(t, EXPECTED_CALLS, called, "expected %d detection callbacks instead of %d", EXPECTED_CALLS, called) - case <-time.After(time.Second * 10): - panic("Waited too long for detector shutdown...") - } -} - -func TestMasterDetector_multipleLeadershipChanges(t *testing.T) { - md, err := NewMasterDetector(zkurl) - defer md.Cancel() - assert.NoError(t, err) - - leadershipChanges := [][]string{ - {"info_014", "info_010", "info_005"}, - {"info_005", "info_004", "info_022"}, - {}, // indicates no master - {"info_017", "info_099", "info_200"}, - } - - ITERATIONS := len(leadershipChanges) - - // +1 for initial snapshot, +1 for final lost-leader (close(errs)) - EXPECTED_CALLS := (ITERATIONS + 2) - - var wg sync.WaitGroup - wg.Add(ITERATIONS) // +1 for the initial snapshot that's sent for the first watch, -1 because set 3 is empty - path := test_zk_path - - md.bootstrapFunc = func() error { - if md.client != nil { - return nil - } - log.V(1).Infoln("bootstrapping detector") - defer log.V(1).Infoln("bootstrapping detector ..finished") - - children := []string{"info_0", "info_5", "info_10"} - mocked, snaps, errs := newMockZkClient(children...) - md.client = mocked - md.minDetectorCyclePeriod = 10 * time.Millisecond // we don't have all day! - - mocked.On("data", fmt.Sprintf("%s/info_0", path)).Return(newTestMasterInfo(0), nil) - mocked.On("data", fmt.Sprintf("%s/info_005", path)).Return(newTestMasterInfo(5), nil) - mocked.On("data", fmt.Sprintf("%s/info_004", path)).Return(newTestMasterInfo(4), nil) - mocked.On("data", fmt.Sprintf("%s/info_017", path)).Return(newTestMasterInfo(17), nil) - - // the first snapshot will be sent immediately and the detector will be awaiting en event. - // cycle through some connected/disconnected events but maintain the same snapshot - go func() { - defer close(errs) - for attempt := 0; attempt < ITERATIONS; attempt++ { - snaps <- leadershipChanges[attempt] - } - }() - return nil - } - - called := 0 - lostMaster := make(chan struct{}) - expectedLeaders := []int{0, 5, 4, 17} - leaderIdx := 0 - err = md.Detect(detector.OnMasterChanged(func(master *mesos.MasterInfo) { - called++ - log.V(3).Infof("detector invoked: called %d", called) - switch { - case called < EXPECTED_CALLS: - if master != nil { - expectedLeader := fmt.Sprintf("master(%d)@localhost:5050", expectedLeaders[leaderIdx]) - assert.Equal(t, expectedLeader, master.GetId()) - leaderIdx++ - wg.Done() - } - case called == EXPECTED_CALLS: - md.Cancel() - defer close(lostMaster) - assert.Nil(t, master) - default: - t.Errorf("unexpected notification call attempt %d", called) - } - })) - assert.NoError(t, err) - - fatalAfter(t, 10*time.Second, wg.Wait, "Waited too long for new-master alerts") - fatalOn(t, 3*time.Second, lostMaster, "Waited too long for lost master") - - select { - case <-md.Done(): - assert.Equal(t, EXPECTED_CALLS, called, "expected %d detection callbacks instead of %d", EXPECTED_CALLS, called) - case <-time.After(time.Second * 10): - panic("Waited too long for detector shutdown...") - } -} - -func TestMasterDetect_selectTopNode_none(t *testing.T) { - assert := assert.New(t) - nodeList := []string{} - node := selectTopNodePrefix(nodeList, "foo") - assert.Equal("", node) -} - -func TestMasterDetect_selectTopNode_0000x(t *testing.T) { - assert := assert.New(t) - nodeList := []string{ - "info_0000000046", - "info_0000000032", - "info_0000000058", - "info_0000000061", - "info_0000000008", - } - node := selectTopNodePrefix(nodeList, nodePrefix) - assert.Equal("info_0000000008", node) -} - -func TestMasterDetect_selectTopNode_mixJson(t *testing.T) { - assert := assert.New(t) - nodeList := []string{ - nodePrefix + "0000000046", - nodePrefix + "0000000032", - nodeJSONPrefix + "0000000046", - nodeJSONPrefix + "0000000032", - } - node := selectTopNodePrefix(nodeList, nodeJSONPrefix) - assert.Equal(nodeJSONPrefix+"0000000032", node) - - node = selectTopNodePrefix(nodeList, nodePrefix) - assert.Equal(nodePrefix+"0000000032", node) -} - -func TestMasterDetect_selectTopNode_mixedEntries(t *testing.T) { - assert := assert.New(t) - nodeList := []string{ - "info_0000000046", - "info_0000000032", - "foo_lskdjfglsdkfsdfgdfg", - "info_0000000061", - "log_replicas_fdgwsdfgsdf", - "bar", - } - node := selectTopNodePrefix(nodeList, nodePrefix) - assert.Equal("info_0000000032", node) -} - -// implements MasterChanged and AllMasters extension -type allMastersListener struct { - mock.Mock -} - -func (a *allMastersListener) OnMasterChanged(mi *mesos.MasterInfo) { - a.Called(mi) -} - -func (a *allMastersListener) UpdatedMasters(mi []*mesos.MasterInfo) { - a.Called(mi) -} - -func afterFunc(f func()) <-chan struct{} { - ch := make(chan struct{}) - go func() { - defer close(ch) - f() - }() - return ch -} - -func fatalAfter(t *testing.T, d time.Duration, f func(), msg string, args ...interface{}) { - fatalOn(t, d, afterFunc(f), msg, args...) -} - -func fatalOn(t *testing.T, d time.Duration, ch <-chan struct{}, msg string, args ...interface{}) { - select { - case <-ch: - return - case <-time.After(d): - // check for a tie - select { - case <-ch: - return - default: - t.Fatalf(msg, args...) - } - } -} - -/* TODO(jdef) refactor this to work with the new zkInterface -func TestNotifyAllMasters(t *testing.T) { - c, err := newClient(test_zk_hosts, test_zk_path) - assert.NoError(t, err) - - childEvents := make(chan zk.Event, 5) - connector := NewMockConnector() - - c.setFactory(asFactory(func() (Connector, <-chan zk.Event, error) { - sessionEvents := make(chan zk.Event, 1) - sessionEvents <- zk.Event{ - Type: zk.EventSession, - State: zk.StateConnected, - } - return connector, sessionEvents, nil - })) - - md, err := NewMasterDetector(zkurl) - defer md.Cancel() - - assert.NoError(t, err) - - c.errorHandler = ErrorHandler(func(c *Client, e error) { - t.Errorf("unexpected error: %v", e) - }) - md.client = c - - listener := &allMastersListener{} - - //-- expect primer - var primer sync.WaitGroup - ignoreArgs := func(f func()) func(mock.Arguments) { - primer.Add(1) - return func(_ mock.Arguments) { - f() - } - } - connector.On("Children", test_zk_path).Return([]string{}, &zk.Stat{}, nil).Run(ignoreArgs(primer.Done)).Once() - listener.On("UpdatedMasters", []*mesos.MasterInfo{}).Return().Run(ignoreArgs(primer.Done)).Once() - connector.On("ChildrenW", test_zk_path).Return([]string{test_zk_path}, &zk.Stat{}, (<-chan zk.Event)(childEvents), nil).Run(ignoreArgs(primer.Done)).Once() - md.Detect(listener) - fatalAfter(t, 3*time.Second, primer.Wait, "timed out waiting for detection primer") - - listener.AssertExpectations(t) - connector.AssertExpectations(t) - - //-- test membership changes - type expectedGets struct { - info []byte - err error - } - tt := []struct { - zkEntry []string - gets []expectedGets - leaderIdx int - }{ - {[]string{"info_004"}, []expectedGets{{newTestMasterInfo(1), nil}}, 0}, - {[]string{"info_007", "info_005", "info_006"}, []expectedGets{{newTestMasterInfo(2), nil}, {newTestMasterInfo(3), nil}, {newTestMasterInfo(4), nil}}, 1}, - {nil, nil, -1}, - } - for j, tc := range tt { - // expectations - var tcwait sync.WaitGroup - ignoreArgs = func(f func()) func(mock.Arguments) { - tcwait.Add(1) - return func(_ mock.Arguments) { - f() - } - } - - expectedInfos := []*mesos.MasterInfo{} - for i, zke := range tc.zkEntry { - connector.On("Get", fmt.Sprintf("%s/%s", test_zk_path, zke)).Return(tc.gets[i].info, &zk.Stat{}, tc.gets[i].err).Run(ignoreArgs(tcwait.Done)).Once() - masterInfo := &mesos.MasterInfo{} - err = proto.Unmarshal(tc.gets[i].info, masterInfo) - if err != nil { - t.Fatalf("failed to unmarshall MasterInfo data: %v", err) - } - expectedInfos = append(expectedInfos, masterInfo) - } - if len(tc.zkEntry) > 0 { - connector.On("Get", fmt.Sprintf("%s/%s", test_zk_path, tc.zkEntry[tc.leaderIdx])).Return( - tc.gets[tc.leaderIdx].info, &zk.Stat{}, tc.gets[tc.leaderIdx].err).Run(ignoreArgs(tcwait.Done)).Once() - } - connector.On("Children", test_zk_path).Return(tc.zkEntry, &zk.Stat{}, nil).Run(ignoreArgs(tcwait.Done)).Once() - listener.On("OnMasterChanged", mock.AnythingOfType("*mesosproto.MasterInfo")).Return().Run(ignoreArgs(tcwait.Done)).Once() - listener.On("UpdatedMasters", expectedInfos).Return().Run(ignoreArgs(tcwait.Done)).Once() - connector.On("ChildrenW", test_zk_path).Return([]string{test_zk_path}, &zk.Stat{}, (<-chan zk.Event)(childEvents), nil).Run(ignoreArgs(tcwait.Done)).Once() - - // fire the event that triggers the test case - childEvents <- zk.Event{ - Type: zk.EventNodeChildrenChanged, - Path: test_zk_path, - } - - // allow plenty of time for all the async processing to happen - fatalAfter(t, 5*time.Second, tcwait.Wait, "timed out waiting for all-masters test case %d", j+1) - listener.AssertExpectations(t) - connector.AssertExpectations(t) - } - - connector.On("Close").Return(nil) -} -*/ diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/plugin_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/plugin_test.go deleted file mode 100644 index 9b93ad3ab9c..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/detector/zoo/plugin_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package zoo - -import ( - "testing" - - "github.com/mesos/mesos-go/detector" - "github.com/stretchr/testify/assert" -) - -// validate plugin registration for zk:// prefix is working -func TestDectorFactoryNew_ZkPrefix(t *testing.T) { - assert := assert.New(t) - m, err := detector.New("zk://127.0.0.1:5050/mesos") - assert.NoError(err) - assert.IsType(&MasterDetector{}, m) - md := m.(*MasterDetector) - t.Logf("canceling detector") - md.Cancel() -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_intgr_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_intgr_test.go deleted file mode 100644 index c16c6bd853b..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_intgr_test.go +++ /dev/null @@ -1,567 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 executor - -import ( - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "sync" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - log "github.com/golang/glog" - mesos "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/mesos/mesos-go/testutil" - "github.com/pborman/uuid" - "github.com/stretchr/testify/assert" -) - -// testScuduler is used for testing Schduler callbacks. -type testExecutor struct { - ch chan bool - wg *sync.WaitGroup - t *testing.T -} - -func newTestExecutor(t *testing.T) *testExecutor { - return &testExecutor{ch: make(chan bool), t: t} -} - -func (exec *testExecutor) Registered(driver ExecutorDriver, execinfo *mesos.ExecutorInfo, fwinfo *mesos.FrameworkInfo, slaveinfo *mesos.SlaveInfo) { - log.Infoln("Exec.Registered() called.") - assert.NotNil(exec.t, execinfo) - assert.NotNil(exec.t, fwinfo) - assert.NotNil(exec.t, slaveinfo) - exec.ch <- true -} - -func (exec *testExecutor) Reregistered(driver ExecutorDriver, slaveinfo *mesos.SlaveInfo) { - log.Infoln("Exec.Re-registered() called.") - assert.NotNil(exec.t, slaveinfo) - exec.ch <- true -} - -func (e *testExecutor) Disconnected(ExecutorDriver) {} - -func (exec *testExecutor) LaunchTask(driver ExecutorDriver, taskinfo *mesos.TaskInfo) { - log.Infoln("Exec.LaunchTask() called.") - assert.NotNil(exec.t, taskinfo) - assert.True(exec.t, util.NewTaskID("test-task-001").Equal(taskinfo.TaskId)) - exec.ch <- true -} - -func (exec *testExecutor) KillTask(driver ExecutorDriver, taskid *mesos.TaskID) { - log.Infoln("Exec.KillTask() called.") - assert.NotNil(exec.t, taskid) - assert.True(exec.t, util.NewTaskID("test-task-001").Equal(taskid)) - exec.ch <- true -} - -func (exec *testExecutor) FrameworkMessage(driver ExecutorDriver, message string) { - log.Infoln("Exec.FrameworkMessage() called.") - assert.NotNil(exec.t, message) - assert.Equal(exec.t, "Hello-Test", message) - exec.ch <- true -} - -func (exec *testExecutor) Shutdown(ExecutorDriver) { - log.Infoln("Exec.Shutdown() called.") - exec.ch <- true -} - -func (exec *testExecutor) Error(driver ExecutorDriver, err string) { - log.Infoln("Exec.Error() called.") - log.Infoln("Got error ", err) - driver.Stop() - exec.ch <- true -} - -// ------------------------ Test Functions -------------------- // - -func setTestEnv(t *testing.T) { - assert.NoError(t, os.Setenv("MESOS_FRAMEWORK_ID", frameworkID)) - assert.NoError(t, os.Setenv("MESOS_EXECUTOR_ID", executorID)) -} - -type integrationTestDriver struct { - *MesosExecutorDriver -} - -func (i *integrationTestDriver) setConnected(b bool) { - i.lock.Lock() - defer i.lock.Unlock() - i.connected = b -} - -// connectionListener returns a signal chan that closes once driver.connected == true. -func (i *integrationTestDriver) connectionListener() chan struct{} { - connected := make(chan struct{}) - go func() { - i.lock.Lock() - defer i.lock.Unlock() - for !i.connected { - select { - case <-i.stopCh: - return - default: - i.cond.Wait() - } - } - close(connected) - }() - return connected -} - -func newIntegrationTestDriver(t *testing.T, exec Executor) *integrationTestDriver { - dconfig := DriverConfig{ - Executor: exec, - } - driver, err := NewMesosExecutorDriver(dconfig) - if err != nil { - t.Fatal(err) - } - return &integrationTestDriver{driver} -} - -func TestExecutorDriverRegisterExecutorMessage(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatalf("Missing RegisteredExecutor data from scheduler.") - } - defer req.Body.Close() - - message := new(mesos.RegisterExecutorMessage) - err = proto.Unmarshal(data, message) - assert.NoError(t, err) - assert.Equal(t, frameworkID, message.GetFrameworkId().GetValue()) - assert.Equal(t, executorID, message.GetExecutorId().GetValue()) - - ch <- true - - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - - driver := newIntegrationTestDriver(t, exec) - assert.False(t, driver.Running()) - - stat, err := driver.Start() - assert.NoError(t, err) - assert.True(t, driver.Running()) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - - select { - case <-ch: - case <-time.After(time.Second * 1): - log.Errorf("Tired of waiting...") - } -} - -func TestExecutorDriverExecutorRegisteredEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - defer driver.Stop() - - //simulate sending ExecutorRegisteredMessage from server to exec pid. - pbMsg := &mesos.ExecutorRegisteredMessage{ - ExecutorInfo: util.NewExecutorInfo(util.NewExecutorID(executorID), util.NewCommandInfo("ls -l")), - FrameworkId: util.NewFrameworkID(frameworkID), - FrameworkInfo: util.NewFrameworkInfo("test", "test-framework", util.NewFrameworkID(frameworkID)), - SlaveId: util.NewSlaveID(slaveID), - SlaveInfo: &mesos.SlaveInfo{Hostname: proto.String("localhost")}, - } - c := testutil.NewMockMesosClient(t, server.PID) - connected := driver.connectionListener() - c.SendMessage(driver.self, pbMsg) - select { - case <-connected: - case <-time.After(time.Second * 1): - log.Errorf("Tired of waiting...") - } -} - -func TestExecutorDriverExecutorReregisteredEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - defer driver.Stop() - - //simulate sending ExecutorRegisteredMessage from server to exec pid. - pbMsg := &mesos.ExecutorReregisteredMessage{ - SlaveId: util.NewSlaveID(slaveID), - SlaveInfo: &mesos.SlaveInfo{Hostname: proto.String("localhost")}, - } - c := testutil.NewMockMesosClient(t, server.PID) - connected := driver.connectionListener() - c.SendMessage(driver.self, pbMsg) - select { - case <-connected: - case <-time.After(time.Second * 1): - log.Errorf("Tired of waiting...") - } -} - -func TestExecutorDriverReconnectEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - - // exec registration request - if strings.Contains(reqPath, "RegisterExecutorMessage") { - log.Infoln("Got Executor registration request") - } - - if strings.Contains(reqPath, "ReregisterExecutorMessage") { - log.Infoln("Got Executor Re-registration request") - ch <- true - } - - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - defer driver.Stop() - - // send "reconnect" event to driver - pbMsg := &mesos.ReconnectExecutorMessage{ - SlaveId: util.NewSlaveID(slaveID), - } - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - - select { - case <-ch: - case <-time.After(time.Second * 2): - log.Errorf("Tired of waiting...") - } - -} - -func TestExecutorDriverRunTaskEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - defer driver.Stop() - - // send runtask event to driver - pbMsg := &mesos.RunTaskMessage{ - FrameworkId: util.NewFrameworkID(frameworkID), - Framework: util.NewFrameworkInfo( - "test", "test-framework-001", util.NewFrameworkID(frameworkID), - ), - Pid: proto.String(server.PID.String()), - Task: util.NewTaskInfo( - "test-task", - util.NewTaskID("test-task-001"), - util.NewSlaveID(slaveID), - []*mesos.Resource{ - util.NewScalarResource("mem", 112), - util.NewScalarResource("cpus", 2), - }, - ), - } - - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - - select { - case <-ch: - case <-time.After(time.Second * 2): - log.Errorf("Tired of waiting...") - } - -} - -func TestExecutorDriverKillTaskEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - defer driver.Stop() - - // send runtask event to driver - pbMsg := &mesos.KillTaskMessage{ - FrameworkId: util.NewFrameworkID(frameworkID), - TaskId: util.NewTaskID("test-task-001"), - } - - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - - select { - case <-ch: - case <-time.After(time.Second * 2): - log.Errorf("Tired of waiting...") - } -} - -func TestExecutorDriverStatusUpdateAcknowledgement(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - defer driver.Stop() - - // send ACK from server - pbMsg := &mesos.StatusUpdateAcknowledgementMessage{ - SlaveId: util.NewSlaveID(slaveID), - FrameworkId: util.NewFrameworkID(frameworkID), - TaskId: util.NewTaskID("test-task-001"), - Uuid: []byte(uuid.NewRandom().String()), - } - - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - <-time.After(time.Second * 1) -} - -func TestExecutorDriverFrameworkToExecutorMessageEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - defer driver.Stop() - - // send runtask event to driver - pbMsg := &mesos.FrameworkToExecutorMessage{ - SlaveId: util.NewSlaveID(slaveID), - ExecutorId: util.NewExecutorID(executorID), - FrameworkId: util.NewFrameworkID(frameworkID), - Data: []byte("Hello-Test"), - } - - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - - select { - case <-ch: - case <-time.After(time.Second * 1): - log.Errorf("Tired of waiting...") - } -} - -func TestExecutorDriverShutdownEvent(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - defer server.Close() - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - // start - driver := newIntegrationTestDriver(t, exec) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - - // send runtask event to driver - pbMsg := &mesos.ShutdownExecutorMessage{} - - c := testutil.NewMockMesosClient(t, server.PID) - c.SendMessage(driver.self, pbMsg) - - select { - case <-ch: - case <-time.After(time.Second * 5): - log.Errorf("Tired of waiting...") - } - - <-time.After(time.Second * 1) // wait for shutdown to finish. - assert.Equal(t, mesos.Status_DRIVER_STOPPED, driver.Status()) -} - -func TestExecutorDriverError(t *testing.T) { - setTestEnv(t) - ch := make(chan bool, 2) - // Mock Slave process to respond to registration event. - server := testutil.NewMockSlaveHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - reqPath, err := url.QueryUnescape(req.URL.String()) - assert.NoError(t, err) - log.Infoln("RCVD request", reqPath) - rsp.WriteHeader(http.StatusAccepted) - }) - - exec := newTestExecutor(t) - exec.ch = ch - exec.t = t - - driver := newIntegrationTestDriver(t, exec) - server.Close() // will cause error - // Run() cause async message processing to start - // Therefore, error-handling will be done via Executor.Error callaback. - stat, err := driver.Run() - assert.NoError(t, err) - assert.Equal(t, mesos.Status_DRIVER_STOPPED, stat) - - select { - case <-ch: - case <-time.After(time.Second * 1): - log.Errorf("Tired of waiting...") - } -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_test.go deleted file mode 100644 index d464172550c..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/executor/executor_test.go +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 executor - -import ( - "fmt" - "os" - "testing" - - "github.com/mesos/mesos-go/healthchecker" - "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/mesos/mesos-go/messenger" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" -) - -var ( - slavePID = "slave(1)@127.0.0.1:8080" - slaveID = "some-slave-id-uuid" - frameworkID = "some-framework-id-uuid" - executorID = "some-executor-id-uuid" -) - -func setEnvironments(t *testing.T, workDir string, checkpoint bool) { - assert.NoError(t, os.Setenv("MESOS_SLAVE_PID", slavePID)) - assert.NoError(t, os.Setenv("MESOS_SLAVE_ID", slaveID)) - assert.NoError(t, os.Setenv("MESOS_FRAMEWORK_ID", frameworkID)) - assert.NoError(t, os.Setenv("MESOS_EXECUTOR_ID", executorID)) - if len(workDir) > 0 { - assert.NoError(t, os.Setenv("MESOS_DIRECTORY", workDir)) - } - if checkpoint { - assert.NoError(t, os.Setenv("MESOS_CHECKPOINT", "1")) - } -} - -func clearEnvironments(t *testing.T) { - assert.NoError(t, os.Setenv("MESOS_SLAVE_PID", "")) - assert.NoError(t, os.Setenv("MESOS_SLAVE_ID", "")) - assert.NoError(t, os.Setenv("MESOS_FRAMEWORK_ID", "")) - assert.NoError(t, os.Setenv("MESOS_EXECUTOR_ID", "")) -} - -func newTestExecutorDriver(t *testing.T, exec Executor) *MesosExecutorDriver { - dconfig := DriverConfig{ - Executor: exec, - } - driver, err := NewMesosExecutorDriver(dconfig) - if err != nil { - t.Fatal(err) - } - return driver -} - -type testExecutorDriver struct { - *MesosExecutorDriver -} - -func (e *testExecutorDriver) setConnected(b bool) { - e.lock.Lock() - defer e.lock.Unlock() - e.connected = b -} - -func createTestExecutorDriver(t *testing.T) ( - *testExecutorDriver, - *messenger.MockedMessenger, - *healthchecker.MockedHealthChecker) { - - exec := NewMockedExecutor() - exec.On("Error").Return(nil) - - setEnvironments(t, "", false) - driver := newTestExecutorDriver(t, exec) - - messenger := messenger.NewMockedMessenger() - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Send").Return(nil) - messenger.On("Stop").Return(nil) - - checker := healthchecker.NewMockedHealthChecker() - checker.On("Start").Return() - checker.On("Stop").Return() - - driver.messenger = messenger - return &testExecutorDriver{driver}, messenger, checker -} - -func TestExecutorDriverStartFailedToParseEnvironment(t *testing.T) { - clearEnvironments(t) - exec := NewMockedExecutor() - exec.On("Error").Return(nil) - dconfig := DriverConfig{Executor: exec} - driver, err := NewMesosExecutorDriver(dconfig) - assert.Nil(t, driver) - assert.Error(t, err) -} - -func TestExecutorDriverStartFailedToStartMessenger(t *testing.T) { - exec := NewMockedExecutor() - - setEnvironments(t, "", false) - driver := newTestExecutorDriver(t, exec) - assert.NotNil(t, driver) - messenger := messenger.NewMockedMessenger() - driver.messenger = messenger - - // Set expections and return values. - messenger.On("Start").Return(fmt.Errorf("messenger failed to start")) - messenger.On("Stop").Return(nil) - - status, err := driver.Start() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_NOT_STARTED, status) - - messenger.Stop() - - messenger.AssertNumberOfCalls(t, "Start", 1) - messenger.AssertNumberOfCalls(t, "Stop", 1) -} - -func TestExecutorDriverStartFailedToSendRegisterMessage(t *testing.T) { - exec := NewMockedExecutor() - - setEnvironments(t, "", false) - driver := newTestExecutorDriver(t, exec) - messenger := messenger.NewMockedMessenger() - driver.messenger = messenger - - // Set expections and return values. - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Send").Return(fmt.Errorf("messenger failed to send")) - messenger.On("Stop").Return(nil) - - status, err := driver.Start() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_NOT_STARTED, status) - - messenger.AssertNumberOfCalls(t, "Start", 1) - messenger.AssertNumberOfCalls(t, "UPID", 1) - messenger.AssertNumberOfCalls(t, "Send", 1) - messenger.AssertNumberOfCalls(t, "Stop", 1) -} - -func TestExecutorDriverStartSucceed(t *testing.T) { - setEnvironments(t, "", false) - - exec := NewMockedExecutor() - exec.On("Error").Return(nil) - - driver := newTestExecutorDriver(t, exec) - - messenger := messenger.NewMockedMessenger() - driver.messenger = messenger - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Send").Return(nil) - messenger.On("Stop").Return(nil) - - checker := healthchecker.NewMockedHealthChecker() - checker.On("Start").Return() - checker.On("Stop").Return() - - assert.False(t, driver.Running()) - status, err := driver.Start() - assert.True(t, driver.Running()) - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, status) - - messenger.AssertNumberOfCalls(t, "Start", 1) - messenger.AssertNumberOfCalls(t, "UPID", 1) - messenger.AssertNumberOfCalls(t, "Send", 1) -} - -func TestExecutorDriverRun(t *testing.T) { - setEnvironments(t, "", false) - - // Set expections and return values. - messenger := messenger.NewMockedMessenger() - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Send").Return(nil) - messenger.On("Stop").Return(nil) - - exec := NewMockedExecutor() - exec.On("Error").Return(nil) - - driver := newTestExecutorDriver(t, exec) - driver.messenger = messenger - assert.False(t, driver.Running()) - - checker := healthchecker.NewMockedHealthChecker() - checker.On("Start").Return() - checker.On("Stop").Return() - - ch := make(chan struct{}) - go func() { - defer close(ch) - stat, err := driver.Run() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) - }() - <-driver.started - assert.True(t, driver.Running()) - driver.Stop() - <-ch -} - -func TestExecutorDriverJoin(t *testing.T) { - setEnvironments(t, "", false) - - // Set expections and return values. - messenger := messenger.NewMockedMessenger() - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Send").Return(nil) - messenger.On("Stop").Return(nil) - - exec := NewMockedExecutor() - exec.On("Error").Return(nil) - - driver := newTestExecutorDriver(t, exec) - driver.messenger = messenger - assert.False(t, driver.Running()) - - checker := healthchecker.NewMockedHealthChecker() - checker.On("Start").Return() - checker.On("Stop").Return() - - stat, err := driver.Start() - assert.NoError(t, err) - assert.True(t, driver.Running()) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - - testCh := make(chan mesosproto.Status) - go func() { - stat, _ := driver.Join() - testCh <- stat - }() - - driver.Stop() - stat = <-testCh // when Stop() is called, stat will be DRIVER_STOPPED. - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) -} - -func TestExecutorDriverAbort(t *testing.T) { - statusChan := make(chan mesosproto.Status) - driver, messenger, _ := createTestExecutorDriver(t) - - assert.False(t, driver.Running()) - stat, err := driver.Start() - assert.True(t, driver.Running()) - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - go func() { - st, _ := driver.Join() - statusChan <- st - }() - - stat, err = driver.Abort() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, stat) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, <-statusChan) - assert.False(t, driver.Running()) - - // Abort for the second time, should return directly. - stat, err = driver.Abort() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, stat) - stat, err = driver.Stop() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, stat) - assert.False(t, driver.Running()) - - // Restart should not start. - stat, err = driver.Start() - assert.False(t, driver.Running()) - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, stat) - - messenger.AssertNumberOfCalls(t, "Start", 1) - messenger.AssertNumberOfCalls(t, "UPID", 1) - messenger.AssertNumberOfCalls(t, "Send", 1) - messenger.AssertNumberOfCalls(t, "Stop", 1) -} - -func TestExecutorDriverStop(t *testing.T) { - statusChan := make(chan mesosproto.Status) - driver, messenger, _ := createTestExecutorDriver(t) - - assert.False(t, driver.Running()) - stat, err := driver.Start() - assert.True(t, driver.Running()) - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - go func() { - stat, _ := driver.Join() - statusChan <- stat - }() - stat, err = driver.Stop() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, <-statusChan) - assert.False(t, driver.Running()) - - // Stop for the second time, should return directly. - stat, err = driver.Stop() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) - stat, err = driver.Abort() - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) - assert.False(t, driver.Running()) - - // Restart should not start. - stat, err = driver.Start() - assert.False(t, driver.Running()) - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_STOPPED, stat) - - messenger.AssertNumberOfCalls(t, "Start", 1) - messenger.AssertNumberOfCalls(t, "UPID", 1) - messenger.AssertNumberOfCalls(t, "Send", 1) - messenger.AssertNumberOfCalls(t, "Stop", 1) -} - -func TestExecutorDriverSendStatusUpdate(t *testing.T) { - - driver, _, _ := createTestExecutorDriver(t) - - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - - taskStatus := util.NewTaskStatus( - util.NewTaskID("test-task-001"), - mesosproto.TaskState_TASK_RUNNING, - ) - - stat, err = driver.SendStatusUpdate(taskStatus) - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) -} - -func TestExecutorDriverSendStatusUpdateStaging(t *testing.T) { - - driver, _, _ := createTestExecutorDriver(t) - stat, err := driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - - taskStatus := util.NewTaskStatus( - util.NewTaskID("test-task-001"), - mesosproto.TaskState_TASK_STAGING, - ) - - stat, err = driver.SendStatusUpdate(taskStatus) - assert.Error(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_ABORTED, stat) -} - -func TestExecutorDriverSendFrameworkMessage(t *testing.T) { - - driver, _, _ := createTestExecutorDriver(t) - - stat, err := driver.SendFrameworkMessage("failed") - assert.Error(t, err) - - stat, err = driver.Start() - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) - driver.setConnected(true) - - stat, err = driver.SendFrameworkMessage("Testing Mesos") - assert.NoError(t, err) - assert.Equal(t, mesosproto.Status_DRIVER_RUNNING, stat) -} - -func TestStatusUpdateAckRace_Issue103(t *testing.T) { - driver, _, _ := createTestExecutorDriver(t) - _, err := driver.Start() - assert.NoError(t, err) - - msg := &mesosproto.StatusUpdateAcknowledgementMessage{} - go func() { - driver.lock.Lock() - defer driver.lock.Unlock() - driver.statusUpdateAcknowledgement(nil, msg) - }() - - taskStatus := util.NewTaskStatus( - util.NewTaskID("test-task-001"), - mesosproto.TaskState_TASK_STAGING, - ) - - driver.SendStatusUpdate(taskStatus) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/logpb_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/logpb_test.go deleted file mode 100644 index 20e6005eaf7..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/logpb_test.go +++ /dev/null @@ -1,3245 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: log.proto -// DO NOT EDIT! - -package mesosproto - -import testing "testing" -import math_rand "math/rand" -import time "time" -import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" -import github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb" -import fmt "fmt" -import go_parser "go/parser" -import proto "github.com/gogo/protobuf/proto" -import math "math" - -// discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -func TestPromiseProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Promise{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPromiseMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Promise{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPromiseProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Promise, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPromise(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPromiseProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPromise(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Promise{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestActionProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestActionMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkActionProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedAction(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkActionProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedAction(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Action{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_NopProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Nop{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestAction_NopMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Nop{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkAction_NopProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Nop, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedAction_Nop(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkAction_NopProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedAction_Nop(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Action_Nop{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_AppendProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Append{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestAction_AppendMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Append{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkAction_AppendProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Append, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedAction_Append(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkAction_AppendProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedAction_Append(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Action_Append{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_TruncateProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Truncate{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestAction_TruncateMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Truncate{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkAction_TruncateProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Truncate, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedAction_Truncate(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkAction_TruncateProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedAction_Truncate(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Action_Truncate{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestMetadataProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Metadata{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestMetadataMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Metadata{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkMetadataProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Metadata, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedMetadata(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkMetadataProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetadata(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Metadata{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecordProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Record{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRecordMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Record{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRecordProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Record, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRecord(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRecordProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRecord(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Record{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseRequestProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPromiseRequestMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPromiseRequestProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PromiseRequest, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPromiseRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPromiseRequestProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPromiseRequest(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &PromiseRequest{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseResponseProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPromiseResponseMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPromiseResponseProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PromiseResponse, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPromiseResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPromiseResponseProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPromiseResponse(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &PromiseResponse{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestWriteRequestProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestWriteRequestMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkWriteRequestProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*WriteRequest, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedWriteRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkWriteRequestProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedWriteRequest(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &WriteRequest{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestWriteResponseProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestWriteResponseMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkWriteResponseProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*WriteResponse, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedWriteResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkWriteResponseProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedWriteResponse(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &WriteResponse{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestLearnedMessageProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &LearnedMessage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestLearnedMessageMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &LearnedMessage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkLearnedMessageProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*LearnedMessage, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedLearnedMessage(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkLearnedMessageProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedLearnedMessage(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &LearnedMessage{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecoverRequestProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRecoverRequestMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRecoverRequestProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RecoverRequest, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRecoverRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRecoverRequestProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRecoverRequest(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &RecoverRequest{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecoverResponseProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRecoverResponseMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRecoverResponseProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RecoverResponse, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRecoverResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRecoverResponseProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRecoverResponse(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &RecoverResponse{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Promise{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestActionJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestAction_NopJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Nop{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestAction_AppendJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Append{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestAction_TruncateJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Action_Truncate{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestMetadataJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Metadata{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRecordJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Record{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPromiseRequestJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseRequest{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPromiseResponseJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PromiseResponse{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestWriteRequestJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteRequest{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestWriteResponseJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &WriteResponse{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestLearnedMessageJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &LearnedMessage{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRecoverRequestJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverRequest{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRecoverResponseJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RecoverResponse{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPromiseProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Promise{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Promise{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestActionProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Action{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestActionProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Action{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_NopProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Action_Nop{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_NopProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Action_Nop{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_AppendProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Action_Append{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_AppendProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Action_Append{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_TruncateProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Action_Truncate{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAction_TruncateProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Action_Truncate{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestMetadataProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Metadata{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestMetadataProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Metadata{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecordProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Record{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecordProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Record{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseRequestProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &PromiseRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseRequestProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &PromiseRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseResponseProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &PromiseResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseResponseProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &PromiseResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestWriteRequestProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &WriteRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestWriteRequestProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &WriteRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestWriteResponseProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &WriteResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestWriteResponseProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &WriteResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLearnedMessageProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &LearnedMessage{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLearnedMessageProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &LearnedMessage{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecoverRequestProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &RecoverRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecoverRequestProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &RecoverRequest{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecoverResponseProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &RecoverResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRecoverResponseProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &RecoverResponse{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPromiseVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromise(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Promise{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestActionVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Action{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestAction_NopVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Nop(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Action_Nop{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestAction_AppendVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Append(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Action_Append{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestAction_TruncateVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Truncate(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Action_Truncate{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestMetadataVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMetadata(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Metadata{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRecordVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecord(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Record{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPromiseRequestVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &PromiseRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPromiseResponseVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &PromiseResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestWriteRequestVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &WriteRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestWriteResponseVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &WriteResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestLearnedMessageVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLearnedMessage(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &LearnedMessage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRecoverRequestVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &RecoverRequest{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRecoverResponseVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverResponse(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &RecoverResponse{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPromiseGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromise(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestActionGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestAction_NopGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Nop(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestAction_AppendGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Append(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestAction_TruncateGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Truncate(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestMetadataGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMetadata(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRecordGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecord(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPromiseRequestGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseRequest(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPromiseResponseGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseResponse(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestWriteRequestGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteRequest(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestWriteResponseGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteResponse(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestLearnedMessageGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLearnedMessage(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRecoverRequestGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverRequest(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRecoverResponseGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverResponse(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPromiseSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromise(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPromiseSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Promise, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPromise(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestActionSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkActionSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedAction(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_NopSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Nop(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkAction_NopSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Nop, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedAction_Nop(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_AppendSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Append(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkAction_AppendSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Append, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedAction_Append(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestAction_TruncateSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAction_Truncate(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkAction_TruncateSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Action_Truncate, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedAction_Truncate(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestMetadataSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMetadata(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkMetadataSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Metadata, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedMetadata(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecordSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecord(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRecordSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Record, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRecord(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseRequestSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseRequest(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPromiseRequestSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PromiseRequest, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPromiseRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseResponseSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPromiseResponse(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPromiseResponseSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PromiseResponse, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPromiseResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestWriteRequestSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteRequest(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkWriteRequestSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*WriteRequest, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedWriteRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestWriteResponseSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedWriteResponse(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkWriteResponseSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*WriteResponse, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedWriteResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestLearnedMessageSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLearnedMessage(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkLearnedMessageSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*LearnedMessage, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedLearnedMessage(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecoverRequestSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverRequest(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRecoverRequestSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RecoverRequest, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRecoverRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRecoverResponseSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRecoverResponse(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRecoverResponseSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RecoverResponse, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRecoverResponse(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPromiseStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromise(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestActionStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestAction_NopStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Nop(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestAction_AppendStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Append(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestAction_TruncateStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAction_Truncate(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestMetadataStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMetadata(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRecordStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecord(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestPromiseRequestStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseRequest(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestPromiseResponseStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPromiseResponse(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestWriteRequestStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteRequest(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestWriteResponseStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedWriteResponse(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestLearnedMessageStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLearnedMessage(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRecoverRequestStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverRequest(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRecoverResponseStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRecoverResponse(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} - -//These tests are generated by github.com/gogo/protobuf/plugin/testgen diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/mesospb_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/mesospb_test.go deleted file mode 100644 index aef9eac8010..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/mesospb_test.go +++ /dev/null @@ -1,15435 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: mesos.proto -// DO NOT EDIT! - -package mesosproto - -import testing "testing" -import math_rand "math/rand" -import time "time" -import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" -import github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb" -import fmt "fmt" -import go_parser "go/parser" -import proto "github.com/gogo/protobuf/proto" -import math "math" - -// discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -func TestFrameworkIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestFrameworkIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkFrameworkIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedFrameworkID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkFrameworkIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedFrameworkID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &FrameworkID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOfferIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &OfferID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOfferIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &OfferID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOfferIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*OfferID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOfferID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOfferIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOfferID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &OfferID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestSlaveIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestSlaveIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkSlaveIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*SlaveID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedSlaveID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkSlaveIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedSlaveID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &SlaveID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestTaskIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkTaskIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedTaskID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkTaskIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedTaskID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &TaskID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestExecutorIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestExecutorIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkExecutorIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ExecutorID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedExecutorID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkExecutorIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedExecutorID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ExecutorID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerIDProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestContainerIDMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkContainerIDProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerID, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedContainerID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkContainerIDProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedContainerID(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ContainerID{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestFrameworkInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkFrameworkInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedFrameworkInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkFrameworkInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedFrameworkInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &FrameworkInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkInfo_CapabilityProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo_Capability{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestFrameworkInfo_CapabilityMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo_Capability{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkFrameworkInfo_CapabilityProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkInfo_Capability, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedFrameworkInfo_Capability(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkFrameworkInfo_CapabilityProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedFrameworkInfo_Capability(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &FrameworkInfo_Capability{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestHealthCheckProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestHealthCheckMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkHealthCheckProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*HealthCheck, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedHealthCheck(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkHealthCheckProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedHealthCheck(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &HealthCheck{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestHealthCheck_HTTPProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck_HTTP{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestHealthCheck_HTTPMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck_HTTP{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkHealthCheck_HTTPProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*HealthCheck_HTTP, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedHealthCheck_HTTP(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkHealthCheck_HTTPProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedHealthCheck_HTTP(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &HealthCheck_HTTP{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestCommandInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkCommandInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedCommandInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkCommandInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedCommandInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &CommandInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfo_URIProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_URI{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestCommandInfo_URIMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_URI{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkCommandInfo_URIProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo_URI, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedCommandInfo_URI(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkCommandInfo_URIProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedCommandInfo_URI(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &CommandInfo_URI{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfo_ContainerInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestCommandInfo_ContainerInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkCommandInfo_ContainerInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo_ContainerInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedCommandInfo_ContainerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkCommandInfo_ContainerInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedCommandInfo_ContainerInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &CommandInfo_ContainerInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestExecutorInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestExecutorInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkExecutorInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ExecutorInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedExecutorInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkExecutorInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedExecutorInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ExecutorInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestMasterInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &MasterInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestMasterInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &MasterInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkMasterInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*MasterInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedMasterInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkMasterInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMasterInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &MasterInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestSlaveInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestSlaveInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkSlaveInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*SlaveInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedSlaveInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkSlaveInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedSlaveInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &SlaveInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValueProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValueMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValueProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValueProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_ScalarProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Scalar{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValue_ScalarMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Scalar{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValue_ScalarProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Scalar, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue_Scalar(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValue_ScalarProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue_Scalar(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value_Scalar{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_RangeProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Range{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValue_RangeMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Range{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValue_RangeProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Range, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue_Range(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValue_RangeProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue_Range(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value_Range{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_RangesProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Ranges{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValue_RangesMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Ranges{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValue_RangesProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Ranges, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue_Ranges(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValue_RangesProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue_Ranges(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value_Ranges{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_SetProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Set{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValue_SetMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Set{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValue_SetProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Set, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue_Set(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValue_SetProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue_Set(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value_Set{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_TextProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Text{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestValue_TextMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Text{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkValue_TextProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Text, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedValue_Text(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkValue_TextProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedValue_Text(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Value_Text{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestAttributeProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Attribute{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestAttributeMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Attribute{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkAttributeProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Attribute, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedAttribute(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkAttributeProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedAttribute(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Attribute{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResourceMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResourceProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResource(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResourceProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResource(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Resource{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_ReservationInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_ReservationInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResource_ReservationInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_ReservationInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResource_ReservationInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_ReservationInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResource_ReservationInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResource_ReservationInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResource_ReservationInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Resource_ReservationInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_DiskInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResource_DiskInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResource_DiskInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_DiskInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResource_DiskInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResource_DiskInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResource_DiskInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Resource_DiskInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_DiskInfo_PersistenceProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo_Persistence{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResource_DiskInfo_PersistenceMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo_Persistence{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResource_DiskInfo_PersistenceProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_DiskInfo_Persistence, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResource_DiskInfo_Persistence(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResource_DiskInfo_PersistenceProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResource_DiskInfo_Persistence(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Resource_DiskInfo_Persistence{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_RevocableInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_RevocableInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResource_RevocableInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_RevocableInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResource_RevocableInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_RevocableInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResource_RevocableInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResource_RevocableInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResource_RevocableInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Resource_RevocableInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestTrafficControlStatisticsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TrafficControlStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestTrafficControlStatisticsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TrafficControlStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkTrafficControlStatisticsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TrafficControlStatistics, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedTrafficControlStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkTrafficControlStatisticsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedTrafficControlStatistics(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &TrafficControlStatistics{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceStatisticsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResourceStatisticsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResourceStatisticsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceStatistics, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResourceStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResourceStatisticsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResourceStatistics(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ResourceStatistics{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceUsageProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResourceUsageMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResourceUsageProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceUsage, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResourceUsage(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResourceUsageProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResourceUsage(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ResourceUsage{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceUsage_ExecutorProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage_Executor{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestResourceUsage_ExecutorMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage_Executor{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkResourceUsage_ExecutorProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceUsage_Executor, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedResourceUsage_Executor(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkResourceUsage_ExecutorProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedResourceUsage_Executor(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ResourceUsage_Executor{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPerfStatisticsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PerfStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPerfStatisticsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PerfStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPerfStatisticsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PerfStatistics, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPerfStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPerfStatisticsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPerfStatistics(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &PerfStatistics{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRequestProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Request{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRequestMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Request{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRequestProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Request, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRequestProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRequest(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Request{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOfferProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOfferMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOfferProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOfferProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_OperationProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_OperationMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_OperationProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_OperationProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_LaunchProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Launch{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_Operation_LaunchMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Launch{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_Operation_LaunchProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Launch, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation_Launch(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_Operation_LaunchProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation_Launch(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation_Launch{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_ReserveProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Reserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_Operation_ReserveMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Reserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_Operation_ReserveProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Reserve, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation_Reserve(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_Operation_ReserveProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation_Reserve(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation_Reserve{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_UnreserveProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Unreserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_Operation_UnreserveMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Unreserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_Operation_UnreserveProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Unreserve, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation_Unreserve(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_Operation_UnreserveProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation_Unreserve(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation_Unreserve{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_CreateProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Create{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_Operation_CreateMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Create{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_Operation_CreateProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Create, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation_Create(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_Operation_CreateProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation_Create(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation_Create{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_DestroyProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Destroy{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOffer_Operation_DestroyMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Destroy{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOffer_Operation_DestroyProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Destroy, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOffer_Operation_Destroy(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOffer_Operation_DestroyProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOffer_Operation_Destroy(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Offer_Operation_Destroy{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestTaskInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkTaskInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedTaskInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkTaskInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedTaskInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &TaskInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskStatusProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskStatus{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestTaskStatusMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskStatus{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkTaskStatusProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskStatus, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedTaskStatus(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkTaskStatusProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedTaskStatus(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &TaskStatus{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestFiltersProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Filters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestFiltersMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Filters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkFiltersProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Filters, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedFilters(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkFiltersProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedFilters(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Filters{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestEnvironmentProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestEnvironmentMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkEnvironmentProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Environment, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedEnvironment(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkEnvironmentProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedEnvironment(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Environment{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestEnvironment_VariableProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment_Variable{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestEnvironment_VariableMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment_Variable{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkEnvironment_VariableProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Environment_Variable, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedEnvironment_Variable(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkEnvironment_VariableProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedEnvironment_Variable(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Environment_Variable{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestParameterProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameter{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestParameterMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameter{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkParameterProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Parameter, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedParameter(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkParameterProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedParameter(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Parameter{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestParametersProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestParametersMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkParametersProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Parameters, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedParameters(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkParametersProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedParameters(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Parameters{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestCredentialProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credential{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestCredentialMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credential{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkCredentialProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Credential, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedCredential(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkCredentialProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedCredential(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Credential{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestCredentialsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credentials{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestCredentialsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credentials{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkCredentialsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Credentials, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedCredentials(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkCredentialsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedCredentials(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Credentials{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACLProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACLMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACLProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACL(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACLProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACL(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACL{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_EntityProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_Entity{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACL_EntityMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_Entity{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACL_EntityProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_Entity, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACL_Entity(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACL_EntityProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACL_Entity(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACL_Entity{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_RegisterFrameworkProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RegisterFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACL_RegisterFrameworkMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RegisterFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACL_RegisterFrameworkProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_RegisterFramework, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACL_RegisterFramework(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACL_RegisterFrameworkProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACL_RegisterFramework(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACL_RegisterFramework{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_RunTaskProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RunTask{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACL_RunTaskMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RunTask{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACL_RunTaskProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_RunTask, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACL_RunTask(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACL_RunTaskProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACL_RunTask(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACL_RunTask{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_ShutdownFrameworkProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_ShutdownFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACL_ShutdownFrameworkMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_ShutdownFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACL_ShutdownFrameworkProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_ShutdownFramework, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACL_ShutdownFramework(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACL_ShutdownFrameworkProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACL_ShutdownFramework(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACL_ShutdownFramework{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestACLsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACLs{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestACLsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACLs{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkACLsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACLs, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedACLs(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkACLsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedACLs(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ACLs{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRateLimitProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimit{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRateLimitMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimit{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRateLimitProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RateLimit, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRateLimit(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRateLimitProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRateLimit(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &RateLimit{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestRateLimitsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimits{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestRateLimitsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimits{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkRateLimitsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RateLimits, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedRateLimits(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkRateLimitsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedRateLimits(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &RateLimits{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestVolumeProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Volume{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestVolumeMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Volume{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkVolumeProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Volume, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedVolume(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkVolumeProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedVolume(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Volume{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestContainerInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkContainerInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedContainerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkContainerInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedContainerInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ContainerInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfo_DockerInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestContainerInfo_DockerInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkContainerInfo_DockerInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo_DockerInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedContainerInfo_DockerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkContainerInfo_DockerInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedContainerInfo_DockerInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ContainerInfo_DockerInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfo_DockerInfo_PortMappingProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo_PortMapping{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestContainerInfo_DockerInfo_PortMappingMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo_PortMapping{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkContainerInfo_DockerInfo_PortMappingProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo_DockerInfo_PortMapping, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkContainerInfo_DockerInfo_PortMappingProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &ContainerInfo_DockerInfo_PortMapping{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestLabelsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Labels{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestLabelsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Labels{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkLabelsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Labels, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedLabels(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkLabelsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedLabels(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Labels{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestLabelProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Label{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestLabelMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Label{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkLabelProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Label, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedLabel(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkLabelProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedLabel(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Label{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPortProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Port{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPortMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Port{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPortProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Port, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPort(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPortProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPort(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Port{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestPortsProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Ports{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestPortsMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Ports{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkPortsProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Ports, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedPorts(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkPortsProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedPorts(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Ports{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestDiscoveryInfoProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &DiscoveryInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestDiscoveryInfoMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &DiscoveryInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkDiscoveryInfoProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*DiscoveryInfo, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedDiscoveryInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkDiscoveryInfoProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedDiscoveryInfo(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &DiscoveryInfo{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOfferIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &OfferID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestSlaveIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestTaskIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestExecutorIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestContainerIDJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerID{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestFrameworkInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestFrameworkInfo_CapabilityJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &FrameworkInfo_Capability{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestHealthCheckJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestHealthCheck_HTTPJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &HealthCheck_HTTP{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestCommandInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestCommandInfo_URIJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_URI{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestCommandInfo_ContainerInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &CommandInfo_ContainerInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestExecutorInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ExecutorInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestMasterInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &MasterInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestSlaveInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &SlaveInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValueJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValue_ScalarJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Scalar{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValue_RangeJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Range{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValue_RangesJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Ranges{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValue_SetJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Set{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestValue_TextJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Value_Text{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestAttributeJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Attribute{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResourceJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResource_ReservationInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_ReservationInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResource_DiskInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResource_DiskInfo_PersistenceJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_DiskInfo_Persistence{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResource_RevocableInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Resource_RevocableInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestTrafficControlStatisticsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TrafficControlStatistics{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResourceStatisticsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceStatistics{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResourceUsageJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestResourceUsage_ExecutorJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ResourceUsage_Executor{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPerfStatisticsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &PerfStatistics{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRequestJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Request{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOfferJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_OperationJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_Operation_LaunchJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Launch{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_Operation_ReserveJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Reserve{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_Operation_UnreserveJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Unreserve{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_Operation_CreateJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Create{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOffer_Operation_DestroyJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Offer_Operation_Destroy{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestTaskInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestTaskStatusJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &TaskStatus{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestFiltersJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Filters{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestEnvironmentJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestEnvironment_VariableJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Environment_Variable{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestParameterJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameter{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestParametersJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Parameters{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestCredentialJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credential{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestCredentialsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Credentials{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACLJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACL_EntityJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_Entity{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACL_RegisterFrameworkJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RegisterFramework{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACL_RunTaskJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_RunTask{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACL_ShutdownFrameworkJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACL_ShutdownFramework{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestACLsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ACLs{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRateLimitJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimit{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestRateLimitsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &RateLimits{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestVolumeJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Volume{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestContainerInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestContainerInfo_DockerInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestContainerInfo_DockerInfo_PortMappingJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &ContainerInfo_DockerInfo_PortMapping{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestLabelsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Labels{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestLabelJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Label{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPortJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Port{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestPortsJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Ports{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestDiscoveryInfoJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &DiscoveryInfo{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestFrameworkIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &FrameworkID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &FrameworkID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOfferIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &OfferID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOfferIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &OfferID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestSlaveIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &SlaveID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestSlaveIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &SlaveID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &TaskID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &TaskID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestExecutorIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ExecutorID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestExecutorIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ExecutorID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerIDProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ContainerID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerIDProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ContainerID{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &FrameworkInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &FrameworkInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkInfo_CapabilityProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &FrameworkInfo_Capability{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkInfo_CapabilityProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &FrameworkInfo_Capability{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestHealthCheckProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &HealthCheck{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestHealthCheckProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &HealthCheck{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestHealthCheck_HTTPProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &HealthCheck_HTTP{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestHealthCheck_HTTPProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &HealthCheck_HTTP{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &CommandInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &CommandInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfo_URIProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &CommandInfo_URI{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfo_URIProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &CommandInfo_URI{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfo_ContainerInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &CommandInfo_ContainerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCommandInfo_ContainerInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &CommandInfo_ContainerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestExecutorInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ExecutorInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestExecutorInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ExecutorInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestMasterInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &MasterInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestMasterInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &MasterInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestSlaveInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &SlaveInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestSlaveInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &SlaveInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValueProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValueProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_ScalarProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value_Scalar{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_ScalarProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value_Scalar{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_RangeProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value_Range{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_RangeProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value_Range{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_RangesProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value_Ranges{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_RangesProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value_Ranges{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_SetProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value_Set{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_SetProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value_Set{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_TextProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Value_Text{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestValue_TextProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Value_Text{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAttributeProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Attribute{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestAttributeProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Attribute{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Resource{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Resource{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_ReservationInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Resource_ReservationInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_ReservationInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Resource_ReservationInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_DiskInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Resource_DiskInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_DiskInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Resource_DiskInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_DiskInfo_PersistenceProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Resource_DiskInfo_Persistence{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_DiskInfo_PersistenceProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Resource_DiskInfo_Persistence{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_RevocableInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Resource_RevocableInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResource_RevocableInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Resource_RevocableInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTrafficControlStatisticsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &TrafficControlStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTrafficControlStatisticsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &TrafficControlStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceStatisticsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ResourceStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceStatisticsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ResourceStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceUsageProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ResourceUsage{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceUsageProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ResourceUsage{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceUsage_ExecutorProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ResourceUsage_Executor{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestResourceUsage_ExecutorProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ResourceUsage_Executor{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPerfStatisticsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &PerfStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPerfStatisticsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &PerfStatistics{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRequestProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Request{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRequestProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Request{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOfferProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOfferProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_OperationProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_OperationProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_LaunchProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation_Launch{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_LaunchProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation_Launch{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_ReserveProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation_Reserve{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_ReserveProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation_Reserve{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_UnreserveProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation_Unreserve{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_UnreserveProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation_Unreserve{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_CreateProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation_Create{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_CreateProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation_Create{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_DestroyProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Offer_Operation_Destroy{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOffer_Operation_DestroyProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Offer_Operation_Destroy{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &TaskInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &TaskInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskStatusProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &TaskStatus{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestTaskStatusProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &TaskStatus{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFiltersProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Filters{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFiltersProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Filters{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEnvironmentProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Environment{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEnvironmentProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Environment{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEnvironment_VariableProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Environment_Variable{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEnvironment_VariableProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Environment_Variable{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestParameterProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Parameter{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestParameterProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Parameter{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestParametersProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Parameters{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestParametersProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Parameters{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCredentialProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Credential{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCredentialProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Credential{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCredentialsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Credentials{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestCredentialsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Credentials{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACLProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACL{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACLProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACL{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_EntityProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACL_Entity{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_EntityProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACL_Entity{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_RegisterFrameworkProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACL_RegisterFramework{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_RegisterFrameworkProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACL_RegisterFramework{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_RunTaskProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACL_RunTask{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_RunTaskProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACL_RunTask{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_ShutdownFrameworkProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACL_ShutdownFramework{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACL_ShutdownFrameworkProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACL_ShutdownFramework{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACLsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ACLs{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestACLsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ACLs{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRateLimitProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &RateLimit{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRateLimitProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &RateLimit{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRateLimitsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &RateLimits{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestRateLimitsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &RateLimits{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestVolumeProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Volume{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestVolumeProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Volume{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ContainerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ContainerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfo_DockerInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ContainerInfo_DockerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfo_DockerInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ContainerInfo_DockerInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfo_DockerInfo_PortMappingProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &ContainerInfo_DockerInfo_PortMapping{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestContainerInfo_DockerInfo_PortMappingProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &ContainerInfo_DockerInfo_PortMapping{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLabelsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Labels{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLabelsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Labels{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLabelProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Label{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestLabelProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Label{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPortProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Port{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPortProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Port{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPortsProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Ports{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestPortsProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Ports{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestDiscoveryInfoProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &DiscoveryInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestDiscoveryInfoProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &DiscoveryInfo{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestFrameworkIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &FrameworkID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOfferIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOfferID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &OfferID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestSlaveIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &SlaveID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestTaskIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &TaskID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestExecutorIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ExecutorID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestContainerIDVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerID(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ContainerID{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestFrameworkInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &FrameworkInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestFrameworkInfo_CapabilityVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo_Capability(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &FrameworkInfo_Capability{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestHealthCheckVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &HealthCheck{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestHealthCheck_HTTPVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck_HTTP(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &HealthCheck_HTTP{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestCommandInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &CommandInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestCommandInfo_URIVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_URI(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &CommandInfo_URI{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestCommandInfo_ContainerInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_ContainerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &CommandInfo_ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestExecutorInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ExecutorInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestMasterInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMasterInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &MasterInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestSlaveInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &SlaveInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValueVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValue_ScalarVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Scalar(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value_Scalar{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValue_RangeVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Range(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value_Range{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValue_RangesVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Ranges(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value_Ranges{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValue_SetVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Set(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value_Set{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestValue_TextVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Text(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Value_Text{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestAttributeVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAttribute(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Attribute{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResourceVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Resource{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResource_ReservationInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_ReservationInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Resource_ReservationInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResource_DiskInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Resource_DiskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResource_DiskInfo_PersistenceVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo_Persistence(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Resource_DiskInfo_Persistence{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResource_RevocableInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_RevocableInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Resource_RevocableInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestTrafficControlStatisticsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTrafficControlStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &TrafficControlStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResourceStatisticsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ResourceStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResourceUsageVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ResourceUsage{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestResourceUsage_ExecutorVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage_Executor(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ResourceUsage_Executor{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPerfStatisticsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPerfStatistics(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &PerfStatistics{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRequestVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRequest(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Request{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOfferVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_OperationVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_Operation_LaunchVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Launch(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation_Launch{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_Operation_ReserveVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Reserve(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation_Reserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_Operation_UnreserveVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Unreserve(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation_Unreserve{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_Operation_CreateVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Create(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation_Create{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOffer_Operation_DestroyVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Destroy(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Offer_Operation_Destroy{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestTaskInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &TaskInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestTaskStatusVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskStatus(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &TaskStatus{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestFiltersVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFilters(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Filters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestEnvironmentVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Environment{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestEnvironment_VariableVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment_Variable(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Environment_Variable{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestParameterVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameter(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Parameter{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestParametersVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameters(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Parameters{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestCredentialVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredential(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Credential{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestCredentialsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredentials(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Credentials{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACLVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACL{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACL_EntityVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_Entity(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACL_Entity{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACL_RegisterFrameworkVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RegisterFramework(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACL_RegisterFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACL_RunTaskVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RunTask(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACL_RunTask{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACL_ShutdownFrameworkVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_ShutdownFramework(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACL_ShutdownFramework{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestACLsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACLs(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ACLs{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRateLimitVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimit(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &RateLimit{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestRateLimitsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimits(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &RateLimits{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestVolumeVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedVolume(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Volume{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestContainerInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ContainerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestContainerInfo_DockerInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ContainerInfo_DockerInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestContainerInfo_DockerInfo_PortMappingVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &ContainerInfo_DockerInfo_PortMapping{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestLabelsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabels(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Labels{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestLabelVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabel(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Label{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPortVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPort(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Port{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestPortsVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPorts(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Ports{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestDiscoveryInfoVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedDiscoveryInfo(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &DiscoveryInfo{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestFrameworkIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOfferIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOfferID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestSlaveIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestTaskIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestExecutorIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestContainerIDGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerID(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestFrameworkInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestFrameworkInfo_CapabilityGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo_Capability(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestHealthCheckGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestHealthCheck_HTTPGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck_HTTP(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestCommandInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestCommandInfo_URIGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_URI(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestCommandInfo_ContainerInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_ContainerInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestExecutorInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestMasterInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMasterInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestSlaveInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValueGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValue_ScalarGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Scalar(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValue_RangeGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Range(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValue_RangesGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Ranges(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValue_SetGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Set(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestValue_TextGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Text(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestAttributeGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAttribute(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResourceGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResource_ReservationInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_ReservationInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResource_DiskInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResource_DiskInfo_PersistenceGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo_Persistence(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResource_RevocableInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_RevocableInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestTrafficControlStatisticsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTrafficControlStatistics(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResourceStatisticsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceStatistics(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResourceUsageGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestResourceUsage_ExecutorGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage_Executor(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPerfStatisticsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPerfStatistics(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRequestGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRequest(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOfferGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_OperationGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_Operation_LaunchGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Launch(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_Operation_ReserveGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Reserve(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_Operation_UnreserveGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Unreserve(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_Operation_CreateGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Create(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOffer_Operation_DestroyGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Destroy(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestTaskInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestTaskStatusGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskStatus(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestFiltersGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFilters(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestEnvironmentGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestEnvironment_VariableGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment_Variable(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestParameterGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameter(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestParametersGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameters(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestCredentialGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredential(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestCredentialsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredentials(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACLGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACL_EntityGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_Entity(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACL_RegisterFrameworkGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RegisterFramework(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACL_RunTaskGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RunTask(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACL_ShutdownFrameworkGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_ShutdownFramework(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestACLsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACLs(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRateLimitGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimit(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestRateLimitsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimits(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestVolumeGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedVolume(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestContainerInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestContainerInfo_DockerInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestContainerInfo_DockerInfo_PortMappingGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestLabelsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabels(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestLabelGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabel(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPortGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPort(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestPortsGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPorts(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestDiscoveryInfoGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedDiscoveryInfo(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestFrameworkIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkFrameworkIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedFrameworkID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOfferIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOfferID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOfferIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*OfferID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOfferID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestSlaveIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkSlaveIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*SlaveID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedSlaveID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkTaskIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedTaskID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestExecutorIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkExecutorIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ExecutorID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedExecutorID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerIDSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerID(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkContainerIDSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerID, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedContainerID(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkFrameworkInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedFrameworkInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkInfo_CapabilitySize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFrameworkInfo_Capability(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkFrameworkInfo_CapabilitySize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*FrameworkInfo_Capability, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedFrameworkInfo_Capability(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestHealthCheckSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkHealthCheckSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*HealthCheck, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedHealthCheck(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestHealthCheck_HTTPSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedHealthCheck_HTTP(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkHealthCheck_HTTPSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*HealthCheck_HTTP, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedHealthCheck_HTTP(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkCommandInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedCommandInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfo_URISize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_URI(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkCommandInfo_URISize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo_URI, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedCommandInfo_URI(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestCommandInfo_ContainerInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCommandInfo_ContainerInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkCommandInfo_ContainerInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*CommandInfo_ContainerInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedCommandInfo_ContainerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestExecutorInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedExecutorInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkExecutorInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ExecutorInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedExecutorInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestMasterInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedMasterInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkMasterInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*MasterInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedMasterInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestSlaveInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedSlaveInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkSlaveInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*SlaveInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedSlaveInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValueSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValueSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_ScalarSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Scalar(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValue_ScalarSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Scalar, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue_Scalar(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_RangeSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Range(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValue_RangeSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Range, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue_Range(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_RangesSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Ranges(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValue_RangesSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Ranges, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue_Ranges(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_SetSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Set(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValue_SetSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Set, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue_Set(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestValue_TextSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedValue_Text(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkValue_TextSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Value_Text, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedValue_Text(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestAttributeSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedAttribute(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkAttributeSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Attribute, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedAttribute(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResourceSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResource(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_ReservationInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_ReservationInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResource_ReservationInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_ReservationInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResource_ReservationInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_DiskInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResource_DiskInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_DiskInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResource_DiskInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_DiskInfo_PersistenceSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_DiskInfo_Persistence(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResource_DiskInfo_PersistenceSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_DiskInfo_Persistence, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResource_DiskInfo_Persistence(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResource_RevocableInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResource_RevocableInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResource_RevocableInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Resource_RevocableInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResource_RevocableInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestTrafficControlStatisticsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTrafficControlStatistics(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkTrafficControlStatisticsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TrafficControlStatistics, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedTrafficControlStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceStatisticsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceStatistics(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResourceStatisticsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceStatistics, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResourceStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceUsageSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResourceUsageSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceUsage, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResourceUsage(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestResourceUsage_ExecutorSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedResourceUsage_Executor(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkResourceUsage_ExecutorSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ResourceUsage_Executor, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedResourceUsage_Executor(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPerfStatisticsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPerfStatistics(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPerfStatisticsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*PerfStatistics, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPerfStatistics(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRequestSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRequest(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRequestSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Request, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRequest(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOfferSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOfferSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_OperationSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_OperationSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_LaunchSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Launch(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_Operation_LaunchSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Launch, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation_Launch(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_ReserveSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Reserve(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_Operation_ReserveSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Reserve, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation_Reserve(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_UnreserveSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Unreserve(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_Operation_UnreserveSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Unreserve, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation_Unreserve(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_CreateSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Create(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_Operation_CreateSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Create, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation_Create(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOffer_Operation_DestroySize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOffer_Operation_Destroy(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOffer_Operation_DestroySize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Offer_Operation_Destroy, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOffer_Operation_Destroy(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkTaskInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedTaskInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestTaskStatusSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedTaskStatus(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkTaskStatusSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*TaskStatus, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedTaskStatus(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestFiltersSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedFilters(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkFiltersSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Filters, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedFilters(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestEnvironmentSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkEnvironmentSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Environment, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedEnvironment(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestEnvironment_VariableSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEnvironment_Variable(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkEnvironment_VariableSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Environment_Variable, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedEnvironment_Variable(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestParameterSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameter(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkParameterSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Parameter, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedParameter(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestParametersSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedParameters(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkParametersSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Parameters, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedParameters(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestCredentialSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredential(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkCredentialSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Credential, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedCredential(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestCredentialsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedCredentials(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkCredentialsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Credentials, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedCredentials(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACLSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACLSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACL(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_EntitySize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_Entity(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACL_EntitySize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_Entity, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACL_Entity(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_RegisterFrameworkSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RegisterFramework(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACL_RegisterFrameworkSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_RegisterFramework, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACL_RegisterFramework(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_RunTaskSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_RunTask(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACL_RunTaskSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_RunTask, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACL_RunTask(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACL_ShutdownFrameworkSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACL_ShutdownFramework(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACL_ShutdownFrameworkSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACL_ShutdownFramework, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACL_ShutdownFramework(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestACLsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedACLs(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkACLsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ACLs, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedACLs(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRateLimitSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimit(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRateLimitSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RateLimit, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRateLimit(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestRateLimitsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedRateLimits(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkRateLimitsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*RateLimits, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedRateLimits(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestVolumeSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedVolume(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkVolumeSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Volume, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedVolume(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkContainerInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedContainerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfo_DockerInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkContainerInfo_DockerInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo_DockerInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedContainerInfo_DockerInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestContainerInfo_DockerInfo_PortMappingSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkContainerInfo_DockerInfo_PortMappingSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*ContainerInfo_DockerInfo_PortMapping, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestLabelsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabels(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkLabelsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Labels, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedLabels(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestLabelSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedLabel(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkLabelSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Label, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedLabel(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPortSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPort(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPortSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Port, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPort(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestPortsSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedPorts(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkPortsSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Ports, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedPorts(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestDiscoveryInfoSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedDiscoveryInfo(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkDiscoveryInfoSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*DiscoveryInfo, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedDiscoveryInfo(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestFrameworkIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOfferIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOfferID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestSlaveIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestTaskIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestExecutorIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestContainerIDStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerID(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestFrameworkInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestFrameworkInfo_CapabilityStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFrameworkInfo_Capability(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestHealthCheckStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestHealthCheck_HTTPStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedHealthCheck_HTTP(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestCommandInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestCommandInfo_URIStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_URI(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestCommandInfo_ContainerInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCommandInfo_ContainerInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestExecutorInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedExecutorInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestMasterInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedMasterInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestSlaveInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedSlaveInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValueStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValue_ScalarStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Scalar(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValue_RangeStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Range(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValue_RangesStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Ranges(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValue_SetStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Set(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestValue_TextStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedValue_Text(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestAttributeStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedAttribute(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResourceStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResource_ReservationInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_ReservationInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResource_DiskInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResource_DiskInfo_PersistenceStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_DiskInfo_Persistence(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResource_RevocableInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResource_RevocableInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestTrafficControlStatisticsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTrafficControlStatistics(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResourceStatisticsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceStatistics(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResourceUsageStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestResourceUsage_ExecutorStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedResourceUsage_Executor(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestPerfStatisticsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPerfStatistics(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRequestStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRequest(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOfferStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_OperationStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_Operation_LaunchStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Launch(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_Operation_ReserveStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Reserve(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_Operation_UnreserveStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Unreserve(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_Operation_CreateStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Create(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOffer_Operation_DestroyStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOffer_Operation_Destroy(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestTaskInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestTaskStatusStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedTaskStatus(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestFiltersStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedFilters(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestEnvironmentStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestEnvironment_VariableStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEnvironment_Variable(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestParameterStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameter(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestParametersStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedParameters(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestCredentialStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredential(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestCredentialsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedCredentials(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACLStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACL_EntityStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_Entity(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACL_RegisterFrameworkStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RegisterFramework(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACL_RunTaskStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_RunTask(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACL_ShutdownFrameworkStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACL_ShutdownFramework(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestACLsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedACLs(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRateLimitStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimit(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestRateLimitsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedRateLimits(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestVolumeStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedVolume(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestContainerInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestContainerInfo_DockerInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestContainerInfo_DockerInfo_PortMappingStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedContainerInfo_DockerInfo_PortMapping(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestLabelsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabels(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestLabelStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedLabel(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestPortStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPort(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestPortsStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedPorts(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestDiscoveryInfoStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedDiscoveryInfo(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} - -//These tests are generated by github.com/gogo/protobuf/plugin/testgen diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/statepb_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/statepb_test.go deleted file mode 100644 index 89870c024c4..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosproto/statepb_test.go +++ /dev/null @@ -1,1175 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: state.proto -// DO NOT EDIT! - -package mesosproto - -import testing "testing" -import math_rand "math/rand" -import time "time" -import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" -import github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb" -import fmt "fmt" -import go_parser "go/parser" -import proto "github.com/gogo/protobuf/proto" -import math "math" - -// discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -func TestEntryProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Entry{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestEntryMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Entry{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkEntryProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Entry, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedEntry(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkEntryProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedEntry(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Entry{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperationProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOperationMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOperationProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOperation(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOperationProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOperation(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Operation{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_SnapshotProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Snapshot{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOperation_SnapshotMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Snapshot{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOperation_SnapshotProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Snapshot, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOperation_Snapshot(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOperation_SnapshotProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOperation_Snapshot(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Operation_Snapshot{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_DiffProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Diff{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOperation_DiffMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Diff{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOperation_DiffProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Diff, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOperation_Diff(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOperation_DiffProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOperation_Diff(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Operation_Diff{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_ExpungeProto(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Expunge{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - littlefuzz := make([]byte, len(data)) - copy(littlefuzz, data) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } - if len(littlefuzz) > 0 { - fuzzamount := 100 - for i := 0; i < fuzzamount; i++ { - littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256)) - littlefuzz = append(littlefuzz, byte(popr.Intn(256))) - } - // shouldn't panic - _ = github_com_gogo_protobuf_proto.Unmarshal(littlefuzz, msg) - } -} - -func TestOperation_ExpungeMarshalTo(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, false) - size := p.Size() - data := make([]byte, size) - for i := range data { - data[i] = byte(popr.Intn(256)) - } - _, err := p.MarshalTo(data) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Expunge{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - for i := range data { - data[i] = byte(popr.Intn(256)) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func BenchmarkOperation_ExpungeProtoMarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Expunge, 10000) - for i := 0; i < 10000; i++ { - pops[i] = NewPopulatedOperation_Expunge(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000]) - if err != nil { - panic(err) - } - total += len(data) - } - b.SetBytes(int64(total / b.N)) -} - -func BenchmarkOperation_ExpungeProtoUnmarshal(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - datas := make([][]byte, 10000) - for i := 0; i < 10000; i++ { - data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedOperation_Expunge(popr, false)) - if err != nil { - panic(err) - } - datas[i] = data - } - msg := &Operation_Expunge{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += len(datas[i%10000]) - if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil { - panic(err) - } - } - b.SetBytes(int64(total / b.N)) -} - -func TestEntryJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Entry{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOperationJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOperation_SnapshotJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Snapshot{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOperation_DiffJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Diff{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestOperation_ExpungeJSON(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, true) - marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{} - jsondata, err := marshaler.MarshalToString(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - msg := &Operation_Expunge{} - err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p) - } -} -func TestEntryProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Entry{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEntryProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Entry{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperationProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Operation{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperationProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Operation{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_SnapshotProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Operation_Snapshot{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_SnapshotProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Operation_Snapshot{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_DiffProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Operation_Diff{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_DiffProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Operation_Diff{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_ExpungeProtoText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, true) - data := github_com_gogo_protobuf_proto.MarshalTextString(p) - msg := &Operation_Expunge{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestOperation_ExpungeProtoCompactText(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, true) - data := github_com_gogo_protobuf_proto.CompactTextString(p) - msg := &Operation_Expunge{} - if err := github_com_gogo_protobuf_proto.UnmarshalText(data, msg); err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("seed = %d, %#v !VerboseProto %#v, since %v", seed, msg, p, err) - } - if !p.Equal(msg) { - t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p) - } -} - -func TestEntryVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEntry(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Entry{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOperationVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Operation{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOperation_SnapshotVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Snapshot(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Operation_Snapshot{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOperation_DiffVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Diff(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Operation_Diff{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestOperation_ExpungeVerboseEqual(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Expunge(popr, false) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - panic(err) - } - msg := &Operation_Expunge{} - if err := github_com_gogo_protobuf_proto.Unmarshal(data, msg); err != nil { - panic(err) - } - if err := p.VerboseEqual(msg); err != nil { - t.Fatalf("%#v !VerboseEqual %#v, since %v", msg, p, err) - } -} -func TestEntryGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEntry(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOperationGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOperation_SnapshotGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Snapshot(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOperation_DiffGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Diff(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestOperation_ExpungeGoString(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Expunge(popr, false) - s1 := p.GoString() - s2 := fmt.Sprintf("%#v", p) - if s1 != s2 { - t.Fatalf("GoString want %v got %v", s1, s2) - } - _, err := go_parser.ParseExpr(s1) - if err != nil { - panic(err) - } -} -func TestEntrySize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedEntry(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkEntrySize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Entry, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedEntry(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperationSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOperationSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOperation(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_SnapshotSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Snapshot(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOperation_SnapshotSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Snapshot, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOperation_Snapshot(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_DiffSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Diff(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOperation_DiffSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Diff, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOperation_Diff(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestOperation_ExpungeSize(t *testing.T) { - seed := time.Now().UnixNano() - popr := math_rand.New(math_rand.NewSource(seed)) - p := NewPopulatedOperation_Expunge(popr, true) - size2 := github_com_gogo_protobuf_proto.Size(p) - data, err := github_com_gogo_protobuf_proto.Marshal(p) - if err != nil { - t.Fatalf("seed = %d, err = %v", seed, err) - } - size := p.Size() - if len(data) != size { - t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(data)) - } - if size2 != size { - t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2) - } - size3 := github_com_gogo_protobuf_proto.Size(p) - if size3 != size { - t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3) - } -} - -func BenchmarkOperation_ExpungeSize(b *testing.B) { - popr := math_rand.New(math_rand.NewSource(616)) - total := 0 - pops := make([]*Operation_Expunge, 1000) - for i := 0; i < 1000; i++ { - pops[i] = NewPopulatedOperation_Expunge(popr, false) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - total += pops[i%1000].Size() - } - b.SetBytes(int64(total / b.N)) -} - -func TestEntryStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedEntry(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOperationStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOperation_SnapshotStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Snapshot(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOperation_DiffStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Diff(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} -func TestOperation_ExpungeStringer(t *testing.T) { - popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano())) - p := NewPopulatedOperation_Expunge(popr, false) - s1 := p.String() - s2 := fmt.Sprintf("%v", p) - if s1 != s2 { - t.Fatalf("String want %v got %v", s1, s2) - } -} - -//These tests are generated by github.com/gogo/protobuf/plugin/testgen diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosutil/mesosprotoutil_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosutil/mesosprotoutil_test.go deleted file mode 100644 index 6e19d75d13d..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/mesosutil/mesosprotoutil_test.go +++ /dev/null @@ -1,252 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 mesosutil - -import ( - "github.com/gogo/protobuf/proto" - mesos "github.com/mesos/mesos-go/mesosproto" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestFilterResources(t *testing.T) { - resources := []*mesos.Resource{ - NewScalarResource("mem", 200), - NewScalarResource("cpu", 4), - NewScalarResource("mem", 500), - } - - memRes := FilterResources(resources, func(res *mesos.Resource) bool { - if res.GetType() == mesos.Value_SCALAR && res.GetName() == "mem" { - return true - } - return false - }) - - assert.Equal(t, 2, len(memRes)) -} - -func TestNewValueRange(t *testing.T) { - val := NewValueRange(20, 40) - if val == nil { - t.Fatal("Not creating protobuf object Value_Range.") - } - - if (val.GetEnd() - val.GetBegin()) != 20 { - t.Fatal("Protobuf object Value_Range not returning expected values.") - } -} - -func TestNewScalarResource(t *testing.T) { - val := NewScalarResource("mem", 200) - if val == nil { - t.Fatal("Not creating protobuf object Resource properly.") - } - if val.GetType() != mesos.Value_SCALAR { - t.Fatal("Expected type SCALAR for protobuf, got", val.GetType()) - } - if val.GetName() != "mem" && val.GetScalar().GetValue() != 200 { - t.Fatal("Protobuf object Resource has wrong name and Scalar values.") - } -} - -func TestNewRangesResource(t *testing.T) { - val := NewRangesResource("quotas", []*mesos.Value_Range{NewValueRange(20, 40)}) - if val == nil { - t.Fatal("Not creating protobuf object Resource properly.") - } - if val.GetType() != mesos.Value_RANGES { - t.Fatal("Expected type SCALAR for protobuf, got", val.GetType()) - } - if len(val.GetRanges().GetRange()) != 1 { - t.Fatal("Expected Resource of type RANGES with 1 range, but got", len(val.GetRanges().GetRange())) - } - -} - -func TestNewSetResource(t *testing.T) { - val := NewSetResource("greeting", []string{"hello", "world"}) - if val == nil { - t.Fatal("Not creating protobuf object Resource properly.") - } - if val.GetType() != mesos.Value_SET { - t.Fatal("Expected type SET for protobuf, got", val.GetType()) - } - if len(val.GetSet().GetItem()) != 2 { - t.Fatal("Expected Resource of type SET with 2 items, but got", len(val.GetRanges().GetRange())) - } - if val.GetSet().GetItem()[0] != "hello" { - t.Fatal("Protobuf Resource of type SET got wrong value.") - } -} - -func TestNewFrameworkID(t *testing.T) { - id := NewFrameworkID("test-id") - if id == nil { - t.Fatal("Not creating protobuf oject FrameworkID.") - } - if id.GetValue() != "test-id" { - t.Fatal("Protobuf object not returning expected value.") - } -} - -func TestNewFrameworkInfo(t *testing.T) { - info := NewFrameworkInfo("test-user", "test-name", NewFrameworkID("test-id")) - info.Hostname = proto.String("localhost") - if info == nil { - t.Fatal("Not creating protobuf object FrameworkInfo") - } - if info.GetUser() != "test-user" { - t.Fatal("Protobuf object FrameworkInfo.User missing value.") - } - if info.GetName() != "test-name" { - t.Fatal("Protobuf object FrameworkInfo.Name missing value.") - } - if info.GetId() == nil { - t.Fatal("Protobuf object FrameowrkInfo.Id missing value.") - } - if info.GetHostname() != "localhost" { - t.Fatal("Protobuf object FrameworkInfo.Hostname missing value.") - } -} - -func TestNewMasterInfo(t *testing.T) { - master := NewMasterInfo("master-1", 1234, 5678) - if master == nil { - t.Fatal("Not creating protobuf object MasterInfo") - } - if master.GetId() != "master-1" { - t.Fatal("Protobuf object MasterInfo.Id missing.") - } - if master.GetIp() != 1234 { - t.Fatal("Protobuf object MasterInfo.Ip missing.") - } - if master.GetPort() != 5678 { - t.Fatal("Protobuf object MasterInfo.Port missing.") - } -} - -func TestNewOfferID(t *testing.T) { - id := NewOfferID("offer-1") - if id == nil { - t.Fatal("Not creating protobuf object OfferID") - } - if id.GetValue() != "offer-1" { - t.Fatal("Protobuf object OfferID.Value missing.") - } -} - -func TestNewOffer(t *testing.T) { - offer := NewOffer(NewOfferID("offer-1"), NewFrameworkID("framework-1"), NewSlaveID("slave-1"), "localhost") - if offer == nil { - t.Fatal("Not creating protobuf object Offer") - } - if offer.GetId().GetValue() != "offer-1" { - t.Fatal("Protobuf object Offer.Id missing") - } - if offer.GetFrameworkId().GetValue() != "framework-1" { - t.Fatal("Protobuf object Offer.FrameworkId missing.") - } - if offer.GetSlaveId().GetValue() != "slave-1" { - t.Fatal("Protobuf object Offer.SlaveId missing.") - } - if offer.GetHostname() != "localhost" { - t.Fatal("Protobuf object offer.Hostname missing.") - } -} - -func TestNewSlaveID(t *testing.T) { - id := NewSlaveID("slave-1") - if id == nil { - t.Fatal("Not creating protobuf object SlaveID") - } - if id.GetValue() != "slave-1" { - t.Fatal("Protobuf object SlaveID.Value missing.") - } -} - -func TestNewTaskID(t *testing.T) { - id := NewSlaveID("task-1") - if id == nil { - t.Fatal("Not creating protobuf object TaskID") - } - if id.GetValue() != "task-1" { - t.Fatal("Protobuf object TaskID.Value missing.") - } -} - -func TestNewTaskInfo(t *testing.T) { - info := NewTaskInfo( - "simple-task", - NewTaskID("simpe-task-1"), - NewSlaveID("slave-1"), - []*mesos.Resource{NewScalarResource("mem", 400)}, - ) - if info == nil { - t.Fatal("Not creating protobuf object TaskInfo") - } - if info.GetName() != "simple-task" { - t.Fatal("Protobuf object TaskInfo.Name missing.") - } - if info.GetTaskId() == nil { - t.Fatal("Protobuf object TaskInfo.TaskId missing.") - } - if info.GetSlaveId() == nil { - t.Fatal("Protobuf object TaskInfo.SlaveId missing.") - } - if len(info.GetResources()) != 1 { - t.Fatal("Protobuf object TaskInfo.Resources missing.") - } -} - -func TestNewTaskStatus(t *testing.T) { - status := NewTaskStatus(NewTaskID("task-1"), mesos.TaskState_TASK_RUNNING) - if status == nil { - t.Fatal("Not creating protobuf object TaskStatus") - } - if status.GetTaskId().GetValue() != "task-1" { - t.Fatal("Protobuf object TaskStatus.TaskId missing.") - } - if status.GetState() != mesos.TaskState(mesos.TaskState_TASK_RUNNING) { - t.Fatal("Protobuf object TaskStatus.State missing.") - } -} - -func TestNewCommandInfo(t *testing.T) { - cmd := NewCommandInfo("echo Hello!") - if cmd == nil { - t.Fatal("Not creating protobuf object CommandInfo") - } - if cmd.GetValue() != "echo Hello!" { - t.Fatal("Protobuf object CommandInfo.Value missing") - } -} - -func TestNewExecutorInfo(t *testing.T) { - info := NewExecutorInfo(NewExecutorID("exec-1"), NewCommandInfo("ls -l")) - if info == nil { - t.Fatal("Not creating protobuf object ExecutorInfo") - } - if info.GetExecutorId().GetValue() != "exec-1" { - t.Fatal("Protobuf object ExecutorInfo.ExecutorId missing") - } - if info.GetCommand().GetValue() != "ls -l" { - t.Fatal("Protobuf object ExecutorInfo.Command missing") - } -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/http_transporter_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/http_transporter_test.go deleted file mode 100644 index dfe241640ac..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/http_transporter_test.go +++ /dev/null @@ -1,350 +0,0 @@ -package messenger - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "regexp" - "strconv" - "testing" - "time" - - "github.com/mesos/mesos-go/messenger/testmessage" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" - "golang.org/x/net/context" -) - -func TestTransporterNew(t *testing.T) { - trans := NewHTTPTransporter(upid.UPID{ID: "mesos1", Host: "localhost"}, nil) - assert.NotNil(t, trans) - assert.NotNil(t, trans.messageQueue) - assert.NotNil(t, trans.client) -} - -func TestTransporterSend(t *testing.T) { - idreg := regexp.MustCompile(`[A-Za-z0-9_\-]+@[A-Za-z0-9_\-\.]+:[0-9]+`) - serverId := "testserver" - - // setup mesos client-side - protoMsg := testmessage.GenerateSmallMessage() - msgName := getMessageName(protoMsg) - msg := &Message{ - Name: msgName, - ProtoMessage: protoMsg, - } - requestURI := fmt.Sprintf("/%s/%s", serverId, msgName) - - // setup server-side - msgReceived := make(chan struct{}) - srv := makeMockServer(requestURI, func(rsp http.ResponseWriter, req *http.Request) { - defer close(msgReceived) - from := req.Header.Get("Libprocess-From") - assert.NotEmpty(t, from) - assert.True(t, idreg.MatchString(from), fmt.Sprintf("regexp failed for '%v'", from)) - }) - defer srv.Close() - toUpid, err := upid.Parse(fmt.Sprintf("%s@%s", serverId, srv.Listener.Addr().String())) - assert.NoError(t, err) - - // make transport call. - transport := NewHTTPTransporter(upid.UPID{ID: "mesos1", Host: "localhost"}, nil) - _, errch := transport.Start() - defer transport.Stop(false) - - msg.UPID = toUpid - err = transport.Send(context.TODO(), msg) - assert.NoError(t, err) - - select { - case <-time.After(2 * time.Second): - t.Fatalf("timed out waiting for message receipt") - case <-msgReceived: - case err := <-errch: - if err != nil { - t.Fatalf(err.Error()) - } - } -} - -func TestTransporter_DiscardedSend(t *testing.T) { - serverId := "testserver" - - // setup mesos client-side - protoMsg := testmessage.GenerateSmallMessage() - msgName := getMessageName(protoMsg) - msg := &Message{ - Name: msgName, - ProtoMessage: protoMsg, - } - requestURI := fmt.Sprintf("/%s/%s", serverId, msgName) - - // setup server-side - msgReceived := make(chan struct{}) - srv := makeMockServer(requestURI, func(rsp http.ResponseWriter, req *http.Request) { - close(msgReceived) - time.Sleep(2 * time.Second) // long enough that we should be able to stop it - }) - defer srv.Close() - toUpid, err := upid.Parse(fmt.Sprintf("%s@%s", serverId, srv.Listener.Addr().String())) - assert.NoError(t, err) - - // make transport call. - transport := NewHTTPTransporter(upid.UPID{ID: "mesos1", Host: "localhost"}, nil) - _, errch := transport.Start() - defer transport.Stop(false) - - msg.UPID = toUpid - senderr := make(chan struct{}) - go func() { - defer close(senderr) - err = transport.Send(context.TODO(), msg) - assert.NotNil(t, err) - assert.Equal(t, discardOnStopError, err) - }() - - // wait for message to be received - select { - case <-time.After(2 * time.Second): - t.Fatalf("timed out waiting for message receipt") - return - case <-msgReceived: - transport.Stop(false) - case err := <-errch: - if err != nil { - t.Fatalf(err.Error()) - return - } - } - - // wait for send() to process discarded-error - select { - case <-time.After(5 * time.Second): - t.Fatalf("timed out waiting for aborted send") - return - case <-senderr: // continue - } -} - -func TestTransporterStartAndRcvd(t *testing.T) { - serverId := "testserver" - serverAddr := "127.0.0.1" - protoMsg := testmessage.GenerateSmallMessage() - msgName := getMessageName(protoMsg) - ctrl := make(chan struct{}) - - // setup receiver (server) process - receiver := NewHTTPTransporter(upid.UPID{ID: serverId, Host: serverAddr}, nil) - receiver.Install(msgName) - - go func() { - defer close(ctrl) - t.Logf("received something...") - msg, err := receiver.Recv() - assert.Nil(t, err) - assert.NotNil(t, msg) - if msg != nil { - assert.Equal(t, msgName, msg.Name) - } - }() - - rcvPid, errch := receiver.Start() - defer receiver.Stop(false) - assert.NotNil(t, errch) - - time.Sleep(time.Millisecond * 7) // time to catchup - - // setup sender (client) process - sender := NewHTTPTransporter(upid.UPID{ID: "mesos1", Host: "localhost"}, nil) - msg := &Message{ - UPID: &rcvPid, - Name: msgName, - ProtoMessage: protoMsg, - } - _, errch2 := sender.Start() - defer sender.Stop(false) - - t.Logf("sending test message") - sender.Send(context.TODO(), msg) - - select { - case <-time.After(time.Second * 5): - t.Fatalf("Timeout") - case <-ctrl: - case err := <-errch: - if err != nil { - t.Fatalf(err.Error()) - } - case err := <-errch2: - if err != nil { - t.Fatalf(err.Error()) - } - } -} - -func TestTransporterStartAndInject(t *testing.T) { - serverId := "testserver" - protoMsg := testmessage.GenerateSmallMessage() - msgName := getMessageName(protoMsg) - ctrl := make(chan struct{}) - - // setup receiver (server) process - receiver := NewHTTPTransporter(upid.UPID{ID: serverId, Host: "127.0.0.1"}, nil) - receiver.Install(msgName) - rcvPid, errch := receiver.Start() - defer receiver.Stop(false) - - msg := &Message{ - UPID: &rcvPid, - Name: msgName, - ProtoMessage: protoMsg, - } - - receiver.Inject(context.TODO(), msg) - - go func() { - defer close(ctrl) - msg, err := receiver.Recv() - assert.Nil(t, err) - assert.NotNil(t, msg) - if msg != nil { - assert.Equal(t, msgName, msg.Name) - } - }() - - select { - case <-time.After(time.Second * 1): - t.Fatalf("Timeout") - case <-ctrl: - case err := <-errch: - if err != nil { - t.Fatalf(err.Error()) - } - } -} - -func TestTransporterStartAndStop(t *testing.T) { - serverId := "testserver" - - // setup receiver (server) process - receiver := NewHTTPTransporter(upid.UPID{ID: serverId, Host: "127.0.0.1"}, nil) - - _, errch := receiver.Start() - assert.NotNil(t, errch) - - time.Sleep(1 * time.Second) - receiver.Stop(false) - - select { - case <-time.After(2 * time.Second): - t.Fatalf("timed out waiting for transport to stop") - case err := <-errch: - if err != nil { - t.Fatalf(err.Error()) - } - } -} - -func TestMutatedHostUPid(t *testing.T) { - serverId := "testserver" - // NOTE(tsenart): This static port can cause conflicts if multiple instances - // of this test run concurrently or else if this port is already bound by - // another socket. - serverPort := 12345 - serverHost := "127.0.0.1" - serverAddr := serverHost + ":" + strconv.Itoa(serverPort) - - // override the upid.Host with this listener IP - addr := net.ParseIP("0.0.0.0") - - // setup receiver (server) process - uPid, err := upid.Parse(fmt.Sprintf("%s@%s", serverId, serverAddr)) - assert.NoError(t, err) - receiver := NewHTTPTransporter(*uPid, addr) - - err = receiver.listen() - assert.NoError(t, err) - - if receiver.upid.Host != "127.0.0.1" { - t.Fatalf("reciever.upid.Host was expected to return %s, got %s\n", serverHost, receiver.upid.Host) - } - - if receiver.upid.Port != strconv.Itoa(serverPort) { - t.Fatalf("receiver.upid.Port was expected to return %d, got %s\n", serverPort, receiver.upid.Port) - } -} - -func TestEmptyHostPortUPid(t *testing.T) { - uPid := upid.UPID{ID: "testserver"} - - // override the upid.Host with this listener IP - addr := net.ParseIP("0.0.0.0") - receiver := NewHTTPTransporter(uPid, addr) - - err := receiver.listen() - assert.NoError(t, err) - - // This should be the host that overrides as uPid.Host is empty - if receiver.upid.Host != "0.0.0.0" { - t.Fatalf("reciever.upid.Host was expected to return 0.0.0.0, got %q", receiver.upid.Host) - } - - if receiver.upid.Port == "0" { - t.Fatalf("receiver.upid.Port was not expected to return 0, got %q", receiver.upid.Port) - } -} - -func makeMockServer(path string, handler func(rsp http.ResponseWriter, req *http.Request)) *httptest.Server { - mux := http.NewServeMux() - mux.HandleFunc(path, handler) - return httptest.NewServer(mux) -} - -func TestProcessOneRequest(t *testing.T) { - ht := &HTTPTransporter{ - messageQueue: make(chan *Message, 1), - shouldQuit: make(chan struct{}), - } - testfunc := func(expectProceed bool) { - rchan := make(chan Response, 1) - proceed := ht.processOneRequest(&upid.UPID{ID: "james"}, &Request{ - response: rchan, - Request: &http.Request{ - Method: "foo", - RequestURI: "a/z/bar", - Body: ioutil.NopCloser(&bytes.Reader{}), - }, - }) - // expecting to get a 202 response since the request doesn't have libprocess headers - if proceed != expectProceed { - t.Fatalf("expected proceed signal %t instead of %t", expectProceed, proceed) - } - select { - case resp := <-rchan: - if resp.code != 202 { - t.Fatalf("expected a 202 response for all libprocess requests") - } - default: - t.Fatalf("expected a response since we're not a libprocess agent") - } - select { - case m := <-ht.messageQueue: - // From, Name, Data - assert.Equal(t, "james", m.UPID.ID) - assert.Equal(t, "bar", m.Name) - default: - t.Fatalf("expected a message for the request that was processed") - } - } - t.Log("testing w/o shouldQuit signal") - testfunc(true) - - t.Log("testing w/ shouldQuit signal") - close(ht.shouldQuit) - for i := 0; i < 100; i++ { - testfunc(false) // do this in a loop to test determinism - } -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/messenger_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/messenger_test.go deleted file mode 100644 index bb6d9fc0532..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/messenger/messenger_test.go +++ /dev/null @@ -1,460 +0,0 @@ -package messenger - -import ( - "fmt" - "math/rand" - "net" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - "github.com/mesos/mesos-go/messenger/testmessage" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" - "golang.org/x/net/context" -) - -var ( - globalWG = new(sync.WaitGroup) -) - -func noopHandler(*upid.UPID, proto.Message) { - globalWG.Done() -} - -func shuffleMessages(queue *[]proto.Message) { - for i := range *queue { - index := rand.Intn(i + 1) - (*queue)[i], (*queue)[index] = (*queue)[index], (*queue)[i] - } -} - -func generateSmallMessages(n int) []proto.Message { - queue := make([]proto.Message, n) - for i := range queue { - queue[i] = testmessage.GenerateSmallMessage() - } - return queue -} - -func generateMediumMessages(n int) []proto.Message { - queue := make([]proto.Message, n) - for i := range queue { - queue[i] = testmessage.GenerateMediumMessage() - } - return queue -} - -func generateBigMessages(n int) []proto.Message { - queue := make([]proto.Message, n) - for i := range queue { - queue[i] = testmessage.GenerateBigMessage() - } - return queue -} - -func generateLargeMessages(n int) []proto.Message { - queue := make([]proto.Message, n) - for i := range queue { - queue[i] = testmessage.GenerateLargeMessage() - } - return queue -} - -func generateMixedMessages(n int) []proto.Message { - queue := make([]proto.Message, n*4) - for i := 0; i < n*4; i = i + 4 { - queue[i] = testmessage.GenerateSmallMessage() - queue[i+1] = testmessage.GenerateMediumMessage() - queue[i+2] = testmessage.GenerateBigMessage() - queue[i+3] = testmessage.GenerateLargeMessage() - } - shuffleMessages(&queue) - return queue -} - -func installMessages(t *testing.T, m Messenger, queue *[]proto.Message, counts *[]int, done chan struct{}) { - testCounts := func(counts []int, done chan struct{}) { - for i := range counts { - if counts[i] != cap(*queue)/4 { - return - } - } - close(done) - } - hander1 := func(from *upid.UPID, pbMsg proto.Message) { - (*queue) = append(*queue, pbMsg) - (*counts)[0]++ - testCounts(*counts, done) - } - hander2 := func(from *upid.UPID, pbMsg proto.Message) { - (*queue) = append(*queue, pbMsg) - (*counts)[1]++ - testCounts(*counts, done) - } - hander3 := func(from *upid.UPID, pbMsg proto.Message) { - (*queue) = append(*queue, pbMsg) - (*counts)[2]++ - testCounts(*counts, done) - } - hander4 := func(from *upid.UPID, pbMsg proto.Message) { - (*queue) = append(*queue, pbMsg) - (*counts)[3]++ - testCounts(*counts, done) - } - assert.NoError(t, m.Install(hander1, &testmessage.SmallMessage{})) - assert.NoError(t, m.Install(hander2, &testmessage.MediumMessage{})) - assert.NoError(t, m.Install(hander3, &testmessage.BigMessage{})) - assert.NoError(t, m.Install(hander4, &testmessage.LargeMessage{})) -} - -func runTestServer(b *testing.B, wg *sync.WaitGroup) *httptest.Server { - mux := http.NewServeMux() - mux.HandleFunc("/testserver/mesos.internal.SmallMessage", func(http.ResponseWriter, *http.Request) { - wg.Done() - }) - mux.HandleFunc("/testserver/mesos.internal.MediumMessage", func(http.ResponseWriter, *http.Request) { - wg.Done() - }) - mux.HandleFunc("/testserver/mesos.internal.BigMessage", func(http.ResponseWriter, *http.Request) { - wg.Done() - }) - mux.HandleFunc("/testserver/mesos.internal.LargeMessage", func(http.ResponseWriter, *http.Request) { - wg.Done() - }) - return httptest.NewServer(mux) -} - -func TestMessengerFailToInstall(t *testing.T) { - m := NewHttp(upid.UPID{ID: "mesos"}) - handler := func(from *upid.UPID, pbMsg proto.Message) {} - assert.NotNil(t, m) - assert.NoError(t, m.Install(handler, &testmessage.SmallMessage{})) - assert.Error(t, m.Install(handler, &testmessage.SmallMessage{})) -} - -func TestMessengerFailToSend(t *testing.T) { - m := NewHttp(upid.UPID{ID: "foo", Host: "localhost"}) - assert.NoError(t, m.Start()) - self := m.UPID() - assert.Error(t, m.Send(context.TODO(), &self, &testmessage.SmallMessage{})) -} - -func TestMessenger(t *testing.T) { - messages := generateMixedMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "mesos2", Host: "localhost"}) - - done := make(chan struct{}) - counts := make([]int, 4) - msgQueue := make([]proto.Message, 0, len(messages)) - installMessages(t, m2, &msgQueue, &counts, done) - - assert.NoError(t, m1.Start()) - assert.NoError(t, m2.Start()) - upid2 := m2.UPID() - - go func() { - for _, msg := range messages { - assert.NoError(t, m1.Send(context.TODO(), &upid2, msg)) - } - }() - - select { - case <-time.After(time.Second * 10): - t.Fatalf("Timeout") - case <-done: - } - - for i := range counts { - assert.Equal(t, 1000, counts[i]) - } - assert.Equal(t, messages, msgQueue) -} - -func BenchmarkMessengerSendSmallMessage(b *testing.B) { - messages := generateSmallMessages(1000) - - wg := new(sync.WaitGroup) - wg.Add(b.N) - srv := runTestServer(b, wg) - defer srv.Close() - - upid2, err := upid.Parse(fmt.Sprintf("testserver@%s", srv.Listener.Addr().String())) - assert.NoError(b, err) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), upid2, messages[i%1000]) - } - wg.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendMediumMessage(b *testing.B) { - messages := generateMediumMessages(1000) - - wg := new(sync.WaitGroup) - wg.Add(b.N) - srv := runTestServer(b, wg) - defer srv.Close() - - upid2, err := upid.Parse(fmt.Sprintf("testserver@%s", srv.Listener.Addr().String())) - assert.NoError(b, err) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), upid2, messages[i%1000]) - } - wg.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendBigMessage(b *testing.B) { - messages := generateBigMessages(1000) - - wg := new(sync.WaitGroup) - wg.Add(b.N) - srv := runTestServer(b, wg) - defer srv.Close() - - upid2, err := upid.Parse(fmt.Sprintf("testserver@%s", srv.Listener.Addr().String())) - assert.NoError(b, err) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), upid2, messages[i%1000]) - } - wg.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendLargeMessage(b *testing.B) { - messages := generateLargeMessages(1000) - - wg := new(sync.WaitGroup) - wg.Add(b.N) - srv := runTestServer(b, wg) - defer srv.Close() - - upid2, err := upid.Parse(fmt.Sprintf("testserver@%s", srv.Listener.Addr().String())) - assert.NoError(b, err) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), upid2, messages[i%1000]) - } - wg.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendMixedMessage(b *testing.B) { - messages := generateMixedMessages(1000) - - wg := new(sync.WaitGroup) - wg.Add(b.N) - srv := runTestServer(b, wg) - defer srv.Close() - - upid2, err := upid.Parse(fmt.Sprintf("testserver@%s", srv.Listener.Addr().String())) - assert.NoError(b, err) - - m1 := NewHttp(upid.UPID{ID: "mesos1", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), upid2, messages[i%1000]) - } - wg.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendRecvSmallMessage(b *testing.B) { - globalWG.Add(b.N) - - messages := generateSmallMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "foo1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "foo2", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - assert.NoError(b, m2.Start()) - defer m2.Stop() - - assert.NoError(b, m2.Install(noopHandler, &testmessage.SmallMessage{})) - - upid2 := m2.UPID() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), &upid2, messages[i%1000]) - } - globalWG.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendRecvMediumMessage(b *testing.B) { - globalWG.Add(b.N) - - messages := generateMediumMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "foo1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "foo2", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - assert.NoError(b, m2.Start()) - defer m2.Stop() - - assert.NoError(b, m2.Install(noopHandler, &testmessage.MediumMessage{})) - - upid2 := m2.UPID() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), &upid2, messages[i%1000]) - } - globalWG.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendRecvBigMessage(b *testing.B) { - globalWG.Add(b.N) - - messages := generateBigMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "foo1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "foo2", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - assert.NoError(b, m2.Start()) - defer m2.Stop() - - assert.NoError(b, m2.Install(noopHandler, &testmessage.BigMessage{})) - - upid2 := m2.UPID() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), &upid2, messages[i%1000]) - } - globalWG.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendRecvLargeMessage(b *testing.B) { - globalWG.Add(b.N) - messages := generateLargeMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "foo1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "foo2", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - assert.NoError(b, m2.Start()) - defer m2.Stop() - - assert.NoError(b, m2.Install(noopHandler, &testmessage.LargeMessage{})) - - upid2 := m2.UPID() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), &upid2, messages[i%1000]) - } - globalWG.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func BenchmarkMessengerSendRecvMixedMessage(b *testing.B) { - globalWG.Add(b.N) - messages := generateMixedMessages(1000) - - m1 := NewHttp(upid.UPID{ID: "foo1", Host: "localhost"}) - m2 := NewHttp(upid.UPID{ID: "foo2", Host: "localhost"}) - assert.NoError(b, m1.Start()) - defer m1.Stop() - - assert.NoError(b, m2.Start()) - defer m2.Stop() - - assert.NoError(b, m2.Install(noopHandler, &testmessage.SmallMessage{})) - assert.NoError(b, m2.Install(noopHandler, &testmessage.MediumMessage{})) - assert.NoError(b, m2.Install(noopHandler, &testmessage.BigMessage{})) - assert.NoError(b, m2.Install(noopHandler, &testmessage.LargeMessage{})) - - upid2 := m2.UPID() - - b.ResetTimer() - for i := 0; i < b.N; i++ { - m1.Send(context.TODO(), &upid2, messages[i%1000]) - } - globalWG.Wait() - b.StopTimer() - time.Sleep(2 * time.Second) // allow time for connection cleanup -} - -func TestUPIDBindingAddress(t *testing.T) { - tt := []struct { - hostname string - binding net.IP - expected string - }{ - {"", nil, ""}, - {"", net.IPv4(1, 2, 3, 4), "1.2.3.4"}, - {"", net.IPv4(0, 0, 0, 0), ""}, - {"localhost", nil, "127.0.0.1"}, - {"localhost", net.IPv4(5, 6, 7, 8), "5.6.7.8"}, - {"localhost", net.IPv4(0, 0, 0, 0), "127.0.0.1"}, - {"0.0.0.0", nil, ""}, - {"7.8.9.1", nil, "7.8.9.1"}, - {"7.8.9.1", net.IPv4(0, 0, 0, 0), "7.8.9.1"}, - {"7.8.9.1", net.IPv4(8, 9, 1, 2), "8.9.1.2"}, - } - - for i, tc := range tt { - actual, err := UPIDBindingAddress(tc.hostname, tc.binding) - if err != nil && tc.expected != "" { - t.Fatalf("test case %d failed; expected %q instead of error %v", i+1, tc.expected, err) - } - if err == nil && actual != tc.expected { - t.Fatalf("test case %d failed; expected %q instead of %q", i+1, tc.expected, actual) - } - if err != nil { - t.Logf("test case %d; received expected error %v", i+1, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/schedcache_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/schedcache_test.go deleted file mode 100644 index 4a3a46e5c4b..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/schedcache_test.go +++ /dev/null @@ -1,215 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 scheduler - -import ( - mesos "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/stretchr/testify/assert" - "testing" - - "github.com/mesos/mesos-go/upid" -) - -func TestSchedCacheNew(t *testing.T) { - cache := newSchedCache() - assert.NotNil(t, cache) - assert.NotNil(t, cache.savedOffers) - assert.NotNil(t, cache.savedSlavePids) -} - -func TestSchedCachePutOffer(t *testing.T) { - cache := newSchedCache() - - offer01 := createTestOffer("01") - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - cache.putOffer(offer01, pid01) - - offer02 := createTestOffer("02") - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - cache.putOffer(offer02, pid02) - - assert.Equal(t, len(cache.savedOffers), 2) - cachedOffer1, ok := cache.savedOffers["test-offer-01"] - assert.True(t, ok) - cachedOffer2, ok := cache.savedOffers["test-offer-02"] - assert.True(t, ok) - - assert.NotNil(t, cachedOffer1.offer) - assert.Equal(t, "test-offer-01", cachedOffer1.offer.Id.GetValue()) - assert.NotNil(t, cachedOffer2.offer) - assert.Equal(t, "test-offer-02", cachedOffer2.offer.Id.GetValue()) - - assert.NotNil(t, cachedOffer1.slavePid) - assert.Equal(t, "slave01@127.0.0.1:5050", cachedOffer1.slavePid.String()) - assert.NotNil(t, cachedOffer2.slavePid) - assert.Equal(t, "slave02@127.0.0.1:5050", cachedOffer2.slavePid.String()) - -} - -func TestSchedCacheGetOffer(t *testing.T) { - cache := newSchedCache() - offer01 := createTestOffer("01") - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - offer02 := createTestOffer("02") - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putOffer(offer01, pid01) - cache.putOffer(offer02, pid02) - - cachedOffer01 := cache.getOffer(util.NewOfferID("test-offer-01")).offer - cachedOffer02 := cache.getOffer(util.NewOfferID("test-offer-02")).offer - assert.NotEqual(t, offer01, cachedOffer02) - assert.Equal(t, offer01, cachedOffer01) - assert.Equal(t, offer02, cachedOffer02) - -} - -func TestSchedCacheContainsOffer(t *testing.T) { - cache := newSchedCache() - offer01 := createTestOffer("01") - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - offer02 := createTestOffer("02") - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putOffer(offer01, pid01) - cache.putOffer(offer02, pid02) - - assert.True(t, cache.containsOffer(util.NewOfferID("test-offer-01"))) - assert.True(t, cache.containsOffer(util.NewOfferID("test-offer-02"))) - assert.False(t, cache.containsOffer(util.NewOfferID("test-offer-05"))) -} - -func TestSchedCacheRemoveOffer(t *testing.T) { - cache := newSchedCache() - offer01 := createTestOffer("01") - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - offer02 := createTestOffer("02") - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putOffer(offer01, pid01) - cache.putOffer(offer02, pid02) - cache.removeOffer(util.NewOfferID("test-offer-01")) - - assert.Equal(t, 1, len(cache.savedOffers)) - assert.True(t, cache.containsOffer(util.NewOfferID("test-offer-02"))) - assert.False(t, cache.containsOffer(util.NewOfferID("test-offer-01"))) -} - -func TestSchedCachePutSlavePid(t *testing.T) { - cache := newSchedCache() - - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - pid03, err := upid.Parse("slave03@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putSlavePid(util.NewSlaveID("slave01"), pid01) - cache.putSlavePid(util.NewSlaveID("slave02"), pid02) - cache.putSlavePid(util.NewSlaveID("slave03"), pid03) - - assert.Equal(t, len(cache.savedSlavePids), 3) - cachedSlavePid1, ok := cache.savedSlavePids["slave01"] - assert.True(t, ok) - cachedSlavePid2, ok := cache.savedSlavePids["slave02"] - assert.True(t, ok) - cachedSlavePid3, ok := cache.savedSlavePids["slave03"] - assert.True(t, ok) - - assert.True(t, cachedSlavePid1.Equal(pid01)) - assert.True(t, cachedSlavePid2.Equal(pid02)) - assert.True(t, cachedSlavePid3.Equal(pid03)) -} - -func TestSchedCacheGetSlavePid(t *testing.T) { - cache := newSchedCache() - - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putSlavePid(util.NewSlaveID("slave01"), pid01) - cache.putSlavePid(util.NewSlaveID("slave02"), pid02) - - cachedSlavePid1 := cache.getSlavePid(util.NewSlaveID("slave01")) - cachedSlavePid2 := cache.getSlavePid(util.NewSlaveID("slave02")) - - assert.NotNil(t, cachedSlavePid1) - assert.NotNil(t, cachedSlavePid2) - assert.True(t, pid01.Equal(cachedSlavePid1)) - assert.True(t, pid02.Equal(cachedSlavePid2)) - assert.False(t, pid01.Equal(cachedSlavePid2)) -} - -func TestSchedCacheContainsSlavePid(t *testing.T) { - cache := newSchedCache() - - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putSlavePid(util.NewSlaveID("slave01"), pid01) - cache.putSlavePid(util.NewSlaveID("slave02"), pid02) - - assert.True(t, cache.containsSlavePid(util.NewSlaveID("slave01"))) - assert.True(t, cache.containsSlavePid(util.NewSlaveID("slave02"))) - assert.False(t, cache.containsSlavePid(util.NewSlaveID("slave05"))) -} - -func TestSchedCacheRemoveSlavePid(t *testing.T) { - cache := newSchedCache() - - pid01, err := upid.Parse("slave01@127.0.0.1:5050") - assert.NoError(t, err) - pid02, err := upid.Parse("slave02@127.0.0.1:5050") - assert.NoError(t, err) - - cache.putSlavePid(util.NewSlaveID("slave01"), pid01) - cache.putSlavePid(util.NewSlaveID("slave02"), pid02) - - assert.True(t, cache.containsSlavePid(util.NewSlaveID("slave01"))) - assert.True(t, cache.containsSlavePid(util.NewSlaveID("slave02"))) - assert.False(t, cache.containsSlavePid(util.NewSlaveID("slave05"))) - - cache.removeSlavePid(util.NewSlaveID("slave01")) - assert.Equal(t, 1, len(cache.savedSlavePids)) - assert.False(t, cache.containsSlavePid(util.NewSlaveID("slave01"))) - -} - -func createTestOffer(idSuffix string) *mesos.Offer { - return util.NewOffer( - util.NewOfferID("test-offer-"+idSuffix), - util.NewFrameworkID("test-framework-"+idSuffix), - util.NewSlaveID("test-slave-"+idSuffix), - "localhost."+idSuffix, - ) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_intgr_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_intgr_test.go deleted file mode 100644 index 7fbae11df17..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_intgr_test.go +++ /dev/null @@ -1,458 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 scheduler - -import ( - "io/ioutil" - "net/http" - "reflect" - "sync" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - log "github.com/golang/glog" - mesos "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/mesos/mesos-go/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -// testScuduler is used for testing Schduler callbacks. -type testScheduler struct { - ch chan bool - wg *sync.WaitGroup - s *SchedulerIntegrationTestSuite - errors chan string // yields errors received by Scheduler.Error -} - -// convenience -func (sched *testScheduler) T() *testing.T { - return sched.s.T() -} - -func (sched *testScheduler) Registered(dr SchedulerDriver, fw *mesos.FrameworkID, mi *mesos.MasterInfo) { - log.Infoln("Sched.Registered() called.") - sched.s.Equal(fw.GetValue(), sched.s.registeredFrameworkId.GetValue(), "driver did not register the expected framework ID") - sched.s.Equal(mi.GetIp(), uint32(123456)) - sched.ch <- true -} - -func (sched *testScheduler) Reregistered(dr SchedulerDriver, mi *mesos.MasterInfo) { - log.Infoln("Sched.Reregistered() called") - sched.s.Equal(mi.GetIp(), uint32(123456)) - sched.ch <- true -} - -func (sched *testScheduler) Disconnected(dr SchedulerDriver) { - log.Infoln("Shed.Disconnected() called") -} - -func (sched *testScheduler) ResourceOffers(dr SchedulerDriver, offers []*mesos.Offer) { - log.Infoln("Sched.ResourceOffers called.") - sched.s.NotNil(offers) - sched.s.Equal(len(offers), 1) - sched.ch <- true -} - -func (sched *testScheduler) OfferRescinded(dr SchedulerDriver, oid *mesos.OfferID) { - log.Infoln("Sched.OfferRescinded() called.") - sched.s.NotNil(oid) - sched.s.Equal("test-offer-001", oid.GetValue()) - sched.ch <- true -} - -func (sched *testScheduler) StatusUpdate(dr SchedulerDriver, stat *mesos.TaskStatus) { - log.Infoln("Sched.StatusUpdate() called.") - sched.s.NotNil(stat) - sched.s.Equal("test-task-001", stat.GetTaskId().GetValue()) - sched.wg.Done() - log.Infof("Status update done with waitGroup") -} - -func (sched *testScheduler) SlaveLost(dr SchedulerDriver, slaveId *mesos.SlaveID) { - log.Infoln("Sched.SlaveLost() called.") - sched.s.NotNil(slaveId) - sched.s.Equal(slaveId.GetValue(), "test-slave-001") - sched.ch <- true -} - -func (sched *testScheduler) FrameworkMessage(dr SchedulerDriver, execId *mesos.ExecutorID, slaveId *mesos.SlaveID, data string) { - log.Infoln("Sched.FrameworkMessage() called.") - sched.s.NotNil(slaveId) - sched.s.Equal(slaveId.GetValue(), "test-slave-001") - sched.s.NotNil(execId) - sched.s.NotNil(data) - sched.s.Equal("test-data-999", string(data)) - sched.ch <- true -} - -func (sched *testScheduler) ExecutorLost(SchedulerDriver, *mesos.ExecutorID, *mesos.SlaveID, int) { - log.Infoln("Sched.ExecutorLost called") -} - -func (sched *testScheduler) Error(dr SchedulerDriver, err string) { - log.Infoln("Sched.Error() called.") - sched.errors <- err - sched.ch <- true -} - -func (sched *testScheduler) waitForCallback(timeout time.Duration) bool { - if timeout == 0 { - timeout = 2 * time.Second - } - select { - case <-sched.ch: - //callback complete - return true - case <-time.After(timeout): - sched.T().Fatalf("timed out after waiting %v for callback", timeout) - } - return false -} - -func newTestScheduler(s *SchedulerIntegrationTestSuite) *testScheduler { - return &testScheduler{ch: make(chan bool), s: s, errors: make(chan string, 2)} -} - -type mockServerConfigurator func(frameworkId *mesos.FrameworkID, suite *SchedulerIntegrationTestSuite) - -type SchedulerIntegrationTestSuiteCore struct { - SchedulerTestSuiteCore - server *testutil.MockMesosHttpServer - driver *MesosSchedulerDriver - sched *testScheduler - config mockServerConfigurator - validator http.HandlerFunc - registeredFrameworkId *mesos.FrameworkID -} - -type SchedulerIntegrationTestSuite struct { - suite.Suite - SchedulerIntegrationTestSuiteCore -} - -// sets up a mock Mesos HTTP master listener, scheduler, and scheduler driver for testing. -// attempts to wait for a registered or re-registered callback on the suite.sched. -func (suite *SchedulerIntegrationTestSuite) configure(frameworkId *mesos.FrameworkID) bool { - t := suite.T() - // start mock master server to handle connection - suite.server = testutil.NewMockMasterHttpServer(t, func(rsp http.ResponseWriter, req *http.Request) { - log.Infoln("MockMaster - rcvd ", req.RequestURI) - if suite.validator != nil { - suite.validator(rsp, req) - } else { - ioutil.ReadAll(req.Body) - defer req.Body.Close() - rsp.WriteHeader(http.StatusAccepted) - } - }) - - t.Logf("test HTTP server listening on %v", suite.server.Addr) - suite.sched = newTestScheduler(suite) - suite.sched.ch = make(chan bool, 10) // big enough that it doesn't block callback processing - - cfg := DriverConfig{ - Scheduler: suite.sched, - Framework: suite.framework, - Master: suite.server.Addr, - } - suite.driver = newTestSchedulerDriver(suite.T(), cfg).MesosSchedulerDriver - suite.config(frameworkId, suite) - - stat, err := suite.driver.Start() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) - - ok := waitForConnected(t, suite.driver, 2*time.Second) - if ok { - ok = suite.sched.waitForCallback(0) // registered or re-registered callback - } - return ok -} - -func (suite *SchedulerIntegrationTestSuite) configureServerWithRegisteredFramework() bool { - // suite.framework is used to initialize the FrameworkInfo of - // the driver, so if we clear the Id then we'll expect a registration message - id := suite.framework.Id - suite.framework.Id = nil - suite.registeredFrameworkId = id - return suite.configure(id) -} - -var defaultMockServerConfigurator = mockServerConfigurator(func(frameworkId *mesos.FrameworkID, suite *SchedulerIntegrationTestSuite) { - t := suite.T() - masterInfo := util.NewMasterInfo("master", 123456, 1234) - suite.server.On("/master/mesos.internal.RegisterFrameworkMessage").Do(func(rsp http.ResponseWriter, req *http.Request) { - if suite.validator != nil { - t.Logf("validating registration request") - suite.validator(rsp, req) - } else { - ioutil.ReadAll(req.Body) - defer req.Body.Close() - rsp.WriteHeader(http.StatusAccepted) - } - // this is what the mocked scheduler is expecting to receive - suite.driver.eventLock.Lock() - defer suite.driver.eventLock.Unlock() - suite.driver.frameworkRegistered(suite.driver.masterPid, &mesos.FrameworkRegisteredMessage{ - FrameworkId: frameworkId, - MasterInfo: masterInfo, - }) - }) - suite.server.On("/master/mesos.internal.ReregisterFrameworkMessage").Do(func(rsp http.ResponseWriter, req *http.Request) { - if suite.validator != nil { - suite.validator(rsp, req) - } else { - ioutil.ReadAll(req.Body) - defer req.Body.Close() - rsp.WriteHeader(http.StatusAccepted) - } - // this is what the mocked scheduler is expecting to receive - suite.driver.eventLock.Lock() - defer suite.driver.eventLock.Unlock() - suite.driver.frameworkReregistered(suite.driver.masterPid, &mesos.FrameworkReregisteredMessage{ - FrameworkId: frameworkId, - MasterInfo: masterInfo, - }) - }) -}) - -func (s *SchedulerIntegrationTestSuite) newMockClient() *testutil.MockMesosClient { - return testutil.NewMockMesosClient(s.T(), s.server.PID) -} - -func (s *SchedulerIntegrationTestSuite) SetupTest() { - s.SchedulerTestSuiteCore.SetupTest() - s.config = defaultMockServerConfigurator -} - -func (s *SchedulerIntegrationTestSuite) TearDownTest() { - if s.server != nil { - s.server.Close() - } - if s.driver != nil { - s.driver.Abort() - - // wait for all events to finish processing, otherwise we can get into a data - // race when the suite object is reused for the next test. - <-s.driver.done - } -} - -// ---------------------------------- Tests ---------------------------------- // - -func TestSchedulerIntegrationSuite(t *testing.T) { - suite.Run(t, new(SchedulerIntegrationTestSuite)) -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverRegisterFrameworkMessage() { - t := suite.T() - - id := suite.framework.Id - suite.framework.Id = nil - validated := make(chan struct{}) - var closeOnce sync.Once - suite.validator = http.HandlerFunc(func(rsp http.ResponseWriter, req *http.Request) { - t.Logf("RCVD request %s", req.URL) - - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatalf("Missing message data from request") - } - defer req.Body.Close() - - if "/master/mesos.internal.RegisterFrameworkMessage" != req.RequestURI { - rsp.WriteHeader(http.StatusAccepted) - return - } - - defer closeOnce.Do(func() { close(validated) }) - - message := new(mesos.RegisterFrameworkMessage) - err = proto.Unmarshal(data, message) - if err != nil { - t.Fatal("Problem unmarshaling expected RegisterFrameworkMessage") - } - - suite.NotNil(message) - info := message.GetFramework() - suite.NotNil(info) - suite.Equal(suite.framework.GetName(), info.GetName()) - suite.True(reflect.DeepEqual(suite.framework.GetId(), info.GetId())) - rsp.WriteHeader(http.StatusOK) - }) - ok := suite.configure(id) - suite.True(ok, "failed to establish running test server and driver") - select { - case <-time.After(1 * time.Second): - t.Fatalf("failed to complete validation of framework registration message") - case <-validated: - // noop - } -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverFrameworkRegisteredEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverFrameworkReregisteredEvent() { - ok := suite.configure(suite.framework.Id) - suite.True(ok, "failed to establish running test server and driver") -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverResourceOffersEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send a event to this SchedulerDriver (via http) to test handlers. - offer := util.NewOffer( - util.NewOfferID("test-offer-001"), - suite.registeredFrameworkId, - util.NewSlaveID("test-slave-001"), - "test-localhost", - ) - pbMsg := &mesos.ResourceOffersMessage{ - Offers: []*mesos.Offer{offer}, - Pids: []string{"test-offer-001@test-slave-001:5051"}, - } - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - suite.sched.waitForCallback(0) -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverRescindOfferEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send a event to this SchedulerDriver (via http) to test handlers. - pbMsg := &mesos.RescindResourceOfferMessage{ - OfferId: util.NewOfferID("test-offer-001"), - } - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - suite.sched.waitForCallback(0) -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverStatusUpdatedEvent() { - t := suite.T() - var wg sync.WaitGroup - wg.Add(2) - suite.config = mockServerConfigurator(func(frameworkId *mesos.FrameworkID, suite *SchedulerIntegrationTestSuite) { - defaultMockServerConfigurator(frameworkId, suite) - suite.server.On("/master/mesos.internal.StatusUpdateAcknowledgementMessage").Do(func(rsp http.ResponseWriter, req *http.Request) { - log.Infoln("Master cvd ACK") - data, _ := ioutil.ReadAll(req.Body) - defer req.Body.Close() - assert.NotNil(t, data) - wg.Done() - log.Infof("MockMaster - Done with wait group") - }) - suite.sched.wg = &wg - }) - - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send a event to this SchedulerDriver (via http) to test handlers. - pbMsg := &mesos.StatusUpdateMessage{ - Update: util.NewStatusUpdate( - suite.registeredFrameworkId, - util.NewTaskStatus(util.NewTaskID("test-task-001"), mesos.TaskState_TASK_STARTING), - float64(time.Now().Unix()), - []byte("test-abcd-ef-3455-454-001"), - ), - // note: cannot use driver's pid here if we want an ACK - Pid: proto.String("test-slave-001(1)@foo.bar:1234"), - } - pbMsg.Update.SlaveId = &mesos.SlaveID{Value: proto.String("test-slave-001")} - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - wg.Wait() -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverLostSlaveEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send a event to this SchedulerDriver (via http) to test handlers. offer := util.NewOffer( - pbMsg := &mesos.LostSlaveMessage{ - SlaveId: util.NewSlaveID("test-slave-001"), - } - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - suite.sched.waitForCallback(0) -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverFrameworkMessageEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send a event to this SchedulerDriver (via http) to test handlers. offer := util.NewOffer( - pbMsg := &mesos.ExecutorToFrameworkMessage{ - SlaveId: util.NewSlaveID("test-slave-001"), - FrameworkId: suite.registeredFrameworkId, - ExecutorId: util.NewExecutorID("test-executor-001"), - Data: []byte("test-data-999"), - } - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - suite.sched.waitForCallback(0) -} - -func waitForConnected(t *testing.T, driver *MesosSchedulerDriver, timeout time.Duration) bool { - connected := make(chan struct{}) - go func() { - defer close(connected) - for !driver.Connected() { - time.Sleep(200 * time.Millisecond) - } - }() - select { - case <-time.After(timeout): - t.Fatalf("driver failed to establish connection within %v", timeout) - return false - case <-connected: - return true - } -} - -func (suite *SchedulerIntegrationTestSuite) TestSchedulerDriverFrameworkErrorEvent() { - ok := suite.configureServerWithRegisteredFramework() - suite.True(ok, "failed to establish running test server and driver") - - // Send an error event to this SchedulerDriver (via http) to test handlers. - pbMsg := &mesos.FrameworkErrorMessage{ - Message: proto.String("test-error-999"), - } - - c := suite.newMockClient() - c.SendMessage(suite.driver.self, pbMsg) - message := <-suite.sched.errors - suite.Equal("test-error-999", message) - suite.sched.waitForCallback(10 * time.Second) - suite.Equal(mesos.Status_DRIVER_ABORTED, suite.driver.Status()) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_unit_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_unit_test.go deleted file mode 100644 index 9f2c02faef7..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/scheduler/scheduler_unit_test.go +++ /dev/null @@ -1,550 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 scheduler - -import ( - "fmt" - "os/user" - "testing" - "time" - - "github.com/gogo/protobuf/proto" - log "github.com/golang/glog" - "github.com/mesos/mesos-go/detector" - _ "github.com/mesos/mesos-go/detector/zoo" - mesos "github.com/mesos/mesos-go/mesosproto" - util "github.com/mesos/mesos-go/mesosutil" - "github.com/mesos/mesos-go/messenger" - "github.com/mesos/mesos-go/upid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" - "golang.org/x/net/context" -) - -type SchedulerTestSuiteCore struct { - master string - masterUpid string - masterId string - frameworkID string - framework *mesos.FrameworkInfo -} - -type SchedulerTestSuite struct { - suite.Suite - SchedulerTestSuiteCore -} - -func (s *SchedulerTestSuiteCore) SetupTest() { - s.master = "127.0.0.1:8080" - s.masterUpid = "master(2)@" + s.master - s.masterId = "some-master-id-uuid" - s.frameworkID = "some-framework-id-uuid" - s.framework = util.NewFrameworkInfo( - "test-user", - "test-name", - util.NewFrameworkID(s.frameworkID), - ) -} - -func TestSchedulerSuite(t *testing.T) { - t.Logf("running scheduler test suite..") - suite.Run(t, new(SchedulerTestSuite)) -} - -func driverConfig(sched Scheduler, framework *mesos.FrameworkInfo, master string, cred *mesos.Credential) DriverConfig { - return driverConfigMessenger(sched, framework, master, cred, nil) -} - -func driverConfigMessenger(sched Scheduler, framework *mesos.FrameworkInfo, master string, cred *mesos.Credential, m messenger.Messenger) DriverConfig { - d := DriverConfig{ - Scheduler: sched, - Framework: framework, - Master: master, - Credential: cred, - NewDetector: func() (detector.Master, error) { return nil, nil }, // master detection not needed - } - if m != nil { - d.NewMessenger = func() (messenger.Messenger, error) { return m, nil } - } - return d -} - -func mockedMessenger() *messenger.MockedMessenger { - m := messenger.NewMockedMessenger() - m.On("Start").Return(nil) - m.On("UPID").Return(upid.UPID{}) - m.On("Send").Return(nil) - m.On("Stop").Return(nil) - m.On("Route").Return(nil) - m.On("Install").Return(nil) - return m -} - -type testSchedulerDriver struct { - *MesosSchedulerDriver -} - -func (t *testSchedulerDriver) setConnected(b bool) { - t.eventLock.Lock() - defer t.eventLock.Unlock() - t.connected = b -} - -func newTestSchedulerDriver(t *testing.T, cfg DriverConfig) *testSchedulerDriver { - driver, err := NewMesosSchedulerDriver(cfg) - if err != nil { - t.Fatal(err) - } - return &testSchedulerDriver{driver} -} - -func TestSchedulerDriverNew(t *testing.T) { - masterAddr := "localhost:5050" - driver := newTestSchedulerDriver(t, driverConfig(NewMockScheduler(), &mesos.FrameworkInfo{}, masterAddr, nil)) - user, _ := user.Current() - assert.Equal(t, user.Username, driver.frameworkInfo.GetUser()) - host := util.GetHostname("") - assert.Equal(t, host, driver.frameworkInfo.GetHostname()) -} - -func TestSchedulerDriverNew_WithPid(t *testing.T) { - masterAddr := "master@127.0.0.1:5050" - mUpid, err := upid.Parse(masterAddr) - assert.NoError(t, err) - driver := newTestSchedulerDriver(t, driverConfig(NewMockScheduler(), &mesos.FrameworkInfo{}, masterAddr, nil)) - driver.handleMasterChanged(driver.self, &mesos.InternalMasterChangeDetected{Master: &mesos.MasterInfo{Pid: proto.String(mUpid.String())}}) - assert.True(t, driver.masterPid.Equal(mUpid), fmt.Sprintf("expected upid %+v instead of %+v", mUpid, driver.masterPid)) - assert.NoError(t, err) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverNew_WithFrameworkInfo_Override() { - suite.framework.Hostname = proto.String("local-host") - driver := newTestSchedulerDriver(suite.T(), driverConfig(NewMockScheduler(), suite.framework, "127.0.0.1:5050", nil)) - suite.Equal(driver.frameworkInfo.GetUser(), "test-user") - suite.Equal("local-host", driver.frameworkInfo.GetHostname()) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverStartOK() { - sched := NewMockScheduler() - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(sched, suite.framework, suite.master, nil, mockedMessenger())) - suite.False(driver.Running()) - - stat, err := driver.Start() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) - suite.True(driver.Running()) - driver.Stop(true) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverStartWithMessengerFailure() { - sched := NewMockScheduler() - sched.On("Error").Return() - - messenger := messenger.NewMockedMessenger() - messenger.On("Start").Return(fmt.Errorf("Failed to start messenger")) - messenger.On("Stop").Return(nil) - messenger.On("Install").Return(nil) - - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(sched, suite.framework, suite.master, nil, messenger)) - suite.False(driver.Running()) - - stat, err := driver.Start() - suite.Error(err) - suite.False(driver.Running()) - suite.False(driver.Connected()) - suite.Equal(mesos.Status_DRIVER_NOT_STARTED, driver.Status()) - suite.Equal(mesos.Status_DRIVER_NOT_STARTED, stat) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverStartWithRegistrationFailure() { - sched := NewMockScheduler() - sched.On("Error").Return() - - // Set expections and return values. - messenger := messenger.NewMockedMessenger() - messenger.On("Start").Return(nil) - messenger.On("UPID").Return(upid.UPID{}) - messenger.On("Stop").Return(nil) - messenger.On("Install").Return(nil) - - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(sched, suite.framework, suite.master, nil, messenger)) - - // reliable registration loops until the driver is stopped, connected, etc.. - stat, err := driver.Start() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) - - time.Sleep(5 * time.Second) // wait a bit, registration should be looping... - - suite.True(driver.Running()) - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - // stop the driver, should not panic! - driver.Stop(false) // intentionally not failing over - suite.False(driver.Running()) - suite.Equal(mesos.Status_DRIVER_STOPPED, driver.Status()) - - messenger.AssertExpectations(suite.T()) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverJoinUnstarted() { - driver := newTestSchedulerDriver(suite.T(), driverConfig(NewMockScheduler(), suite.framework, suite.master, nil)) - suite.False(driver.Running()) - - stat, err := driver.Join() - suite.Error(err) - suite.Equal(mesos.Status_DRIVER_NOT_STARTED, stat) - suite.False(driver.Running()) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverJoinOK() { - // Set expections and return values. - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - suite.False(driver.Running()) - - stat, err := driver.Start() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) - suite.True(driver.Running()) - - testCh := make(chan mesos.Status) - go func() { - stat, _ := driver.Join() - testCh <- stat - }() - - driver.Stop(true) -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverRun() { - // Set expections and return values. - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - suite.False(driver.Running()) - - ch := make(chan struct{}) - go func() { - defer close(ch) - stat, err := driver.Run() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_STOPPED, stat) - }() - <-driver.started - suite.True(driver.Running()) - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - // close it all. - driver.Stop(true) - <-ch -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverStopUnstarted() { - driver := newTestSchedulerDriver(suite.T(), driverConfig(NewMockScheduler(), suite.framework, suite.master, nil)) - suite.False(driver.Running()) - - stat, err := driver.Stop(true) - suite.NotNil(err) - suite.False(driver.Running()) - suite.Equal(mesos.Status_DRIVER_NOT_STARTED, stat) -} - -type msgTracker struct { - *messenger.MockedMessenger - lastMessage proto.Message -} - -func (m *msgTracker) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { - m.lastMessage = msg - return m.MockedMessenger.Send(ctx, upid, msg) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverStop_WithoutFailover() { - // Set expections and return values. - messenger := &msgTracker{MockedMessenger: mockedMessenger()} - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, messenger)) - suite.False(driver.Running()) - - ch := make(chan struct{}) - go func() { - defer close(ch) - stat, err := driver.Run() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_STOPPED, stat) - }() - <-driver.started - suite.True(driver.Running()) - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - driver.connected = true // pretend that we're already registered - - driver.Stop(false) - - msg := messenger.lastMessage - suite.NotNil(msg) - _, isUnregMsg := msg.(proto.Message) - suite.True(isUnregMsg, "expected UnregisterFrameworkMessage instead of %+v", msg) - - suite.False(driver.Running()) - suite.Equal(mesos.Status_DRIVER_STOPPED, driver.Status()) - <-ch -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverStop_WithFailover() { - // Set expections and return values. - mess := &msgTracker{MockedMessenger: mockedMessenger()} - d := DriverConfig{ - Scheduler: NewMockScheduler(), - Framework: suite.framework, - Master: suite.master, - NewMessenger: func() (messenger.Messenger, error) { return mess, nil }, - NewDetector: func() (detector.Master, error) { return nil, nil }, - } - driver := newTestSchedulerDriver(suite.T(), d) - suite.False(driver.Running()) - - ch := make(chan struct{}) - go func() { - defer close(ch) - stat, err := driver.Run() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_STOPPED, stat) - }() - <-driver.started - driver.setConnected(true) // simulated - - suite.True(driver.Running()) - driver.Stop(true) // true = scheduler failover - msg := mess.lastMessage - - // we're expecting that lastMessage is nil because when failing over there's no - // 'unregister' message sent by the scheduler. - suite.Nil(msg) - - suite.False(driver.Running()) - suite.Equal(mesos.Status_DRIVER_STOPPED, driver.Status()) - <-ch -} - -func (suite *SchedulerTestSuite) TestSchedulerDriverAbort() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - suite.False(driver.Running()) - - ch := make(chan struct{}) - go func() { - defer close(ch) - stat, err := driver.Run() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_ABORTED, stat) - }() - <-driver.started - driver.setConnected(true) // simulated - - suite.True(driver.Running()) - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - stat, err := driver.Abort() - suite.NoError(err) - - <-driver.stopCh - suite.False(driver.Running()) - suite.Equal(mesos.Status_DRIVER_ABORTED, stat) - suite.Equal(mesos.Status_DRIVER_ABORTED, driver.Status()) - log.Info("waiting for driver to stop") - <-ch -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverLunchTasksUnstarted() { - sched := NewMockScheduler() - sched.On("Error").Return() - - // Set expections and return values. - messenger := messenger.NewMockedMessenger() - messenger.On("Route").Return(nil) - messenger.On("Install").Return(nil) - - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(sched, suite.framework, suite.master, nil, messenger)) - - stat, err := driver.LaunchTasks( - []*mesos.OfferID{{}}, - []*mesos.TaskInfo{}, - &mesos.Filters{}, - ) - suite.Error(err) - suite.Equal(mesos.Status_DRIVER_NOT_STARTED, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverLaunchTasksWithError() { - sched := NewMockScheduler() - sched.On("StatusUpdate").Return(nil) - sched.On("Error").Return() - - msgr := mockedMessenger() - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(sched, suite.framework, suite.master, nil, msgr)) - driver.dispatch = func(_ context.Context, _ *upid.UPID, _ proto.Message) error { - return fmt.Errorf("Unable to send message") - } - - go func() { - driver.Run() - }() - <-driver.started - driver.setConnected(true) // simulated - suite.True(driver.Running()) - - // setup an offer - offer := util.NewOffer( - util.NewOfferID("test-offer-001"), - suite.framework.Id, - util.NewSlaveID("test-slave-001"), - "test-slave(1)@localhost:5050", - ) - - pid, err := upid.Parse("test-slave(1)@localhost:5050") - suite.NoError(err) - driver.cache.putOffer(offer, pid) - - // launch task - task := util.NewTaskInfo( - "simple-task", - util.NewTaskID("simpe-task-1"), - util.NewSlaveID("test-slave-001"), - []*mesos.Resource{util.NewScalarResource("mem", 400)}, - ) - task.Command = util.NewCommandInfo("pwd") - task.Executor = util.NewExecutorInfo(util.NewExecutorID("test-exec"), task.Command) - tasks := []*mesos.TaskInfo{task} - - stat, err := driver.LaunchTasks( - []*mesos.OfferID{offer.Id}, - tasks, - &mesos.Filters{}, - ) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) - suite.Error(err) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverLaunchTasks() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - go func() { - driver.Run() - }() - <-driver.started - driver.setConnected(true) // simulated - suite.True(driver.Running()) - - task := util.NewTaskInfo( - "simple-task", - util.NewTaskID("simpe-task-1"), - util.NewSlaveID("slave-1"), - []*mesos.Resource{util.NewScalarResource("mem", 400)}, - ) - task.Command = util.NewCommandInfo("pwd") - tasks := []*mesos.TaskInfo{task} - - stat, err := driver.LaunchTasks( - []*mesos.OfferID{{}}, - tasks, - &mesos.Filters{}, - ) - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverKillTask() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - go func() { - driver.Run() - }() - <-driver.started - driver.setConnected(true) // simulated - suite.True(driver.Running()) - - stat, err := driver.KillTask(util.NewTaskID("test-task-1")) - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverRequestResources() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - driver.Start() - driver.setConnected(true) // simulated - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - stat, err := driver.RequestResources( - []*mesos.Request{ - { - SlaveId: util.NewSlaveID("test-slave-001"), - Resources: []*mesos.Resource{ - util.NewScalarResource("test-res-001", 33.00), - }, - }, - }, - ) - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverDeclineOffers() { - // see LaunchTasks test -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverReviveOffers() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - driver.Start() - driver.setConnected(true) // simulated - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - stat, err := driver.ReviveOffers() - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverSendFrameworkMessage() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - driver.Start() - driver.setConnected(true) // simulated - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - stat, err := driver.SendFrameworkMessage( - util.NewExecutorID("test-exec-001"), - util.NewSlaveID("test-slave-001"), - "Hello!", - ) - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} - -func (suite *SchedulerTestSuite) TestSchdulerDriverReconcileTasks() { - driver := newTestSchedulerDriver(suite.T(), driverConfigMessenger(NewMockScheduler(), suite.framework, suite.master, nil, mockedMessenger())) - - driver.Start() - driver.setConnected(true) // simulated - suite.Equal(mesos.Status_DRIVER_RUNNING, driver.Status()) - - stat, err := driver.ReconcileTasks( - []*mesos.TaskStatus{ - util.NewTaskStatus(util.NewTaskID("test-task-001"), mesos.TaskState_TASK_FINISHED), - }, - ) - suite.NoError(err) - suite.Equal(mesos.Status_DRIVER_RUNNING, stat) -} diff --git a/Godeps/_workspace/src/github.com/mesos/mesos-go/upid/upid_test.go b/Godeps/_workspace/src/github.com/mesos/mesos-go/upid/upid_test.go deleted file mode 100644 index 99d446bfd34..00000000000 --- a/Godeps/_workspace/src/github.com/mesos/mesos-go/upid/upid_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package upid - -import ( - "testing" - "testing/quick" - - "github.com/stretchr/testify/assert" -) - -func TestUPIDParse(t *testing.T) { - u, err := Parse("mesos@foo:bar") - assert.Nil(t, u) - assert.Error(t, err) - - u, err = Parse("mesoslocalhost5050") - assert.Nil(t, u) - assert.Error(t, err) - - u, err = Parse("mesos@localhost") - assert.Nil(t, u) - assert.Error(t, err) - - assert.Nil(t, quick.Check(func(s string) bool { - u, err := Parse(s) - return u == nil && err != nil - }, &quick.Config{MaxCount: 100000})) -} - -func TestUPIDString(t *testing.T) { - u, err := Parse("mesos@localhost:5050") - assert.NotNil(t, u) - assert.NoError(t, err) - assert.Equal(t, "mesos@localhost:5050", u.String()) -} - -func TestUPIDEqual(t *testing.T) { - u1, err := Parse("mesos@localhost:5050") - u2, err := Parse("mesos@localhost:5050") - u3, err := Parse("mesos1@localhost:5050") - u4, err := Parse("mesos@mesos.com:5050") - u5, err := Parse("mesos@localhost:5051") - assert.NoError(t, err) - - assert.True(t, u1.Equal(u2)) - assert.False(t, u1.Equal(u3)) - assert.False(t, u1.Equal(u4)) - assert.False(t, u1.Equal(u5)) - assert.False(t, u1.Equal(nil)) - assert.False(t, (*UPID)(nil).Equal(u5)) - assert.True(t, (*UPID)(nil).Equal(nil)) -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/client_test.go b/Godeps/_workspace/src/github.com/miekg/dns/client_test.go deleted file mode 100644 index 2113f3b0e5b..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/client_test.go +++ /dev/null @@ -1,195 +0,0 @@ -package dns - -import ( - "testing" - "time" -) - -func TestClientSync(t *testing.T) { - HandleFunc("miek.nl.", HelloServer) - defer HandleRemove("miek.nl.") - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - m := new(Msg) - m.SetQuestion("miek.nl.", TypeSOA) - - c := new(Client) - r, _, e := c.Exchange(m, addrstr) - if e != nil { - t.Logf("failed to exchange: %s", e.Error()) - t.Fail() - } - if r != nil && r.Rcode != RcodeSuccess { - t.Log("failed to get an valid answer") - t.Fail() - t.Logf("%v\n", r) - } - // And now with plain Exchange(). - r, e = Exchange(m, addrstr) - if e != nil { - t.Logf("failed to exchange: %s", e.Error()) - t.Fail() - } - if r != nil && r.Rcode != RcodeSuccess { - t.Log("failed to get an valid answer") - t.Fail() - t.Logf("%v\n", r) - } -} - -func TestClientEDNS0(t *testing.T) { - HandleFunc("miek.nl.", HelloServer) - defer HandleRemove("miek.nl.") - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - m := new(Msg) - m.SetQuestion("miek.nl.", TypeDNSKEY) - - m.SetEdns0(2048, true) - - c := new(Client) - r, _, e := c.Exchange(m, addrstr) - if e != nil { - t.Logf("failed to exchange: %s", e.Error()) - t.Fail() - } - - if r != nil && r.Rcode != RcodeSuccess { - t.Log("failed to get an valid answer") - t.Fail() - t.Logf("%v\n", r) - } -} - -func TestSingleSingleInflight(t *testing.T) { - HandleFunc("miek.nl.", HelloServer) - defer HandleRemove("miek.nl.") - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - m := new(Msg) - m.SetQuestion("miek.nl.", TypeDNSKEY) - - c := new(Client) - c.SingleInflight = true - nr := 10 - ch := make(chan time.Duration) - for i := 0; i < nr; i++ { - go func() { - _, rtt, _ := c.Exchange(m, addrstr) - ch <- rtt - }() - } - i := 0 - var first time.Duration - // With inflight *all* rtt are identical, and by doing actual lookups - // the changes that this is a coincidence is small. -Loop: - for { - select { - case rtt := <-ch: - if i == 0 { - first = rtt - } else { - if first != rtt { - t.Log("all rtts should be equal") - t.Fail() - } - } - i++ - if i == 10 { - break Loop - } - } - } -} - -/* -func TestClientTsigAXFR(t *testing.T) { - m := new(Msg) - m.SetAxfr("example.nl.") - m.SetTsig("axfr.", HmacMD5, 300, time.Now().Unix()) - - tr := new(Transfer) - tr.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="} - - if a, err := tr.In(m, "176.58.119.54:53"); err != nil { - t.Log("failed to setup axfr: " + err.Error()) - t.Fatal() - } else { - for ex := range a { - if ex.Error != nil { - t.Logf("error %s\n", ex.Error.Error()) - t.Fail() - break - } - for _, rr := range ex.RR { - t.Logf("%s\n", rr.String()) - } - } - } -} - -func TestClientAXFRMultipleEnvelopes(t *testing.T) { - m := new(Msg) - m.SetAxfr("nlnetlabs.nl.") - - tr := new(Transfer) - if a, err := tr.In(m, "213.154.224.1:53"); err != nil { - t.Log("Failed to setup axfr" + err.Error()) - t.Fail() - return - } else { - for ex := range a { - if ex.Error != nil { - t.Logf("Error %s\n", ex.Error.Error()) - t.Fail() - break - } - } - } -} -*/ - -// ExampleUpdateLeaseTSIG shows how to update a lease signed with TSIG. -func ExampleUpdateLeaseTSIG(t *testing.T) { - m := new(Msg) - m.SetUpdate("t.local.ip6.io.") - rr, _ := NewRR("t.local.ip6.io. 30 A 127.0.0.1") - rrs := make([]RR, 1) - rrs[0] = rr - m.Insert(rrs) - - lease_rr := new(OPT) - lease_rr.Hdr.Name = "." - lease_rr.Hdr.Rrtype = TypeOPT - e := new(EDNS0_UL) - e.Code = EDNS0UL - e.Lease = 120 - lease_rr.Option = append(lease_rr.Option, e) - m.Extra = append(m.Extra, lease_rr) - - c := new(Client) - m.SetTsig("polvi.", HmacMD5, 300, time.Now().Unix()) - c.TsigSecret = map[string]string{"polvi.": "pRZgBrBvI4NAHZYhxmhs/Q=="} - - _, _, err := c.Exchange(m, "127.0.0.1:53") - if err != nil { - t.Log(err.Error()) - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go deleted file mode 100644 index 16c86f474f1..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go +++ /dev/null @@ -1,511 +0,0 @@ -package dns - -import ( - "encoding/hex" - "net" - "testing" -) - -func TestPackUnpack(t *testing.T) { - out := new(Msg) - out.Answer = make([]RR, 1) - key := new(DNSKEY) - key = &DNSKEY{Flags: 257, Protocol: 3, Algorithm: RSASHA1} - key.Hdr = RR_Header{Name: "miek.nl.", Rrtype: TypeDNSKEY, Class: ClassINET, Ttl: 3600} - key.PublicKey = "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ" - - out.Answer[0] = key - msg, err := out.Pack() - if err != nil { - t.Log("failed to pack msg with DNSKEY") - t.Fail() - } - in := new(Msg) - if in.Unpack(msg) != nil { - t.Log("failed to unpack msg with DNSKEY") - t.Fail() - } - - sig := new(RRSIG) - sig = &RRSIG{TypeCovered: TypeDNSKEY, Algorithm: RSASHA1, Labels: 2, - OrigTtl: 3600, Expiration: 4000, Inception: 4000, KeyTag: 34641, SignerName: "miek.nl.", - Signature: "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ"} - sig.Hdr = RR_Header{Name: "miek.nl.", Rrtype: TypeRRSIG, Class: ClassINET, Ttl: 3600} - - out.Answer[0] = sig - msg, err = out.Pack() - if err != nil { - t.Log("failed to pack msg with RRSIG") - t.Fail() - } - - if in.Unpack(msg) != nil { - t.Log("failed to unpack msg with RRSIG") - t.Fail() - } -} - -func TestPackUnpack2(t *testing.T) { - m := new(Msg) - m.Extra = make([]RR, 1) - m.Answer = make([]RR, 1) - dom := "miek.nl." - rr := new(A) - rr.Hdr = RR_Header{Name: dom, Rrtype: TypeA, Class: ClassINET, Ttl: 0} - rr.A = net.IPv4(127, 0, 0, 1) - - x := new(TXT) - x.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0} - x.Txt = []string{"heelalaollo"} - - m.Extra[0] = x - m.Answer[0] = rr - _, err := m.Pack() - if err != nil { - t.Log("Packing failed: " + err.Error()) - t.Fail() - return - } -} - -func TestPackUnpack3(t *testing.T) { - m := new(Msg) - m.Extra = make([]RR, 2) - m.Answer = make([]RR, 1) - dom := "miek.nl." - rr := new(A) - rr.Hdr = RR_Header{Name: dom, Rrtype: TypeA, Class: ClassINET, Ttl: 0} - rr.A = net.IPv4(127, 0, 0, 1) - - x1 := new(TXT) - x1.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0} - x1.Txt = []string{} - - x2 := new(TXT) - x2.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0} - x2.Txt = []string{"heelalaollo"} - - m.Extra[0] = x1 - m.Extra[1] = x2 - m.Answer[0] = rr - b, err := m.Pack() - if err != nil { - t.Log("packing failed: " + err.Error()) - t.Fail() - return - } - - var unpackMsg Msg - err = unpackMsg.Unpack(b) - if err != nil { - t.Log("unpacking failed") - t.Fail() - return - } -} - -func TestBailiwick(t *testing.T) { - yes := map[string]string{ - "miek.nl": "ns.miek.nl", - ".": "miek.nl", - } - for parent, child := range yes { - if !IsSubDomain(parent, child) { - t.Logf("%s should be child of %s\n", child, parent) - t.Logf("comparelabels %d", CompareDomainName(parent, child)) - t.Logf("lenlabels %d %d", CountLabel(parent), CountLabel(child)) - t.Fail() - } - } - no := map[string]string{ - "www.miek.nl": "ns.miek.nl", - "m\\.iek.nl": "ns.miek.nl", - "w\\.iek.nl": "w.iek.nl", - "p\\\\.iek.nl": "ns.p.iek.nl", // p\\.iek.nl , literal \ in domain name - "miek.nl": ".", - } - for parent, child := range no { - if IsSubDomain(parent, child) { - t.Logf("%s should not be child of %s\n", child, parent) - t.Logf("comparelabels %d", CompareDomainName(parent, child)) - t.Logf("lenlabels %d %d", CountLabel(parent), CountLabel(child)) - t.Fail() - } - } -} - -func TestPack(t *testing.T) { - rr := []string{"US. 86400 IN NSEC 0-.us. NS SOA RRSIG NSEC DNSKEY TYPE65534"} - m := new(Msg) - var err error - m.Answer = make([]RR, 1) - for _, r := range rr { - m.Answer[0], err = NewRR(r) - if err != nil { - t.Logf("failed to create RR: %s\n", err.Error()) - t.Fail() - continue - } - if _, err := m.Pack(); err != nil { - t.Logf("packing failed: %s\n", err.Error()) - t.Fail() - } - } - x := new(Msg) - ns, _ := NewRR("pool.ntp.org. 390 IN NS a.ntpns.org") - ns.(*NS).Ns = "a.ntpns.org" - x.Ns = append(m.Ns, ns) - x.Ns = append(m.Ns, ns) - x.Ns = append(m.Ns, ns) - // This crashes due to the fact the a.ntpns.org isn't a FQDN - // How to recover() from a remove panic()? - if _, err := x.Pack(); err == nil { - t.Log("packing should fail") - t.Fail() - } - x.Answer = make([]RR, 1) - x.Answer[0], err = NewRR(rr[0]) - if _, err := x.Pack(); err == nil { - t.Log("packing should fail") - t.Fail() - } - x.Question = make([]Question, 1) - x.Question[0] = Question{";sd#edddds鍛↙赏‘℅∥↙xzztsestxssweewwsssstx@s@Z嵌e@cn.pool.ntp.org.", TypeA, ClassINET} - if _, err := x.Pack(); err == nil { - t.Log("packing should fail") - t.Fail() - } -} - -func TestPackNAPTR(t *testing.T) { - for _, n := range []string{ - `apple.com. IN NAPTR 100 50 "se" "SIP+D2U" "" _sip._udp.apple.com.`, - `apple.com. IN NAPTR 90 50 "se" "SIP+D2T" "" _sip._tcp.apple.com.`, - `apple.com. IN NAPTR 50 50 "se" "SIPS+D2T" "" _sips._tcp.apple.com.`, - } { - rr, _ := NewRR(n) - msg := make([]byte, rr.len()) - if off, err := PackRR(rr, msg, 0, nil, false); err != nil { - t.Logf("packing failed: %s", err.Error()) - t.Logf("length %d, need more than %d\n", rr.len(), off) - t.Fail() - } else { - t.Logf("buf size needed: %d\n", off) - } - } -} - -func TestCompressLength(t *testing.T) { - m := new(Msg) - m.SetQuestion("miek.nl", TypeMX) - ul := m.Len() - m.Compress = true - if ul != m.Len() { - t.Fatalf("should be equal") - } -} - -// Does the predicted length match final packed length? -func TestMsgCompressLength(t *testing.T) { - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - msg.Compress = true - return msg - } - - name1 := "12345678901234567890123456789012345.12345678.123." - rrA, _ := NewRR(name1 + " 3600 IN A 192.0.2.1") - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - tests := []*Msg{ - makeMsg(name1, []RR{rrA}, nil, nil), - makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)} - - for _, msg := range tests { - predicted := msg.Len() - buf, err := msg.Pack() - if err != nil { - t.Error(err) - t.Fail() - } - if predicted < len(buf) { - t.Errorf("predicted compressed length is wrong: predicted %s (len=%d) %d, actual %d\n", - msg.Question[0].Name, len(msg.Answer), predicted, len(buf)) - t.Fail() - } - } -} - -func TestMsgLength(t *testing.T) { - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - return msg - } - - name1 := "12345678901234567890123456789012345.12345678.123." - rrA, _ := NewRR(name1 + " 3600 IN A 192.0.2.1") - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - tests := []*Msg{ - makeMsg(name1, []RR{rrA}, nil, nil), - makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)} - - for _, msg := range tests { - predicted := msg.Len() - buf, err := msg.Pack() - if err != nil { - t.Error(err) - t.Fail() - } - if predicted < len(buf) { - t.Errorf("predicted length is wrong: predicted %s (len=%d), actual %d\n", - msg.Question[0].Name, predicted, len(buf)) - t.Fail() - } - } -} - -func TestMsgLength2(t *testing.T) { - // Serialized replies - var testMessages = []string{ - // google.com. IN A? - "064e81800001000b0004000506676f6f676c6503636f6d0000010001c00c00010001000000050004adc22986c00c00010001000000050004adc22987c00c00010001000000050004adc22988c00c00010001000000050004adc22989c00c00010001000000050004adc2298ec00c00010001000000050004adc22980c00c00010001000000050004adc22981c00c00010001000000050004adc22982c00c00010001000000050004adc22983c00c00010001000000050004adc22984c00c00010001000000050004adc22985c00c00020001000000050006036e7331c00cc00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc0d800010001000000050004d8ef200ac0ea00010001000000050004d8ef220ac0fc00010001000000050004d8ef240ac10e00010001000000050004d8ef260a0000290500000000050000", - // amazon.com. IN A? (reply has no EDNS0 record) - // TODO(miek): this one is off-by-one, need to find out why - //"6de1818000010004000a000806616d617a6f6e03636f6d0000010001c00c000100010000000500044815c2d4c00c000100010000000500044815d7e8c00c00010001000000050004b02062a6c00c00010001000000050004cdfbf236c00c000200010000000500140570646e733408756c747261646e73036f726700c00c000200010000000500150570646e733508756c747261646e7304696e666f00c00c000200010000000500160570646e733608756c747261646e7302636f02756b00c00c00020001000000050014036e7331037033310664796e656374036e657400c00c00020001000000050006036e7332c0cfc00c00020001000000050006036e7333c0cfc00c00020001000000050006036e7334c0cfc00c000200010000000500110570646e733108756c747261646e73c0dac00c000200010000000500080570646e7332c127c00c000200010000000500080570646e7333c06ec0cb00010001000000050004d04e461fc0eb00010001000000050004cc0dfa1fc0fd00010001000000050004d04e471fc10f00010001000000050004cc0dfb1fc12100010001000000050004cc4a6c01c121001c000100000005001020010502f3ff00000000000000000001c13e00010001000000050004cc4a6d01c13e001c0001000000050010261000a1101400000000000000000001", - // yahoo.com. IN A? - "fc2d81800001000300070008057961686f6f03636f6d0000010001c00c00010001000000050004628afd6dc00c00010001000000050004628bb718c00c00010001000000050004cebe242dc00c00020001000000050006036e7336c00cc00c00020001000000050006036e7338c00cc00c00020001000000050006036e7331c00cc00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc00c00020001000000050006036e7335c00cc07b0001000100000005000444b48310c08d00010001000000050004448eff10c09f00010001000000050004cb54dd35c0b100010001000000050004628a0b9dc0c30001000100000005000477a0f77cc05700010001000000050004ca2bdfaac06900010001000000050004caa568160000290500000000050000", - // microsoft.com. IN A? - "f4368180000100020005000b096d6963726f736f667403636f6d0000010001c00c0001000100000005000440040b25c00c0001000100000005000441373ac9c00c0002000100000005000e036e7331046d736674036e657400c00c00020001000000050006036e7332c04fc00c00020001000000050006036e7333c04fc00c00020001000000050006036e7334c04fc00c00020001000000050006036e7335c04fc04b000100010000000500044137253ec04b001c00010000000500102a010111200500000000000000010001c0650001000100000005000440043badc065001c00010000000500102a010111200600060000000000010001c07700010001000000050004d5c7b435c077001c00010000000500102a010111202000000000000000010001c08900010001000000050004cf2e4bfec089001c00010000000500102404f800200300000000000000010001c09b000100010000000500044137e28cc09b001c00010000000500102a010111200f000100000000000100010000290500000000050000", - // google.com. IN MX? - "724b8180000100050004000b06676f6f676c6503636f6d00000f0001c00c000f000100000005000c000a056173706d78016cc00cc00c000f0001000000050009001404616c7431c02ac00c000f0001000000050009001e04616c7432c02ac00c000f0001000000050009002804616c7433c02ac00c000f0001000000050009003204616c7434c02ac00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc00c00020001000000050006036e7331c00cc02a00010001000000050004adc2421bc02a001c00010000000500102a00145040080c01000000000000001bc04200010001000000050004adc2461bc05700010001000000050004adc2451bc06c000100010000000500044a7d8f1bc081000100010000000500044a7d191bc0ca00010001000000050004d8ef200ac09400010001000000050004d8ef220ac0a600010001000000050004d8ef240ac0b800010001000000050004d8ef260a0000290500000000050000", - // reddit.com. IN A? - "12b98180000100080000000c0672656464697403636f6d0000020001c00c0002000100000005000f046175733204616b616d036e657400c00c000200010000000500070475736534c02dc00c000200010000000500070475737733c02dc00c000200010000000500070475737735c02dc00c00020001000000050008056173696131c02dc00c00020001000000050008056173696139c02dc00c00020001000000050008056e73312d31c02dc00c0002000100000005000a076e73312d313935c02dc02800010001000000050004c30a242ec04300010001000000050004451f1d39c05600010001000000050004451f3bc7c0690001000100000005000460073240c07c000100010000000500046007fb81c090000100010000000500047c283484c090001c00010000000500102a0226f0006700000000000000000064c0a400010001000000050004c16c5b01c0a4001c000100000005001026001401000200000000000000000001c0b800010001000000050004c16c5bc3c0b8001c0001000000050010260014010002000000000000000000c30000290500000000050000", - } - - for i, hexData := range testMessages { - // we won't fail the decoding of the hex - input, _ := hex.DecodeString(hexData) - m := new(Msg) - m.Unpack(input) - //println(m.String()) - m.Compress = true - lenComp := m.Len() - b, _ := m.Pack() - pacComp := len(b) - m.Compress = false - lenUnComp := m.Len() - b, _ = m.Pack() - pacUnComp := len(b) - if pacComp+1 != lenComp { - t.Errorf("msg.Len(compressed)=%d actual=%d for test %d", lenComp, pacComp, i) - } - if pacUnComp+1 != lenUnComp { - t.Errorf("msg.Len(uncompressed)=%d actual=%d for test %d", lenUnComp, pacUnComp, i) - } - } -} - -func TestMsgLengthCompressionMalformed(t *testing.T) { - // SOA with empty hostmaster, which is illegal - soa := &SOA{Hdr: RR_Header{Name: ".", Rrtype: TypeSOA, Class: ClassINET, Ttl: 12345}, - Ns: ".", - Mbox: "", - Serial: 0, - Refresh: 28800, - Retry: 7200, - Expire: 604800, - Minttl: 60} - m := new(Msg) - m.Compress = true - m.Ns = []RR{soa} - m.Len() // Should not crash. -} - -func BenchmarkMsgLength(b *testing.B) { - b.StopTimer() - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - msg.Compress = true - return msg - } - name1 := "12345678901234567890123456789012345.12345678.123." - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil) - b.StartTimer() - for i := 0; i < b.N; i++ { - msg.Len() - } -} - -func BenchmarkMsgLengthPack(b *testing.B) { - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - msg.Compress = true - return msg - } - name1 := "12345678901234567890123456789012345.12345678.123." - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = msg.Pack() - } -} - -func BenchmarkMsgPackBuffer(b *testing.B) { - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - msg.Compress = true - return msg - } - name1 := "12345678901234567890123456789012345.12345678.123." - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil) - buf := make([]byte, 512) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = msg.PackBuffer(buf) - } -} - -func BenchmarkMsgUnpack(b *testing.B) { - makeMsg := func(question string, ans, ns, e []RR) *Msg { - msg := new(Msg) - msg.SetQuestion(Fqdn(question), TypeANY) - msg.Answer = append(msg.Answer, ans...) - msg.Ns = append(msg.Ns, ns...) - msg.Extra = append(msg.Extra, e...) - msg.Compress = true - return msg - } - name1 := "12345678901234567890123456789012345.12345678.123." - rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1) - msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil) - msg_buf, _ := msg.Pack() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = msg.Unpack(msg_buf) - } -} - -func BenchmarkPackDomainName(b *testing.B) { - name1 := "12345678901234567890123456789012345.12345678.123." - buf := make([]byte, len(name1)+1) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _ = PackDomainName(name1, buf, 0, nil, false) - } -} - -func BenchmarkUnpackDomainName(b *testing.B) { - name1 := "12345678901234567890123456789012345.12345678.123." - buf := make([]byte, len(name1)+1) - _, _ = PackDomainName(name1, buf, 0, nil, false) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _, _ = UnpackDomainName(buf, 0) - } -} - -func BenchmarkUnpackDomainNameUnprintable(b *testing.B) { - name1 := "\x02\x02\x02\x025\x02\x02\x02\x02.12345678.123." - buf := make([]byte, len(name1)+1) - _, _ = PackDomainName(name1, buf, 0, nil, false) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, _, _ = UnpackDomainName(buf, 0) - } -} - -func TestToRFC3597(t *testing.T) { - a, _ := NewRR("miek.nl. IN A 10.0.1.1") - x := new(RFC3597) - x.ToRFC3597(a) - if x.String() != `miek.nl. 3600 CLASS1 TYPE1 \# 4 0a000101` { - t.Fail() - } -} - -func TestNoRdataPack(t *testing.T) { - data := make([]byte, 1024) - for typ, fn := range typeToRR { - if typ == TypeCAA { - continue // TODO(miek): known omission - } - r := fn() - *r.Header() = RR_Header{Name: "miek.nl.", Rrtype: typ, Class: ClassINET, Ttl: 3600} - _, e := PackRR(r, data, 0, nil, false) - if e != nil { - t.Logf("failed to pack RR with zero rdata: %s: %s\n", TypeToString[typ], e.Error()) - t.Fail() - } - } -} - -// TODO(miek): fix dns buffer too small errors this throws -func TestNoRdataUnpack(t *testing.T) { - data := make([]byte, 1024) - for typ, fn := range typeToRR { - if typ == TypeSOA || typ == TypeTSIG || typ == TypeWKS { - // SOA, TSIG will not be seen (like this) in dyn. updates? - // WKS is an bug, but...deprecated record. - continue - } - r := fn() - *r.Header() = RR_Header{Name: "miek.nl.", Rrtype: typ, Class: ClassINET, Ttl: 3600} - off, e := PackRR(r, data, 0, nil, false) - if e != nil { - // Should always works, TestNoDataPack should have catched this - continue - } - rr, _, e := UnpackRR(data[:off], 0) - if e != nil { - t.Logf("failed to unpack RR with zero rdata: %s: %s\n", TypeToString[typ], e.Error()) - t.Fail() - } - t.Logf("%s\n", rr) - } -} - -func TestRdataOverflow(t *testing.T) { - rr := new(RFC3597) - rr.Hdr.Name = "." - rr.Hdr.Class = ClassINET - rr.Hdr.Rrtype = 65280 - rr.Rdata = hex.EncodeToString(make([]byte, 0xFFFF)) - buf := make([]byte, 0xFFFF*2) - if _, err := PackRR(rr, buf, 0, nil, false); err != nil { - t.Fatalf("maximum size rrdata pack failed: %v", err) - } - rr.Rdata += "00" - if _, err := PackRR(rr, buf, 0, nil, false); err != ErrRdata { - t.Fatalf("oversize rrdata pack didn't return ErrRdata - instead: %v", err) - } -} - -func TestCopy(t *testing.T) { - rr, _ := NewRR("miek.nl. 2311 IN A 127.0.0.1") // Weird TTL to avoid catching TTL - rr1 := Copy(rr) - if rr.String() != rr1.String() { - t.Fatalf("Copy() failed %s != %s", rr.String(), rr1.String()) - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go deleted file mode 100644 index f6263d505f4..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go +++ /dev/null @@ -1,672 +0,0 @@ -package dns - -import ( - "crypto/rsa" - "reflect" - "strings" - "testing" - "time" -) - -func getKey() *DNSKEY { - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz" - return key -} - -func getSoa() *SOA { - soa := new(SOA) - soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0} - soa.Ns = "open.nlnetlabs.nl." - soa.Mbox = "miekg.atoom.net." - soa.Serial = 1293945905 - soa.Refresh = 14400 - soa.Retry = 3600 - soa.Expire = 604800 - soa.Minttl = 86400 - return soa -} - -func TestGenerateEC(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = ECDSAP256SHA256 - privkey, _ := key.Generate(256) - t.Logf("%s\n", key.String()) - t.Logf("%s\n", key.PrivateKeyString(privkey)) -} - -func TestGenerateDSA(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = DSA - privkey, _ := key.Generate(1024) - t.Logf("%s\n", key.String()) - t.Logf("%s\n", key.PrivateKeyString(privkey)) -} - -func TestGenerateRSA(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - privkey, _ := key.Generate(1024) - t.Logf("%s\n", key.String()) - t.Logf("%s\n", key.PrivateKeyString(privkey)) -} - -func TestSecure(t *testing.T) { - soa := getSoa() - - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.TypeCovered = TypeSOA - sig.Algorithm = RSASHA256 - sig.Labels = 2 - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.OrigTtl = 14400 - sig.KeyTag = 12051 - sig.SignerName = "miek.nl." - sig.Signature = "oMCbslaAVIp/8kVtLSms3tDABpcPRUgHLrOR48OOplkYo+8TeEGWwkSwaz/MRo2fB4FxW0qj/hTlIjUGuACSd+b1wKdH5GvzRJc2pFmxtCbm55ygAh4EUL0F6U5cKtGJGSXxxg6UFCQ0doJCmiGFa78LolaUOXImJrk6AFrGa0M=" - - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz" - - // It should validate. Period is checked seperately, so this will keep on working - if sig.Verify(key, []RR{soa}) != nil { - t.Log("failure to validate") - t.Fail() - } -} - -func TestSignature(t *testing.T) { - sig := new(RRSIG) - sig.Hdr.Name = "miek.nl." - sig.Hdr.Class = ClassINET - sig.Hdr.Ttl = 3600 - sig.TypeCovered = TypeDNSKEY - sig.Algorithm = RSASHA1 - sig.Labels = 2 - sig.OrigTtl = 4000 - sig.Expiration = 1000 //Thu Jan 1 02:06:40 CET 1970 - sig.Inception = 800 //Thu Jan 1 01:13:20 CET 1970 - sig.KeyTag = 34641 - sig.SignerName = "miek.nl." - sig.Signature = "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ" - - // Should not be valid - if sig.ValidityPeriod(time.Now()) { - t.Log("should not be valid") - t.Fail() - } - - sig.Inception = 315565800 //Tue Jan 1 10:10:00 CET 1980 - sig.Expiration = 4102477800 //Fri Jan 1 10:10:00 CET 2100 - if !sig.ValidityPeriod(time.Now()) { - t.Log("should be valid") - t.Fail() - } -} - -func TestSignVerify(t *testing.T) { - // The record we want to sign - soa := new(SOA) - soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0} - soa.Ns = "open.nlnetlabs.nl." - soa.Mbox = "miekg.atoom.net." - soa.Serial = 1293945905 - soa.Refresh = 14400 - soa.Retry = 3600 - soa.Expire = 604800 - soa.Minttl = 86400 - - soa1 := new(SOA) - soa1.Hdr = RR_Header{"*.miek.nl.", TypeSOA, ClassINET, 14400, 0} - soa1.Ns = "open.nlnetlabs.nl." - soa1.Mbox = "miekg.atoom.net." - soa1.Serial = 1293945905 - soa1.Refresh = 14400 - soa1.Retry = 3600 - soa1.Expire = 604800 - soa1.Minttl = 86400 - - srv := new(SRV) - srv.Hdr = RR_Header{"srv.miek.nl.", TypeSRV, ClassINET, 14400, 0} - srv.Port = 1000 - srv.Weight = 800 - srv.Target = "web1.miek.nl." - - // With this key - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - privkey, _ := key.Generate(512) - - // Fill in the values of the Sig, before signing - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.TypeCovered = soa.Hdr.Rrtype - sig.Labels = uint8(CountLabel(soa.Hdr.Name)) // works for all 3 - sig.OrigTtl = soa.Hdr.Ttl - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.KeyTag = key.KeyTag() // Get the keyfrom the Key - sig.SignerName = key.Hdr.Name - sig.Algorithm = RSASHA256 - - for _, r := range []RR{soa, soa1, srv} { - if sig.Sign(privkey, []RR{r}) != nil { - t.Log("failure to sign the record") - t.Fail() - continue - } - if sig.Verify(key, []RR{r}) != nil { - t.Log("failure to validate") - t.Fail() - continue - } - t.Logf("validated: %s\n", r.Header().Name) - } -} - -func Test65534(t *testing.T) { - t6 := new(RFC3597) - t6.Hdr = RR_Header{"miek.nl.", 65534, ClassINET, 14400, 0} - t6.Rdata = "505D870001" - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - privkey, _ := key.Generate(1024) - - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.TypeCovered = t6.Hdr.Rrtype - sig.Labels = uint8(CountLabel(t6.Hdr.Name)) - sig.OrigTtl = t6.Hdr.Ttl - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.KeyTag = key.KeyTag() - sig.SignerName = key.Hdr.Name - sig.Algorithm = RSASHA256 - if err := sig.Sign(privkey, []RR{t6}); err != nil { - t.Log(err) - t.Log("failure to sign the TYPE65534 record") - t.Fail() - } - if err := sig.Verify(key, []RR{t6}); err != nil { - t.Log(err) - t.Log("failure to validate") - t.Fail() - } else { - t.Logf("validated: %s\n", t6.Header().Name) - } -} - -func TestDnskey(t *testing.T) { - // f, _ := os.Open("t/Kmiek.nl.+010+05240.key") - pubkey, _ := ReadRR(strings.NewReader(` -miek.nl. IN DNSKEY 256 3 10 AwEAAZuMCu2FdugHkTrXYgl5qixvcDw1aDDlvL46/xJKbHBAHY16fNUb2b65cwko2Js/aJxUYJbZk5dwCDZxYfrfbZVtDPQuc3o8QaChVxC7/JYz2AHc9qHvqQ1j4VrH71RWINlQo6VYjzN/BGpMhOZoZOEwzp1HfsOE3lNYcoWU1smL ;{id = 5240 (zsk), size = 1024b} -`), "Kmiek.nl.+010+05240.key") - privkey, _ := pubkey.(*DNSKEY).ReadPrivateKey(strings.NewReader(` -Private-key-format: v1.2 -Algorithm: 10 (RSASHA512) -Modulus: m4wK7YV26AeROtdiCXmqLG9wPDVoMOW8vjr/EkpscEAdjXp81RvZvrlzCSjYmz9onFRgltmTl3AINnFh+t9tlW0M9C5zejxBoKFXELv8ljPYAdz2oe+pDWPhWsfvVFYg2VCjpViPM38EakyE5mhk4TDOnUd+w4TeU1hyhZTWyYs= -PublicExponent: AQAB -PrivateExponent: UfCoIQ/Z38l8vB6SSqOI/feGjHEl/fxIPX4euKf0D/32k30fHbSaNFrFOuIFmWMB3LimWVEs6u3dpbB9CQeCVg7hwU5puG7OtuiZJgDAhNeOnxvo5btp4XzPZrJSxR4WNQnwIiYWbl0aFlL1VGgHC/3By89ENZyWaZcMLW4KGWE= -Prime1: yxwC6ogAu8aVcDx2wg1V0b5M5P6jP8qkRFVMxWNTw60Vkn+ECvw6YAZZBHZPaMyRYZLzPgUlyYRd0cjupy4+fQ== -Prime2: xA1bF8M0RTIQ6+A11AoVG6GIR/aPGg5sogRkIZ7ID/sF6g9HMVU/CM2TqVEBJLRPp73cv6ZeC3bcqOCqZhz+pw== -Exponent1: xzkblyZ96bGYxTVZm2/vHMOXswod4KWIyMoOepK6B/ZPcZoIT6omLCgtypWtwHLfqyCz3MK51Nc0G2EGzg8rFQ== -Exponent2: Pu5+mCEb7T5F+kFNZhQadHUklt0JUHbi3hsEvVoHpEGSw3BGDQrtIflDde0/rbWHgDPM4WQY+hscd8UuTXrvLw== -Coefficient: UuRoNqe7YHnKmQzE6iDWKTMIWTuoqqrFAmXPmKQnC+Y+BQzOVEHUo9bXdDnoI9hzXP1gf8zENMYwYLeWpuYlFQ== -`), "Kmiek.nl.+010+05240.private") - if pubkey.(*DNSKEY).PublicKey != "AwEAAZuMCu2FdugHkTrXYgl5qixvcDw1aDDlvL46/xJKbHBAHY16fNUb2b65cwko2Js/aJxUYJbZk5dwCDZxYfrfbZVtDPQuc3o8QaChVxC7/JYz2AHc9qHvqQ1j4VrH71RWINlQo6VYjzN/BGpMhOZoZOEwzp1HfsOE3lNYcoWU1smL" { - t.Log("pubkey is not what we've read") - t.Fail() - } - // Coefficient looks fishy... - t.Logf("%s", pubkey.(*DNSKEY).PrivateKeyString(privkey)) -} - -func TestTag(t *testing.T) { - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 3600 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz" - - tag := key.KeyTag() - if tag != 12051 { - t.Logf("wrong key tag: %d for key %v\n", tag, key) - t.Fail() - } -} - -func TestKeyRSA(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 3600 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - priv, _ := key.Generate(2048) - - soa := new(SOA) - soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0} - soa.Ns = "open.nlnetlabs.nl." - soa.Mbox = "miekg.atoom.net." - soa.Serial = 1293945905 - soa.Refresh = 14400 - soa.Retry = 3600 - soa.Expire = 604800 - soa.Minttl = 86400 - - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.TypeCovered = TypeSOA - sig.Algorithm = RSASHA256 - sig.Labels = 2 - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.OrigTtl = soa.Hdr.Ttl - sig.KeyTag = key.KeyTag() - sig.SignerName = key.Hdr.Name - - if err := sig.Sign(priv, []RR{soa}); err != nil { - t.Logf("failed to sign") - t.Fail() - return - } - if err := sig.Verify(key, []RR{soa}); err != nil { - t.Logf("failed to verify") - t.Fail() - } -} - -func TestKeyToDS(t *testing.T) { - key := new(DNSKEY) - key.Hdr.Name = "miek.nl." - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 3600 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = RSASHA256 - key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz" - - ds := key.ToDS(SHA1) - if strings.ToUpper(ds.Digest) != "B5121BDB5B8D86D0CC5FFAFBAAABE26C3E20BAC1" { - t.Logf("wrong DS digest for SHA1\n%v\n", ds) - t.Fail() - } -} - -func TestSignRSA(t *testing.T) { - pub := "miek.nl. IN DNSKEY 256 3 5 AwEAAb+8lGNCxJgLS8rYVer6EnHVuIkQDghdjdtewDzU3G5R7PbMbKVRvH2Ma7pQyYceoaqWZQirSj72euPWfPxQnMy9ucCylA+FuH9cSjIcPf4PqJfdupHk9X6EBYjxrCLY4p1/yBwgyBIRJtZtAqM3ceAH2WovEJD6rTtOuHo5AluJ" - - priv := `Private-key-format: v1.3 -Algorithm: 5 (RSASHA1) -Modulus: v7yUY0LEmAtLythV6voScdW4iRAOCF2N217APNTcblHs9sxspVG8fYxrulDJhx6hqpZlCKtKPvZ649Z8/FCczL25wLKUD4W4f1xKMhw9/g+ol926keT1foQFiPGsItjinX/IHCDIEhEm1m0Cozdx4AfZai8QkPqtO064ejkCW4k= -PublicExponent: AQAB -PrivateExponent: YPwEmwjk5HuiROKU4xzHQ6l1hG8Iiha4cKRG3P5W2b66/EN/GUh07ZSf0UiYB67o257jUDVEgwCuPJz776zfApcCB4oGV+YDyEu7Hp/rL8KcSN0la0k2r9scKwxTp4BTJT23zyBFXsV/1wRDK1A5NxsHPDMYi2SoK63Enm/1ptk= -Prime1: /wjOG+fD0ybNoSRn7nQ79udGeR1b0YhUA5mNjDx/x2fxtIXzygYk0Rhx9QFfDy6LOBvz92gbNQlzCLz3DJt5hw== -Prime2: wHZsJ8OGhkp5p3mrJFZXMDc2mbYusDVTA+t+iRPdS797Tj0pjvU2HN4vTnTj8KBQp6hmnY7dLp9Y1qserySGbw== -Exponent1: N0A7FsSRIg+IAN8YPQqlawoTtG1t1OkJ+nWrurPootScApX6iMvn8fyvw3p2k51rv84efnzpWAYiC8SUaQDNxQ== -Exponent2: SvuYRaGyvo0zemE3oS+WRm2scxR8eiA8WJGeOc+obwOKCcBgeZblXzfdHGcEC1KaOcetOwNW/vwMA46lpLzJNw== -Coefficient: 8+7ZN/JgByqv0NfULiFKTjtyegUcijRuyij7yNxYbCBneDvZGxJwKNi4YYXWx743pcAj4Oi4Oh86gcmxLs+hGw== -Created: 20110302104537 -Publish: 20110302104537 -Activate: 20110302104537` - - xk, _ := NewRR(pub) - k := xk.(*DNSKEY) - p, err := k.NewPrivateKey(priv) - if err != nil { - t.Logf("%v\n", err) - t.Fail() - } - switch priv := p.(type) { - case *rsa.PrivateKey: - if 65537 != priv.PublicKey.E { - t.Log("exponenent should be 65537") - t.Fail() - } - default: - t.Logf("we should have read an RSA key: %v", priv) - t.Fail() - } - if k.KeyTag() != 37350 { - t.Logf("%d %v\n", k.KeyTag(), k) - t.Log("keytag should be 37350") - t.Fail() - } - - soa := new(SOA) - soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0} - soa.Ns = "open.nlnetlabs.nl." - soa.Mbox = "miekg.atoom.net." - soa.Serial = 1293945905 - soa.Refresh = 14400 - soa.Retry = 3600 - soa.Expire = 604800 - soa.Minttl = 86400 - - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.KeyTag = k.KeyTag() - sig.SignerName = k.Hdr.Name - sig.Algorithm = k.Algorithm - - sig.Sign(p, []RR{soa}) - if sig.Signature != "D5zsobpQcmMmYsUMLxCVEtgAdCvTu8V/IEeP4EyLBjqPJmjt96bwM9kqihsccofA5LIJ7DN91qkCORjWSTwNhzCv7bMyr2o5vBZElrlpnRzlvsFIoAZCD9xg6ZY7ZyzUJmU6IcTwG4v3xEYajcpbJJiyaw/RqR90MuRdKPiBzSo=" { - t.Log("signature is not correct") - t.Logf("%v\n", sig) - t.Fail() - } -} - -func TestSignVerifyECDSA(t *testing.T) { - pub := `example.net. 3600 IN DNSKEY 257 3 14 ( - xKYaNhWdGOfJ+nPrL8/arkwf2EY3MDJ+SErKivBVSum1 - w/egsXvSADtNJhyem5RCOpgQ6K8X1DRSEkrbYQ+OB+v8 - /uX45NBwY8rp65F6Glur8I/mlVNgF6W/qTI37m40 )` - priv := `Private-key-format: v1.2 -Algorithm: 14 (ECDSAP384SHA384) -PrivateKey: WURgWHCcYIYUPWgeLmiPY2DJJk02vgrmTfitxgqcL4vwW7BOrbawVmVe0d9V94SR` - - eckey, err := NewRR(pub) - if err != nil { - t.Fatal(err.Error()) - } - privkey, err := eckey.(*DNSKEY).NewPrivateKey(priv) - if err != nil { - t.Fatal(err.Error()) - } - // TODO: Create seperate test for this - ds := eckey.(*DNSKEY).ToDS(SHA384) - if ds.KeyTag != 10771 { - t.Fatal("wrong keytag on DS") - } - if ds.Digest != "72d7b62976ce06438e9c0bf319013cf801f09ecc84b8d7e9495f27e305c6a9b0563a9b5f4d288405c3008a946df983d6" { - t.Fatal("wrong DS Digest") - } - a, _ := NewRR("www.example.net. 3600 IN A 192.0.2.1") - sig := new(RRSIG) - sig.Hdr = RR_Header{"example.net.", TypeRRSIG, ClassINET, 14400, 0} - sig.Expiration, _ = StringToTime("20100909102025") - sig.Inception, _ = StringToTime("20100812102025") - sig.KeyTag = eckey.(*DNSKEY).KeyTag() - sig.SignerName = eckey.(*DNSKEY).Hdr.Name - sig.Algorithm = eckey.(*DNSKEY).Algorithm - - if sig.Sign(privkey, []RR{a}) != nil { - t.Fatal("failure to sign the record") - } - - if e := sig.Verify(eckey.(*DNSKEY), []RR{a}); e != nil { - t.Logf("\n%s\n%s\n%s\n\n%s\n\n", - eckey.(*DNSKEY).String(), - a.String(), - sig.String(), - eckey.(*DNSKEY).PrivateKeyString(privkey), - ) - - t.Fatalf("failure to validate: %s", e.Error()) - } -} - -func TestSignVerifyECDSA2(t *testing.T) { - srv1, err := NewRR("srv.miek.nl. IN SRV 1000 800 0 web1.miek.nl.") - if err != nil { - t.Fatalf(err.Error()) - } - srv := srv1.(*SRV) - - // With this key - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = ECDSAP256SHA256 - privkey, err := key.Generate(256) - if err != nil { - t.Fatal("failure to generate key") - } - - // Fill in the values of the Sig, before signing - sig := new(RRSIG) - sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0} - sig.TypeCovered = srv.Hdr.Rrtype - sig.Labels = uint8(CountLabel(srv.Hdr.Name)) // works for all 3 - sig.OrigTtl = srv.Hdr.Ttl - sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05" - sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05" - sig.KeyTag = key.KeyTag() // Get the keyfrom the Key - sig.SignerName = key.Hdr.Name - sig.Algorithm = ECDSAP256SHA256 - - if sig.Sign(privkey, []RR{srv}) != nil { - t.Fatal("failure to sign the record") - } - - err = sig.Verify(key, []RR{srv}) - if err != nil { - t.Logf("\n%s\n%s\n%s\n\n%s\n\n", - key.String(), - srv.String(), - sig.String(), - key.PrivateKeyString(privkey), - ) - - t.Fatal("Failure to validate:", err) - } -} - -// Here the test vectors from the relevant RFCs are checked. -// rfc6605 6.1 -func TestRFC6605P256(t *testing.T) { - exDNSKEY := `example.net. 3600 IN DNSKEY 257 3 13 ( - GojIhhXUN/u4v54ZQqGSnyhWJwaubCvTmeexv7bR6edb - krSqQpF64cYbcB7wNcP+e+MAnLr+Wi9xMWyQLc8NAA== )` - exPriv := `Private-key-format: v1.2 -Algorithm: 13 (ECDSAP256SHA256) -PrivateKey: GU6SnQ/Ou+xC5RumuIUIuJZteXT2z0O/ok1s38Et6mQ=` - rrDNSKEY, err := NewRR(exDNSKEY) - if err != nil { - t.Fatal(err.Error()) - } - priv, err := rrDNSKEY.(*DNSKEY).NewPrivateKey(exPriv) - if err != nil { - t.Fatal(err.Error()) - } - - exDS := `example.net. 3600 IN DS 55648 13 2 ( - b4c8c1fe2e7477127b27115656ad6256f424625bf5c1 - e2770ce6d6e37df61d17 )` - rrDS, err := NewRR(exDS) - if err != nil { - t.Fatal(err.Error()) - } - ourDS := rrDNSKEY.(*DNSKEY).ToDS(SHA256) - if !reflect.DeepEqual(ourDS, rrDS.(*DS)) { - t.Errorf("DS record differs:\n%v\n%v\n", ourDS, rrDS.(*DS)) - } - - exA := `www.example.net. 3600 IN A 192.0.2.1` - exRRSIG := `www.example.net. 3600 IN RRSIG A 13 3 3600 ( - 20100909100439 20100812100439 55648 example.net. - qx6wLYqmh+l9oCKTN6qIc+bw6ya+KJ8oMz0YP107epXA - yGmt+3SNruPFKG7tZoLBLlUzGGus7ZwmwWep666VCw== )` - rrA, err := NewRR(exA) - if err != nil { - t.Fatal(err.Error()) - } - rrRRSIG, err := NewRR(exRRSIG) - if err != nil { - t.Fatal(err.Error()) - } - if err = rrRRSIG.(*RRSIG).Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil { - t.Errorf("Failure to validate the spec RRSIG: %v", err) - } - - ourRRSIG := &RRSIG{ - Hdr: RR_Header{ - Ttl: rrA.Header().Ttl, - }, - KeyTag: rrDNSKEY.(*DNSKEY).KeyTag(), - SignerName: rrDNSKEY.(*DNSKEY).Hdr.Name, - Algorithm: rrDNSKEY.(*DNSKEY).Algorithm, - } - ourRRSIG.Expiration, _ = StringToTime("20100909100439") - ourRRSIG.Inception, _ = StringToTime("20100812100439") - err = ourRRSIG.Sign(priv, []RR{rrA}) - if err != nil { - t.Fatal(err.Error()) - } - - if err = ourRRSIG.Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil { - t.Errorf("Failure to validate our RRSIG: %v", err) - } - - // Signatures are randomized - rrRRSIG.(*RRSIG).Signature = "" - ourRRSIG.Signature = "" - if !reflect.DeepEqual(ourRRSIG, rrRRSIG.(*RRSIG)) { - t.Fatalf("RRSIG record differs:\n%v\n%v\n", ourRRSIG, rrRRSIG.(*RRSIG)) - } -} - -// rfc6605 6.2 -func TestRFC6605P384(t *testing.T) { - exDNSKEY := `example.net. 3600 IN DNSKEY 257 3 14 ( - xKYaNhWdGOfJ+nPrL8/arkwf2EY3MDJ+SErKivBVSum1 - w/egsXvSADtNJhyem5RCOpgQ6K8X1DRSEkrbYQ+OB+v8 - /uX45NBwY8rp65F6Glur8I/mlVNgF6W/qTI37m40 )` - exPriv := `Private-key-format: v1.2 -Algorithm: 14 (ECDSAP384SHA384) -PrivateKey: WURgWHCcYIYUPWgeLmiPY2DJJk02vgrmTfitxgqcL4vwW7BOrbawVmVe0d9V94SR` - rrDNSKEY, err := NewRR(exDNSKEY) - if err != nil { - t.Fatal(err.Error()) - } - priv, err := rrDNSKEY.(*DNSKEY).NewPrivateKey(exPriv) - if err != nil { - t.Fatal(err.Error()) - } - - exDS := `example.net. 3600 IN DS 10771 14 4 ( - 72d7b62976ce06438e9c0bf319013cf801f09ecc84b8 - d7e9495f27e305c6a9b0563a9b5f4d288405c3008a94 - 6df983d6 )` - rrDS, err := NewRR(exDS) - if err != nil { - t.Fatal(err.Error()) - } - ourDS := rrDNSKEY.(*DNSKEY).ToDS(SHA384) - if !reflect.DeepEqual(ourDS, rrDS.(*DS)) { - t.Fatalf("DS record differs:\n%v\n%v\n", ourDS, rrDS.(*DS)) - } - - exA := `www.example.net. 3600 IN A 192.0.2.1` - exRRSIG := `www.example.net. 3600 IN RRSIG A 14 3 3600 ( - 20100909102025 20100812102025 10771 example.net. - /L5hDKIvGDyI1fcARX3z65qrmPsVz73QD1Mr5CEqOiLP - 95hxQouuroGCeZOvzFaxsT8Glr74hbavRKayJNuydCuz - WTSSPdz7wnqXL5bdcJzusdnI0RSMROxxwGipWcJm )` - rrA, err := NewRR(exA) - if err != nil { - t.Fatal(err.Error()) - } - rrRRSIG, err := NewRR(exRRSIG) - if err != nil { - t.Fatal(err.Error()) - } - if err = rrRRSIG.(*RRSIG).Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil { - t.Errorf("Failure to validate the spec RRSIG: %v", err) - } - - ourRRSIG := &RRSIG{ - Hdr: RR_Header{ - Ttl: rrA.Header().Ttl, - }, - KeyTag: rrDNSKEY.(*DNSKEY).KeyTag(), - SignerName: rrDNSKEY.(*DNSKEY).Hdr.Name, - Algorithm: rrDNSKEY.(*DNSKEY).Algorithm, - } - ourRRSIG.Expiration, _ = StringToTime("20100909102025") - ourRRSIG.Inception, _ = StringToTime("20100812102025") - err = ourRRSIG.Sign(priv, []RR{rrA}) - if err != nil { - t.Fatal(err.Error()) - } - - if err = ourRRSIG.Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil { - t.Errorf("Failure to validate our RRSIG: %v", err) - } - - // Signatures are randomized - rrRRSIG.(*RRSIG).Signature = "" - ourRRSIG.Signature = "" - if !reflect.DeepEqual(ourRRSIG, rrRRSIG.(*RRSIG)) { - t.Fatalf("RRSIG record differs:\n%v\n%v\n", ourRRSIG, rrRRSIG.(*RRSIG)) - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go deleted file mode 100644 index 09986a5e4ef..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go +++ /dev/null @@ -1,3 +0,0 @@ -package dns - -// Find better solution diff --git a/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go b/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go deleted file mode 100644 index 8ee82ab4264..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package dns - -import "testing" - -func TestOPTTtl(t *testing.T) { - e := &OPT{} - e.Hdr.Name = "." - e.Hdr.Rrtype = TypeOPT - - if e.Do() { - t.Fail() - } - - e.SetDo() - if !e.Do() { - t.Fail() - } - - oldTtl := e.Hdr.Ttl - - if e.Version() != 0 { - t.Fail() - } - - e.SetVersion(42) - if e.Version() != 42 { - t.Fail() - } - - e.SetVersion(0) - if e.Hdr.Ttl != oldTtl { - t.Fail() - } - - if e.ExtendedRcode() != 0 { - t.Fail() - } - - e.SetExtendedRcode(42) - if e.ExtendedRcode() != 42 { - t.Fail() - } - - e.SetExtendedRcode(0) - if e.Hdr.Ttl != oldTtl { - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/example_test.go b/Godeps/_workspace/src/github.com/miekg/dns/example_test.go deleted file mode 100644 index 1578a4d0539..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/example_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package dns_test - -import ( - "errors" - "fmt" - "github.com/miekg/dns" - "log" - "net" -) - -// Retrieve the MX records for miek.nl. -func ExampleMX() { - config, _ := dns.ClientConfigFromFile("/etc/resolv.conf") - c := new(dns.Client) - m := new(dns.Msg) - m.SetQuestion("miek.nl.", dns.TypeMX) - m.RecursionDesired = true - r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port) - if err != nil { - return - } - if r.Rcode != dns.RcodeSuccess { - return - } - for _, a := range r.Answer { - if mx, ok := a.(*dns.MX); ok { - fmt.Printf("%s\n", mx.String()) - } - } -} - -// Retrieve the DNSKEY records of a zone and convert them -// to DS records for SHA1, SHA256 and SHA384. -func ExampleDS(zone string) { - config, _ := dns.ClientConfigFromFile("/etc/resolv.conf") - c := new(dns.Client) - m := new(dns.Msg) - if zone == "" { - zone = "miek.nl" - } - m.SetQuestion(dns.Fqdn(zone), dns.TypeDNSKEY) - m.SetEdns0(4096, true) - r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port) - if err != nil { - return - } - if r.Rcode != dns.RcodeSuccess { - return - } - for _, k := range r.Answer { - if key, ok := k.(*dns.DNSKEY); ok { - for _, alg := range []uint8{dns.SHA1, dns.SHA256, dns.SHA384} { - fmt.Printf("%s; %d\n", key.ToDS(alg).String(), key.Flags) - } - } - } -} - -const TypeAPAIR = 0x0F99 - -type APAIR struct { - addr [2]net.IP -} - -func NewAPAIR() dns.PrivateRdata { return new(APAIR) } - -func (rd *APAIR) String() string { return rd.addr[0].String() + " " + rd.addr[1].String() } -func (rd *APAIR) Parse(txt []string) error { - if len(txt) != 2 { - return errors.New("two addresses required for APAIR") - } - for i, s := range txt { - ip := net.ParseIP(s) - if ip == nil { - return errors.New("invalid IP in APAIR text representation") - } - rd.addr[i] = ip - } - return nil -} - -func (rd *APAIR) Pack(buf []byte) (int, error) { - b := append([]byte(rd.addr[0]), []byte(rd.addr[1])...) - n := copy(buf, b) - if n != len(b) { - return n, dns.ErrBuf - } - return n, nil -} - -func (rd *APAIR) Unpack(buf []byte) (int, error) { - ln := net.IPv4len * 2 - if len(buf) != ln { - return 0, errors.New("invalid length of APAIR rdata") - } - cp := make([]byte, ln) - copy(cp, buf) // clone bytes to use them in IPs - - rd.addr[0] = net.IP(cp[:3]) - rd.addr[1] = net.IP(cp[4:]) - - return len(buf), nil -} - -func (rd *APAIR) Copy(dest dns.PrivateRdata) error { - cp := make([]byte, rd.Len()) - _, err := rd.Pack(cp) - if err != nil { - return err - } - - d := dest.(*APAIR) - d.addr[0] = net.IP(cp[:3]) - d.addr[1] = net.IP(cp[4:]) - return nil -} - -func (rd *APAIR) Len() int { - return net.IPv4len * 2 -} - -func ExamplePrivateHandle() { - dns.PrivateHandle("APAIR", TypeAPAIR, NewAPAIR) - defer dns.PrivateHandleRemove(TypeAPAIR) - - rr, err := dns.NewRR("miek.nl. APAIR (1.2.3.4 1.2.3.5)") - if err != nil { - log.Fatal("could not parse APAIR record: ", err) - } - fmt.Println(rr) - // Output: miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5 - - m := new(dns.Msg) - m.Id = 12345 - m.SetQuestion("miek.nl.", TypeAPAIR) - m.Answer = append(m.Answer, rr) - - fmt.Println(m) - // ;; opcode: QUERY, status: NOERROR, id: 12345 - // ;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 - // - // ;; QUESTION SECTION: - // ;miek.nl. IN APAIR - // - // ;; ANSWER SECTION: - // miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5 -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/idn/example_test.go b/Godeps/_workspace/src/github.com/miekg/dns/idn/example_test.go deleted file mode 100644 index 8833cd91de1..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/idn/example_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package idn_test - -import ( - "fmt" - "github.com/miekg/dns/idn" -) - -func ExampleToPunycode() { - name := "インターネット.テスト" - fmt.Printf("%s -> %s", name, idn.ToPunycode(name)) - // Output: インターネット.テスト -> xn--eckucmux0ukc.xn--zckzah -} - -func ExampleFromPunycode() { - name := "xn--mgbaja8a1hpac.xn--mgbachtv" - fmt.Printf("%s -> %s", name, idn.FromPunycode(name)) - // Output: xn--mgbaja8a1hpac.xn--mgbachtv -> الانترنت.اختبار -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/idn/punycode_test.go b/Godeps/_workspace/src/github.com/miekg/dns/idn/punycode_test.go deleted file mode 100644 index 3202450aa52..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/idn/punycode_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package idn - -import ( - "strings" - "testing" -) - -var testcases = [][2]string{ - {"", ""}, - {"a", "a"}, - {"A-B", "a-b"}, - {"AbC", "abc"}, - {"я", "xn--41a"}, - {"zя", "xn--z-0ub"}, - {"ЯZ", "xn--z-zub"}, - {"إختبار", "xn--kgbechtv"}, - {"آزمایشی", "xn--hgbk6aj7f53bba"}, - {"测试", "xn--0zwm56d"}, - {"測試", "xn--g6w251d"}, - {"Испытание", "xn--80akhbyknj4f"}, - {"परीक्षा", "xn--11b5bs3a9aj6g"}, - {"δοκιμή", "xn--jxalpdlp"}, - {"테스트", "xn--9t4b11yi5a"}, - {"טעסט", "xn--deba0ad"}, - {"テスト", "xn--zckzah"}, - {"பரிட்சை", "xn--hlcj6aya9esc7a"}, -} - -func TestEncodeDecodePunycode(t *testing.T) { - for _, tst := range testcases { - enc := encode([]byte(tst[0])) - if string(enc) != tst[1] { - t.Errorf("%s encodeded as %s but should be %s", tst[0], enc, tst[1]) - } - dec := decode([]byte(tst[1])) - if string(dec) != strings.ToLower(tst[0]) { - t.Errorf("%s decoded as %s but should be %s", tst[1], dec, strings.ToLower(tst[0])) - } - } -} - -func TestToFromPunycode(t *testing.T) { - for _, tst := range testcases { - // assert unicode.com == punycode.com - full := ToPunycode(tst[0] + ".com") - if full != tst[1]+".com" { - t.Errorf("invalid result from string conversion to punycode, %s and should be %s.com", full, tst[1]) - } - // assert punycode.punycode == unicode.unicode - decoded := FromPunycode(tst[1] + "." + tst[1]) - if decoded != strings.ToLower(tst[0]+"."+tst[0]) { - t.Errorf("invalid result from string conversion to punycode, %s and should be %s.%s", decoded, tst[0], tst[0]) - } - } -} - -func TestEncodeDecodeFinalPeriod(t *testing.T) { - for _, tst := range testcases { - // assert unicode.com. == punycode.com. - full := ToPunycode(tst[0] + ".") - if full != tst[1]+"." { - t.Errorf("invalid result from string conversion to punycode when period added at the end, %#v and should be %#v", full, tst[1]+".") - } - // assert punycode.com. == unicode.com. - decoded := FromPunycode(tst[1] + ".") - if decoded != strings.ToLower(tst[0]+".") { - t.Errorf("invalid result from string conversion to punycode when period added, %#v and should be %#v", decoded, tst[0]+".") - } - full = ToPunycode(tst[0]) - if full != tst[1] { - t.Errorf("invalid result from string conversion to punycode when no period added at the end, %#v and should be %#v", full, tst[1]+".") - } - // assert punycode.com. == unicode.com. - decoded = FromPunycode(tst[1]) - if decoded != strings.ToLower(tst[0]) { - t.Errorf("invalid result from string conversion to punycode when no period added, %#v and should be %#v", decoded, tst[0]+".") - } - } -} - -var invalid = []string{ - "xn--*", - "xn--", - "xn---", -} - -func TestInvalidPunycode(t *testing.T) { - for _, d := range invalid { - s := FromPunycode(d) - if s != d { - t.Errorf("Changed invalid name %s to %#v", d, s) - } - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/labels_test.go b/Godeps/_workspace/src/github.com/miekg/dns/labels_test.go deleted file mode 100644 index 1d8da155fd5..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/labels_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package dns - -import ( - "testing" -) - -func TestCompareDomainName(t *testing.T) { - s1 := "www.miek.nl." - s2 := "miek.nl." - s3 := "www.bla.nl." - s4 := "nl.www.bla." - s5 := "nl" - s6 := "miek.nl" - - if CompareDomainName(s1, s2) != 2 { - t.Logf("%s with %s should be %d", s1, s2, 2) - t.Fail() - } - if CompareDomainName(s1, s3) != 1 { - t.Logf("%s with %s should be %d", s1, s3, 1) - t.Fail() - } - if CompareDomainName(s3, s4) != 0 { - t.Logf("%s with %s should be %d", s3, s4, 0) - t.Fail() - } - // Non qualified tests - if CompareDomainName(s1, s5) != 1 { - t.Logf("%s with %s should be %d", s1, s5, 1) - t.Fail() - } - if CompareDomainName(s1, s6) != 2 { - t.Logf("%s with %s should be %d", s1, s5, 2) - t.Fail() - } - - if CompareDomainName(s1, ".") != 0 { - t.Logf("%s with %s should be %d", s1, s5, 0) - t.Fail() - } - if CompareDomainName(".", ".") != 0 { - t.Logf("%s with %s should be %d", ".", ".", 0) - t.Fail() - } -} - -func TestSplit(t *testing.T) { - splitter := map[string]int{ - "www.miek.nl.": 3, - "www.miek.nl": 3, - "www..miek.nl": 4, - `www\.miek.nl.`: 2, - `www\\.miek.nl.`: 3, - ".": 0, - "nl.": 1, - "nl": 1, - "com.": 1, - ".com.": 2, - } - for s, i := range splitter { - if x := len(Split(s)); x != i { - t.Logf("labels should be %d, got %d: %s %v\n", i, x, s, Split(s)) - t.Fail() - } else { - t.Logf("%s %v\n", s, Split(s)) - } - } -} - -func TestSplit2(t *testing.T) { - splitter := map[string][]int{ - "www.miek.nl.": []int{0, 4, 9}, - "www.miek.nl": []int{0, 4, 9}, - "nl": []int{0}, - } - for s, i := range splitter { - x := Split(s) - switch len(i) { - case 1: - if x[0] != i[0] { - t.Logf("labels should be %v, got %v: %s\n", i, x, s) - t.Fail() - } - default: - if x[0] != i[0] || x[1] != i[1] || x[2] != i[2] { - t.Logf("labels should be %v, got %v: %s\n", i, x, s) - t.Fail() - } - } - } -} - -func TestPrevLabel(t *testing.T) { - type prev struct { - string - int - } - prever := map[prev]int{ - prev{"www.miek.nl.", 0}: 12, - prev{"www.miek.nl.", 1}: 9, - prev{"www.miek.nl.", 2}: 4, - - prev{"www.miek.nl", 0}: 11, - prev{"www.miek.nl", 1}: 9, - prev{"www.miek.nl", 2}: 4, - - prev{"www.miek.nl.", 5}: 0, - prev{"www.miek.nl", 5}: 0, - - prev{"www.miek.nl.", 3}: 0, - prev{"www.miek.nl", 3}: 0, - } - for s, i := range prever { - x, ok := PrevLabel(s.string, s.int) - if i != x { - t.Logf("label should be %d, got %d, %t: preving %d, %s\n", i, x, ok, s.int, s.string) - t.Fail() - } - } -} - -func TestCountLabel(t *testing.T) { - splitter := map[string]int{ - "www.miek.nl.": 3, - "www.miek.nl": 3, - "nl": 1, - ".": 0, - } - for s, i := range splitter { - x := CountLabel(s) - if x != i { - t.Logf("CountLabel should have %d, got %d\n", i, x) - t.Fail() - } - } -} - -func TestSplitDomainName(t *testing.T) { - labels := map[string][]string{ - "miek.nl": []string{"miek", "nl"}, - ".": nil, - "www.miek.nl.": []string{"www", "miek", "nl"}, - "www.miek.nl": []string{"www", "miek", "nl"}, - "www..miek.nl": []string{"www", "", "miek", "nl"}, - `www\.miek.nl`: []string{`www\.miek`, "nl"}, - `www\\.miek.nl`: []string{`www\\`, "miek", "nl"}, - } -domainLoop: - for domain, splits := range labels { - parts := SplitDomainName(domain) - if len(parts) != len(splits) { - t.Logf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits) - t.Fail() - continue domainLoop - } - for i := range parts { - if parts[i] != splits[i] { - t.Logf("SplitDomainName returned %v for %s, expected %v", parts, domain, splits) - t.Fail() - continue domainLoop - } - } - } -} - -func TestIsDomainName(t *testing.T) { - type ret struct { - ok bool - lab int - } - names := map[string]*ret{ - "..": &ret{false, 1}, - "@.": &ret{true, 1}, - "www.example.com": &ret{true, 3}, - "www.e%ample.com": &ret{true, 3}, - "www.example.com.": &ret{true, 3}, - "mi\\k.nl.": &ret{true, 2}, - "mi\\k.nl": &ret{true, 2}, - } - for d, ok := range names { - l, k := IsDomainName(d) - if ok.ok != k || ok.lab != l { - t.Logf(" got %v %d for %s ", k, l, d) - t.Logf("have %v %d for %s ", ok.ok, ok.lab, d) - t.Fail() - } - } -} - -func BenchmarkSplitLabels(b *testing.B) { - for i := 0; i < b.N; i++ { - Split("www.example.com") - } -} - -func BenchmarkLenLabels(b *testing.B) { - for i := 0; i < b.N; i++ { - CountLabel("www.example.com") - } -} - -func BenchmarkCompareLabels(b *testing.B) { - for i := 0; i < b.N; i++ { - CompareDomainName("www.example.com", "aa.example.com") - } -} - -func BenchmarkIsSubDomain(b *testing.B) { - for i := 0; i < b.N; i++ { - IsSubDomain("www.example.com", "aa.example.com") - IsSubDomain("example.com", "aa.example.com") - IsSubDomain("miek.nl", "aa.example.com") - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/nsecx_test.go b/Godeps/_workspace/src/github.com/miekg/dns/nsecx_test.go deleted file mode 100644 index 72f641a6673..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/nsecx_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package dns - -import ( - "testing" -) - -func TestPackNsec3(t *testing.T) { - nsec3 := HashName("dnsex.nl.", SHA1, 0, "DEAD") - if nsec3 != "ROCCJAE8BJJU7HN6T7NG3TNM8ACRS87J" { - t.Logf("%v\n", nsec3) - t.Fail() - } - - nsec3 = HashName("a.b.c.example.org.", SHA1, 2, "DEAD") - if nsec3 != "6LQ07OAHBTOOEU2R9ANI2AT70K5O0RCG" { - t.Logf("%v\n", nsec3) - t.Fail() - } -} - -func TestNsec3(t *testing.T) { - // examples taken from .nl - nsec3, _ := NewRR("39p91242oslggest5e6a7cci4iaeqvnk.nl. IN NSEC3 1 1 5 F10E9F7EA83FC8F3 39P99DCGG0MDLARTCRMCF6OFLLUL7PR6 NS DS RRSIG") - if !nsec3.(*NSEC3).Cover("snasajsksasasa.nl.") { // 39p94jrinub66hnpem8qdpstrec86pg3 - t.Logf("39p94jrinub66hnpem8qdpstrec86pg3. should be covered by 39p91242oslggest5e6a7cci4iaeqvnk.nl. - 39P99DCGG0MDLARTCRMCF6OFLLUL7PR6") - t.Fail() - } - nsec3, _ = NewRR("sk4e8fj94u78smusb40o1n0oltbblu2r.nl. IN NSEC3 1 1 5 F10E9F7EA83FC8F3 SK4F38CQ0ATIEI8MH3RGD0P5I4II6QAN NS SOA TXT RRSIG DNSKEY NSEC3PARAM") - if !nsec3.(*NSEC3).Match("nl.") { // sk4e8fj94u78smusb40o1n0oltbblu2r.nl. - t.Logf("sk4e8fj94u78smusb40o1n0oltbblu2r.nl. should match sk4e8fj94u78smusb40o1n0oltbblu2r.nl.") - t.Fail() - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/parse_test.go b/Godeps/_workspace/src/github.com/miekg/dns/parse_test.go deleted file mode 100644 index dd2799d1f14..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/parse_test.go +++ /dev/null @@ -1,1276 +0,0 @@ -package dns - -import ( - "bytes" - "crypto/rsa" - "encoding/hex" - "fmt" - "math/rand" - "net" - "reflect" - "strconv" - "strings" - "testing" - "testing/quick" - "time" -) - -func TestDotInName(t *testing.T) { - buf := make([]byte, 20) - PackDomainName("aa\\.bb.nl.", buf, 0, nil, false) - // index 3 must be a real dot - if buf[3] != '.' { - t.Log("dot should be a real dot") - t.Fail() - } - - if buf[6] != 2 { - t.Log("this must have the value 2") - t.Fail() - } - dom, _, _ := UnpackDomainName(buf, 0) - // printing it should yield the backspace again - if dom != "aa\\.bb.nl." { - t.Log("dot should have been escaped: " + dom) - t.Fail() - } -} - -func TestDotLastInLabel(t *testing.T) { - sample := "aa\\..au." - buf := make([]byte, 20) - _, err := PackDomainName(sample, buf, 0, nil, false) - if err != nil { - t.Fatalf("unexpected error packing domain: %s", err) - } - dom, _, _ := UnpackDomainName(buf, 0) - if dom != sample { - t.Fatalf("unpacked domain `%s' doesn't match packed domain", dom) - } -} - -func TestTooLongDomainName(t *testing.T) { - l := "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt." - dom := l + l + l + l + l + l + l - _, e := NewRR(dom + " IN A 127.0.0.1") - if e == nil { - t.Log("should be too long") - t.Fail() - } else { - t.Logf("error is %s", e.Error()) - } - _, e = NewRR("..com. IN A 127.0.0.1") - if e == nil { - t.Log("should fail") - t.Fail() - } else { - t.Logf("error is %s", e.Error()) - } -} - -func TestDomainName(t *testing.T) { - tests := []string{"r\\.gieben.miek.nl.", "www\\.www.miek.nl.", - "www.*.miek.nl.", "www.*.miek.nl.", - } - dbuff := make([]byte, 40) - - for _, ts := range tests { - if _, err := PackDomainName(ts, dbuff, 0, nil, false); err != nil { - t.Log("not a valid domain name") - t.Fail() - continue - } - n, _, err := UnpackDomainName(dbuff, 0) - if err != nil { - t.Log("failed to unpack packed domain name") - t.Fail() - continue - } - if ts != n { - t.Logf("must be equal: in: %s, out: %s\n", ts, n) - t.Fail() - } - } -} - -func TestDomainNameAndTXTEscapes(t *testing.T) { - tests := []byte{'.', '(', ')', ';', ' ', '@', '"', '\\', '\t', '\r', '\n', 0, 255} - for _, b := range tests { - rrbytes := []byte{ - 1, b, 0, // owner - byte(TypeTXT >> 8), byte(TypeTXT), - byte(ClassINET >> 8), byte(ClassINET), - 0, 0, 0, 1, // TTL - 0, 2, 1, b, // Data - } - rr1, _, err := UnpackRR(rrbytes, 0) - if err != nil { - panic(err) - } - s := rr1.String() - rr2, err := NewRR(s) - if err != nil { - t.Logf("Error parsing unpacked RR's string: %v", err) - t.Logf(" Bytes: %v\n", rrbytes) - t.Logf("String: %v\n", s) - t.Fail() - } - repacked := make([]byte, len(rrbytes)) - if _, err := PackRR(rr2, repacked, 0, nil, false); err != nil { - t.Logf("error packing parsed RR: %v", err) - t.Logf(" original Bytes: %v\n", rrbytes) - t.Logf("unpacked Struct: %V\n", rr1) - t.Logf(" parsed Struct: %V\n", rr2) - t.Fail() - } - if !bytes.Equal(repacked, rrbytes) { - t.Log("packed bytes don't match original bytes") - t.Logf(" original bytes: %v", rrbytes) - t.Logf(" packed bytes: %v", repacked) - t.Logf("unpacked struct: %V", rr1) - t.Logf(" parsed struct: %V", rr2) - t.Fail() - } - } -} - -func TestTXTEscapeParsing(t *testing.T) { - test := [][]string{ - {`";"`, `";"`}, - {`\;`, `";"`}, - {`"\t"`, `"\t"`}, - {`"\r"`, `"\r"`}, - {`"\ "`, `" "`}, - {`"\;"`, `";"`}, - {`"\;\""`, `";\""`}, - {`"\(a\)"`, `"(a)"`}, - {`"\(a)"`, `"(a)"`}, - {`"(a\)"`, `"(a)"`}, - {`"(a)"`, `"(a)"`}, - {`"\048"`, `"0"`}, - {`"\` + "\n" + `"`, `"\n"`}, - {`"\` + "\r" + `"`, `"\r"`}, - {`"\` + "\x11" + `"`, `"\017"`}, - {`"\'"`, `"'"`}, - } - for _, s := range test { - rr, err := NewRR(fmt.Sprintf("example.com. IN TXT %v", s[0])) - if err != nil { - t.Errorf("Could not parse %v TXT: %s", s[0], err) - continue - } - - txt := sprintTxt(rr.(*TXT).Txt) - if txt != s[1] { - t.Errorf("Mismatch after parsing `%v` TXT record: `%v` != `%v`", s[0], txt, s[1]) - } - } -} - -func GenerateDomain(r *rand.Rand, size int) []byte { - dnLen := size % 70 // artificially limit size so there's less to intrepret if a failure occurs - var dn []byte - done := false - for i := 0; i < dnLen && !done; { - max := dnLen - i - if max > 63 { - max = 63 - } - lLen := max - if lLen != 0 { - lLen = int(r.Int31()) % max - } - done = lLen == 0 - if done { - continue - } - l := make([]byte, lLen+1) - l[0] = byte(lLen) - for j := 0; j < lLen; j++ { - l[j+1] = byte(rand.Int31()) - } - dn = append(dn, l...) - i += 1 + lLen - } - return append(dn, 0) -} - -func TestDomainQuick(t *testing.T) { - r := rand.New(rand.NewSource(0)) - f := func(l int) bool { - db := GenerateDomain(r, l) - ds, _, err := UnpackDomainName(db, 0) - if err != nil { - panic(err) - } - buf := make([]byte, 255) - off, err := PackDomainName(ds, buf, 0, nil, false) - if err != nil { - t.Logf("error packing domain: %s", err.Error()) - t.Logf(" bytes: %v\n", db) - t.Logf("string: %v\n", ds) - return false - } - if !bytes.Equal(db, buf[:off]) { - t.Logf("repacked domain doesn't match original:") - t.Logf("src bytes: %v", db) - t.Logf(" string: %v", ds) - t.Logf("out bytes: %v", buf[:off]) - return false - } - return true - } - if err := quick.Check(f, nil); err != nil { - t.Error(err) - } -} - -func GenerateTXT(r *rand.Rand, size int) []byte { - rdLen := size % 300 // artificially limit size so there's less to intrepret if a failure occurs - var rd []byte - for i := 0; i < rdLen; { - max := rdLen - 1 - if max > 255 { - max = 255 - } - sLen := max - if max != 0 { - sLen = int(r.Int31()) % max - } - s := make([]byte, sLen+1) - s[0] = byte(sLen) - for j := 0; j < sLen; j++ { - s[j+1] = byte(rand.Int31()) - } - rd = append(rd, s...) - i += 1 + sLen - } - return rd -} - -func TestTXTRRQuick(t *testing.T) { - s := rand.NewSource(0) - r := rand.New(s) - typeAndClass := []byte{ - byte(TypeTXT >> 8), byte(TypeTXT), - byte(ClassINET >> 8), byte(ClassINET), - 0, 0, 0, 1, // TTL - } - f := func(l int) bool { - owner := GenerateDomain(r, l) - rdata := GenerateTXT(r, l) - rrbytes := make([]byte, 0, len(owner)+2+2+4+2+len(rdata)) - rrbytes = append(rrbytes, owner...) - rrbytes = append(rrbytes, typeAndClass...) - rrbytes = append(rrbytes, byte(len(rdata)>>8)) - rrbytes = append(rrbytes, byte(len(rdata))) - rrbytes = append(rrbytes, rdata...) - rr, _, err := UnpackRR(rrbytes, 0) - if err != nil { - panic(err) - } - buf := make([]byte, len(rrbytes)*3) - off, err := PackRR(rr, buf, 0, nil, false) - if err != nil { - t.Logf("pack Error: %s\nRR: %V", err.Error(), rr) - return false - } - buf = buf[:off] - if !bytes.Equal(buf, rrbytes) { - t.Logf("packed bytes don't match original bytes") - t.Logf("src bytes: %v", rrbytes) - t.Logf(" struct: %V", rr) - t.Logf("oUt bytes: %v", buf) - return false - } - if len(rdata) == 0 { - // string'ing won't produce any data to parse - return true - } - rrString := rr.String() - rr2, err := NewRR(rrString) - if err != nil { - t.Logf("error parsing own output: %s", err.Error()) - t.Logf("struct: %V", rr) - t.Logf("string: %v", rrString) - return false - } - if rr2.String() != rrString { - t.Logf("parsed rr.String() doesn't match original string") - t.Logf("original: %v", rrString) - t.Logf(" parsed: %v", rr2.String()) - return false - } - - buf = make([]byte, len(rrbytes)*3) - off, err = PackRR(rr2, buf, 0, nil, false) - if err != nil { - t.Logf("error packing parsed rr: %s", err.Error()) - t.Logf("unpacked Struct: %V", rr) - t.Logf(" string: %v", rrString) - t.Logf(" parsed Struct: %V", rr2) - return false - } - buf = buf[:off] - if !bytes.Equal(buf, rrbytes) { - t.Logf("parsed packed bytes don't match original bytes") - t.Logf(" source bytes: %v", rrbytes) - t.Logf("unpacked struct: %V", rr) - t.Logf(" string: %v", rrString) - t.Logf(" parsed struct: %V", rr2) - t.Logf(" repacked bytes: %v", buf) - return false - } - return true - } - c := &quick.Config{MaxCountScale: 10} - if err := quick.Check(f, c); err != nil { - t.Error(err) - } -} - -func TestParseDirectiveMisc(t *testing.T) { - tests := map[string]string{ - "$ORIGIN miek.nl.\na IN NS b": "a.miek.nl.\t3600\tIN\tNS\tb.miek.nl.", - "$TTL 2H\nmiek.nl. IN NS b.": "miek.nl.\t7200\tIN\tNS\tb.", - "miek.nl. 1D IN NS b.": "miek.nl.\t86400\tIN\tNS\tb.", - `name. IN SOA a6.nstld.com. hostmaster.nic.name. ( - 203362132 ; serial - 5m ; refresh (5 minutes) - 5m ; retry (5 minutes) - 2w ; expire (2 weeks) - 300 ; minimum (5 minutes) -)`: "name.\t3600\tIN\tSOA\ta6.nstld.com. hostmaster.nic.name. 203362132 300 300 1209600 300", - ". 3600000 IN NS ONE.MY-ROOTS.NET.": ".\t3600000\tIN\tNS\tONE.MY-ROOTS.NET.", - "ONE.MY-ROOTS.NET. 3600000 IN A 192.168.1.1": "ONE.MY-ROOTS.NET.\t3600000\tIN\tA\t192.168.1.1", - } - for i, o := range tests { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestNSEC(t *testing.T) { - nsectests := map[string]string{ - "nl. IN NSEC3PARAM 1 0 5 30923C44C6CBBB8F": "nl.\t3600\tIN\tNSEC3PARAM\t1 0 5 30923C44C6CBBB8F", - "p2209hipbpnm681knjnu0m1febshlv4e.nl. IN NSEC3 1 1 5 30923C44C6CBBB8F P90DG1KE8QEAN0B01613LHQDG0SOJ0TA NS SOA TXT RRSIG DNSKEY NSEC3PARAM": "p2209hipbpnm681knjnu0m1febshlv4e.nl.\t3600\tIN\tNSEC3\t1 1 5 30923C44C6CBBB8F P90DG1KE8QEAN0B01613LHQDG0SOJ0TA NS SOA TXT RRSIG DNSKEY NSEC3PARAM", - "localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSEC": "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC", - "localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSEC TYPE65534": "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC TYPE65534", - "localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSec Type65534": "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC TYPE65534", - } - for i, o := range nsectests { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestParseLOC(t *testing.T) { - lt := map[string]string{ - "SW1A2AA.find.me.uk. LOC 51 30 12.748 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 30 12.748 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m", - "SW1A2AA.find.me.uk. LOC 51 0 0.0 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 00 0.000 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m", - } - for i, o := range lt { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestParseDS(t *testing.T) { - dt := map[string]string{ - "example.net. 3600 IN DS 40692 12 3 22261A8B0E0D799183E35E24E2AD6BB58533CBA7E3B14D659E9CA09B 2071398F": "example.net.\t3600\tIN\tDS\t40692 12 3 22261A8B0E0D799183E35E24E2AD6BB58533CBA7E3B14D659E9CA09B2071398F", - } - for i, o := range dt { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestQuotes(t *testing.T) { - tests := map[string]string{ - `t.example.com. IN TXT "a bc"`: "t.example.com.\t3600\tIN\tTXT\t\"a bc\"", - `t.example.com. IN TXT "a - bc"`: "t.example.com.\t3600\tIN\tTXT\t\"a\\n bc\"", - `t.example.com. IN TXT ""`: "t.example.com.\t3600\tIN\tTXT\t\"\"", - `t.example.com. IN TXT "a"`: "t.example.com.\t3600\tIN\tTXT\t\"a\"", - `t.example.com. IN TXT "aa"`: "t.example.com.\t3600\tIN\tTXT\t\"aa\"", - `t.example.com. IN TXT "aaa" ;`: "t.example.com.\t3600\tIN\tTXT\t\"aaa\"", - `t.example.com. IN TXT "abc" "DEF"`: "t.example.com.\t3600\tIN\tTXT\t\"abc\" \"DEF\"", - `t.example.com. IN TXT "abc" ( "DEF" )`: "t.example.com.\t3600\tIN\tTXT\t\"abc\" \"DEF\"", - `t.example.com. IN TXT aaa ;`: "t.example.com.\t3600\tIN\tTXT\t\"aaa \"", - `t.example.com. IN TXT aaa aaa;`: "t.example.com.\t3600\tIN\tTXT\t\"aaa aaa\"", - `t.example.com. IN TXT aaa aaa`: "t.example.com.\t3600\tIN\tTXT\t\"aaa aaa\"", - `t.example.com. IN TXT aaa`: "t.example.com.\t3600\tIN\tTXT\t\"aaa\"", - "cid.urn.arpa. NAPTR 100 50 \"s\" \"z3950+I2L+I2C\" \"\" _z3950._tcp.gatech.edu.": "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"z3950+I2L+I2C\" \"\" _z3950._tcp.gatech.edu.", - "cid.urn.arpa. NAPTR 100 50 \"s\" \"rcds+I2C\" \"\" _rcds._udp.gatech.edu.": "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"rcds+I2C\" \"\" _rcds._udp.gatech.edu.", - "cid.urn.arpa. NAPTR 100 50 \"s\" \"http+I2L+I2C+I2R\" \"\" _http._tcp.gatech.edu.": "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"http+I2L+I2C+I2R\" \"\" _http._tcp.gatech.edu.", - "cid.urn.arpa. NAPTR 100 10 \"\" \"\" \"/urn:cid:.+@([^\\.]+\\.)(.*)$/\\2/i\" .": "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 10 \"\" \"\" \"/urn:cid:.+@([^\\.]+\\.)(.*)$/\\2/i\" .", - } - for i, o := range tests { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is\n`%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestParseClass(t *testing.T) { - tests := map[string]string{ - "t.example.com. IN A 127.0.0.1": "t.example.com. 3600 IN A 127.0.0.1", - "t.example.com. CS A 127.0.0.1": "t.example.com. 3600 CS A 127.0.0.1", - "t.example.com. CH A 127.0.0.1": "t.example.com. 3600 CH A 127.0.0.1", - // ClassANY can not occur in zone files - // "t.example.com. ANY A 127.0.0.1": "t.example.com. 3600 ANY A 127.0.0.1", - "t.example.com. NONE A 127.0.0.1": "t.example.com. 3600 NONE A 127.0.0.1", - } - for i, o := range tests { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is\n`%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestBrace(t *testing.T) { - tests := map[string]string{ - "(miek.nl.) 3600 IN A 127.0.1.1": "miek.nl.\t3600\tIN\tA\t127.0.1.1", - "miek.nl. (3600) IN MX (10) elektron.atoom.net.": "miek.nl.\t3600\tIN\tMX\t10 elektron.atoom.net.", - `miek.nl. IN ( - 3600 A 127.0.0.1)`: "miek.nl.\t3600\tIN\tA\t127.0.0.1", - "(miek.nl.) (A) (127.0.2.1)": "miek.nl.\t3600\tIN\tA\t127.0.2.1", - "miek.nl A 127.0.3.1": "miek.nl.\t3600\tIN\tA\t127.0.3.1", - "_ssh._tcp.local. 60 IN (PTR) stora._ssh._tcp.local.": "_ssh._tcp.local.\t60\tIN\tPTR\tstora._ssh._tcp.local.", - "miek.nl. NS ns.miek.nl": "miek.nl.\t3600\tIN\tNS\tns.miek.nl.", - `(miek.nl.) ( - (IN) - (AAAA) - (::1) )`: "miek.nl.\t3600\tIN\tAAAA\t::1", - `(miek.nl.) ( - (IN) - (AAAA) - (::1))`: "miek.nl.\t3600\tIN\tAAAA\t::1", - "miek.nl. IN AAAA ::2": "miek.nl.\t3600\tIN\tAAAA\t::2", - `((m)(i)ek.(n)l.) (SOA) (soa.) (soa.) ( - 2009032802 ; serial - 21600 ; refresh (6 hours) - 7(2)00 ; retry (2 hours) - 604()800 ; expire (1 week) - 3600 ; minimum (1 hour) - )`: "miek.nl.\t3600\tIN\tSOA\tsoa. soa. 2009032802 21600 7200 604800 3600", - "miek\\.nl. IN A 127.0.0.10": "miek\\.nl.\t3600\tIN\tA\t127.0.0.10", - "miek.nl. IN A 127.0.0.11": "miek.nl.\t3600\tIN\tA\t127.0.0.11", - "miek.nl. A 127.0.0.12": "miek.nl.\t3600\tIN\tA\t127.0.0.12", - `miek.nl. 86400 IN SOA elektron.atoom.net. miekg.atoom.net. ( - 2009032802 ; serial - 21600 ; refresh (6 hours) - 7200 ; retry (2 hours) - 604800 ; expire (1 week) - 3600 ; minimum (1 hour) - )`: "miek.nl.\t86400\tIN\tSOA\telektron.atoom.net. miekg.atoom.net. 2009032802 21600 7200 604800 3600", - } - for i, o := range tests { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error() + "\n\t" + i) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestParseFailure(t *testing.T) { - tests := []string{"miek.nl. IN A 327.0.0.1", - "miek.nl. IN AAAA ::x", - "miek.nl. IN MX a0 miek.nl.", - "miek.nl aap IN MX mx.miek.nl.", - "miek.nl 200 IN mxx 10 mx.miek.nl.", - "miek.nl. inn MX 10 mx.miek.nl.", - // "miek.nl. IN CNAME ", // actually valid nowadays, zero size rdata - "miek.nl. IN CNAME ..", - "miek.nl. PA MX 10 miek.nl.", - "miek.nl. ) IN MX 10 miek.nl.", - } - - for _, s := range tests { - _, err := NewRR(s) - if err == nil { - t.Logf("should have triggered an error: \"%s\"", s) - t.Fail() - } - } -} - -func TestZoneParsing(t *testing.T) { - // parse_test.db - db := ` -a.example.com. IN A 127.0.0.1 -8db7._openpgpkey.example.com. IN OPENPGPKEY mQCNAzIG -$ORIGIN a.example.com. -test IN A 127.0.0.1 -$ORIGIN b.example.com. -test IN CNAME test.a.example.com. -` - start := time.Now().UnixNano() - to := ParseZone(strings.NewReader(db), "", "parse_test.db") - var i int - for x := range to { - i++ - if x.Error != nil { - t.Logf("%s\n", x.Error) - t.Fail() - continue - } - t.Logf("%s\n", x.RR) - } - delta := time.Now().UnixNano() - start - t.Logf("%d RRs parsed in %.2f s (%.2f RR/s)", i, float32(delta)/1e9, float32(i)/(float32(delta)/1e9)) -} - -func ExampleZone() { - zone := `$ORIGIN . -$TTL 3600 ; 1 hour -name IN SOA a6.nstld.com. hostmaster.nic.name. ( - 203362132 ; serial - 300 ; refresh (5 minutes) - 300 ; retry (5 minutes) - 1209600 ; expire (2 weeks) - 300 ; minimum (5 minutes) - ) -$TTL 10800 ; 3 hours -name. 10800 IN NS name. - IN NS g6.nstld.com. - 7200 NS h6.nstld.com. - 3600 IN NS j6.nstld.com. - IN 3600 NS k6.nstld.com. - NS l6.nstld.com. - NS a6.nstld.com. - NS c6.nstld.com. - NS d6.nstld.com. - NS f6.nstld.com. - NS m6.nstld.com. -( - NS m7.nstld.com. -) -$ORIGIN name. -0-0onlus NS ns7.ehiweb.it. - NS ns8.ehiweb.it. -0-g MX 10 mx01.nic - MX 10 mx02.nic - MX 10 mx03.nic - MX 10 mx04.nic -$ORIGIN 0-g.name -moutamassey NS ns01.yahoodomains.jp. - NS ns02.yahoodomains.jp. -` - to := ParseZone(strings.NewReader(zone), "", "testzone") - for x := range to { - fmt.Printf("%s\n", x.RR) - } - // Output: - // name. 3600 IN SOA a6.nstld.com. hostmaster.nic.name. 203362132 300 300 1209600 300 - // name. 10800 IN NS name. - // name. 10800 IN NS g6.nstld.com. - // name. 7200 IN NS h6.nstld.com. - // name. 3600 IN NS j6.nstld.com. - // name. 3600 IN NS k6.nstld.com. - // name. 10800 IN NS l6.nstld.com. - // name. 10800 IN NS a6.nstld.com. - // name. 10800 IN NS c6.nstld.com. - // name. 10800 IN NS d6.nstld.com. - // name. 10800 IN NS f6.nstld.com. - // name. 10800 IN NS m6.nstld.com. - // name. 10800 IN NS m7.nstld.com. - // 0-0onlus.name. 10800 IN NS ns7.ehiweb.it. - // 0-0onlus.name. 10800 IN NS ns8.ehiweb.it. - // 0-g.name. 10800 IN MX 10 mx01.nic.name. - // 0-g.name. 10800 IN MX 10 mx02.nic.name. - // 0-g.name. 10800 IN MX 10 mx03.nic.name. - // 0-g.name. 10800 IN MX 10 mx04.nic.name. - // moutamassey.0-g.name.name. 10800 IN NS ns01.yahoodomains.jp. - // moutamassey.0-g.name.name. 10800 IN NS ns02.yahoodomains.jp. -} - -func ExampleHIP() { - h := `www.example.com IN HIP ( 2 200100107B1A74DF365639CC39F1D578 - AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p -9+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQ -b1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D - rvs.example.com. )` - if hip, err := NewRR(h); err == nil { - fmt.Printf("%s\n", hip.String()) - } - // Output: - // www.example.com. 3600 IN HIP 2 200100107B1A74DF365639CC39F1D578 AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p9+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQb1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D rvs.example.com. -} - -func TestHIP(t *testing.T) { - h := `www.example.com. IN HIP ( 2 200100107B1A74DF365639CC39F1D578 - AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p -9+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQ -b1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D - rvs1.example.com. - rvs2.example.com. )` - rr, err := NewRR(h) - if err != nil { - t.Fatalf("failed to parse RR: %s", err) - } - t.Logf("RR: %s", rr) - msg := new(Msg) - msg.Answer = []RR{rr, rr} - bytes, err := msg.Pack() - if err != nil { - t.Fatalf("failed to pack msg: %s", err) - } - if err := msg.Unpack(bytes); err != nil { - t.Fatalf("failed to unpack msg: %s", err) - } - if len(msg.Answer) != 2 { - t.Fatalf("2 answers expected: %V", msg) - } - for i, rr := range msg.Answer { - rr := rr.(*HIP) - t.Logf("RR: %s", rr) - if l := len(rr.RendezvousServers); l != 2 { - t.Fatalf("2 servers expected, only %d in record %d:\n%V", l, i, msg) - } - for j, s := range []string{"rvs1.example.com.", "rvs2.example.com."} { - if rr.RendezvousServers[j] != s { - t.Fatalf("expected server %d of record %d to be %s:\n%V", j, i, s, msg) - } - } - } -} - -func ExampleSOA() { - s := "example.com. 1000 SOA master.example.com. admin.example.com. 1 4294967294 4294967293 4294967295 100" - if soa, err := NewRR(s); err == nil { - fmt.Printf("%s\n", soa.String()) - } - // Output: - // example.com. 1000 IN SOA master.example.com. admin.example.com. 1 4294967294 4294967293 4294967295 100 -} - -func TestLineNumberError(t *testing.T) { - s := "example.com. 1000 SOA master.example.com. admin.example.com. monkey 4294967294 4294967293 4294967295 100" - if _, err := NewRR(s); err != nil { - if err.Error() != "dns: bad SOA zone parameter: \"monkey\" at line: 1:68" { - t.Logf("not expecting this error: " + err.Error()) - t.Fail() - } - } -} - -// Test with no known RR on the line -func TestLineNumberError2(t *testing.T) { - tests := map[string]string{ - "example.com. 1000 SO master.example.com. admin.example.com. 1 4294967294 4294967293 4294967295 100": "dns: expecting RR type or class, not this...: \"SO\" at line: 1:21", - "example.com 1000 IN TALINK a.example.com. b..example.com.": "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:57", - "example.com 1000 IN TALINK ( a.example.com. b..example.com. )": "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:60", - `example.com 1000 IN TALINK ( a.example.com. - bb..example.com. )`: "dns: bad TALINK NextName: \"bb..example.com.\" at line: 2:18", - // This is a bug, it should report an error on line 1, but the new is already processed. - `example.com 1000 IN TALINK ( a.example.com. b...example.com. - )`: "dns: bad TALINK NextName: \"b...example.com.\" at line: 2:1"} - - for in, err := range tests { - _, e := NewRR(in) - if e == nil { - t.Fail() - } else { - if e.Error() != err { - t.Logf("%s\n", in) - t.Logf("error should be %s is %s\n", err, e.Error()) - t.Fail() - } - } - } -} - -// Test if the calculations are correct -func TestRfc1982(t *testing.T) { - // If the current time and the timestamp are more than 68 years apart - // it means the date has wrapped. 0 is 1970 - - // fall in the current 68 year span - strtests := []string{"20120525134203", "19700101000000", "20380119031408"} - for _, v := range strtests { - if x, _ := StringToTime(v); v != TimeToString(x) { - t.Logf("1982 arithmetic string failure %s (%s:%d)", v, TimeToString(x), x) - t.Fail() - } - } - - inttests := map[uint32]string{0: "19700101000000", - 1 << 31: "20380119031408", - 1<<32 - 1: "21060207062815", - } - for i, v := range inttests { - if TimeToString(i) != v { - t.Logf("1982 arithmetic int failure %d:%s (%s)", i, v, TimeToString(i)) - t.Fail() - } - } - - // Future tests, these dates get parsed to a date within the current 136 year span - future := map[string]string{"22680119031408": "20631123173144", - "19010101121212": "20370206184028", - "19210101121212": "20570206184028", - "19500101121212": "20860206184028", - "19700101000000": "19700101000000", - "19690101000000": "21050207062816", - "29210101121212": "21040522212236", - } - for from, to := range future { - x, _ := StringToTime(from) - y := TimeToString(x) - if y != to { - t.Logf("1982 arithmetic future failure %s:%s (%s)", from, to, y) - t.Fail() - } - } -} - -func TestEmpty(t *testing.T) { - for _ = range ParseZone(strings.NewReader(""), "", "") { - t.Logf("should be empty") - t.Fail() - } -} - -func TestLowercaseTokens(t *testing.T) { - var testrecords = []string{ - "example.org. 300 IN a 1.2.3.4", - "example.org. 300 in A 1.2.3.4", - "example.org. 300 in a 1.2.3.4", - "example.org. 300 a 1.2.3.4", - "example.org. 300 A 1.2.3.4", - "example.org. IN a 1.2.3.4", - "example.org. in A 1.2.3.4", - "example.org. in a 1.2.3.4", - "example.org. a 1.2.3.4", - "example.org. A 1.2.3.4", - "example.org. a 1.2.3.4", - "$ORIGIN example.org.\n a 1.2.3.4", - "$Origin example.org.\n a 1.2.3.4", - "$origin example.org.\n a 1.2.3.4", - "example.org. Class1 Type1 1.2.3.4", - } - for _, testrr := range testrecords { - _, err := NewRR(testrr) - if err != nil { - t.Errorf("failed to parse %#v, got %s", testrr, err.Error()) - } - } -} - -func ExampleGenerate() { - // From the manual: http://www.bind9.net/manual/bind/9.3.2/Bv9ARM.ch06.html#id2566761 - zone := "$GENERATE 1-2 0 NS SERVER$.EXAMPLE.\n$GENERATE 1-8 $ CNAME $.0" - to := ParseZone(strings.NewReader(zone), "0.0.192.IN-ADDR.ARPA.", "") - for x := range to { - if x.Error == nil { - fmt.Printf("%s\n", x.RR.String()) - } - } - // Output: - // 0.0.0.192.IN-ADDR.ARPA. 3600 IN NS SERVER1.EXAMPLE. - // 0.0.0.192.IN-ADDR.ARPA. 3600 IN NS SERVER2.EXAMPLE. - // 1.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 1.0.0.0.192.IN-ADDR.ARPA. - // 2.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 2.0.0.0.192.IN-ADDR.ARPA. - // 3.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 3.0.0.0.192.IN-ADDR.ARPA. - // 4.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 4.0.0.0.192.IN-ADDR.ARPA. - // 5.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 5.0.0.0.192.IN-ADDR.ARPA. - // 6.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 6.0.0.0.192.IN-ADDR.ARPA. - // 7.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 7.0.0.0.192.IN-ADDR.ARPA. - // 8.0.0.192.IN-ADDR.ARPA. 3600 IN CNAME 8.0.0.0.192.IN-ADDR.ARPA. -} - -func TestSRVPacking(t *testing.T) { - msg := Msg{} - - things := []string{"1.2.3.4:8484", - "45.45.45.45:8484", - "84.84.84.84:8484", - } - - for i, n := range things { - h, p, err := net.SplitHostPort(n) - if err != nil { - continue - } - port := 8484 - tmp, err := strconv.Atoi(p) - if err == nil { - port = tmp - } - - rr := &SRV{ - Hdr: RR_Header{Name: "somename.", - Rrtype: TypeSRV, - Class: ClassINET, - Ttl: 5}, - Priority: uint16(i), - Weight: 5, - Port: uint16(port), - Target: h + ".", - } - - msg.Answer = append(msg.Answer, rr) - } - - _, err := msg.Pack() - if err != nil { - t.Fatalf("couldn't pack %v\n", msg) - } -} - -func TestParseBackslash(t *testing.T) { - if r, e := NewRR("nul\\000gap.test.globnix.net. 600 IN A 192.0.2.10"); e != nil { - t.Fatalf("could not create RR with \\000 in it") - } else { - t.Logf("parsed %s\n", r.String()) - } - if r, e := NewRR(`nul\000gap.test.globnix.net. 600 IN TXT "Hello\123"`); e != nil { - t.Fatalf("could not create RR with \\000 in it") - } else { - t.Logf("parsed %s\n", r.String()) - } - if r, e := NewRR(`m\ @\ iek.nl. IN 3600 A 127.0.0.1`); e != nil { - t.Fatalf("could not create RR with \\ and \\@ in it") - } else { - t.Logf("parsed %s\n", r.String()) - } -} - -func TestILNP(t *testing.T) { - tests := []string{ - "host1.example.com.\t3600\tIN\tNID\t10 0014:4fff:ff20:ee64", - "host1.example.com.\t3600\tIN\tNID\t20 0015:5fff:ff21:ee65", - "host2.example.com.\t3600\tIN\tNID\t10 0016:6fff:ff22:ee66", - "host1.example.com.\t3600\tIN\tL32\t10 10.1.2.0", - "host1.example.com.\t3600\tIN\tL32\t20 10.1.4.0", - "host2.example.com.\t3600\tIN\tL32\t10 10.1.8.0", - "host1.example.com.\t3600\tIN\tL64\t10 2001:0DB8:1140:1000", - "host1.example.com.\t3600\tIN\tL64\t20 2001:0DB8:2140:2000", - "host2.example.com.\t3600\tIN\tL64\t10 2001:0DB8:4140:4000", - "host1.example.com.\t3600\tIN\tLP\t10 l64-subnet1.example.com.", - "host1.example.com.\t3600\tIN\tLP\t10 l64-subnet2.example.com.", - "host1.example.com.\t3600\tIN\tLP\t20 l32-subnet1.example.com.", - } - for _, t1 := range tests { - r, e := NewRR(t1) - if e != nil { - t.Fatalf("an error occured: %s\n", e.Error()) - } else { - if t1 != r.String() { - t.Fatalf("strings should be equal %s %s", t1, r.String()) - } - } - } -} - -func TestNsapGposEidNimloc(t *testing.T) { - dt := map[string]string{ - "foo.bar.com. IN NSAP 21 47000580ffff000000321099991111222233334444": "foo.bar.com.\t3600\tIN\tNSAP\t21 47000580ffff000000321099991111222233334444", - "host.school.de IN NSAP 17 39276f3100111100002222333344449876": "host.school.de.\t3600\tIN\tNSAP\t17 39276f3100111100002222333344449876", - "444433332222111199990123000000ff. NSAP-PTR foo.bar.com.": "444433332222111199990123000000ff.\t3600\tIN\tNSAP-PTR\tfoo.bar.com.", - "lillee. IN GPOS -32.6882 116.8652 10.0": "lillee.\t3600\tIN\tGPOS\t-32.6882 116.8652 10.0", - "hinault. IN GPOS -22.6882 116.8652 250.0": "hinault.\t3600\tIN\tGPOS\t-22.6882 116.8652 250.0", - "VENERA. IN NIMLOC 75234159EAC457800920": "VENERA.\t3600\tIN\tNIMLOC\t75234159EAC457800920", - "VAXA. IN EID 3141592653589793": "VAXA.\t3600\tIN\tEID\t3141592653589793", - } - for i, o := range dt { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestPX(t *testing.T) { - dt := map[string]string{ - "*.net2.it. IN PX 10 net2.it. PRMD-net2.ADMD-p400.C-it.": "*.net2.it.\t3600\tIN\tPX\t10 net2.it. PRMD-net2.ADMD-p400.C-it.", - "ab.net2.it. IN PX 10 ab.net2.it. O-ab.PRMD-net2.ADMDb.C-it.": "ab.net2.it.\t3600\tIN\tPX\t10 ab.net2.it. O-ab.PRMD-net2.ADMDb.C-it.", - } - for i, o := range dt { - rr, e := NewRR(i) - if e != nil { - t.Log("failed to parse RR: " + e.Error()) - t.Fail() - continue - } - if rr.String() != o { - t.Logf("`%s' should be equal to\n`%s', but is `%s'\n", i, o, rr.String()) - t.Fail() - } else { - t.Logf("RR is OK: `%s'", rr.String()) - } - } -} - -func TestComment(t *testing.T) { - // Comments we must see - comments := map[string]bool{"; this is comment 1": true, - "; this is comment 4": true, "; this is comment 6": true, - "; this is comment 7": true, "; this is comment 8": true} - zone := ` -foo. IN A 10.0.0.1 ; this is comment 1 -foo. IN A ( - 10.0.0.2 ; this is comment2 -) -; this is comment3 -foo. IN A 10.0.0.3 -foo. IN A ( 10.0.0.4 ); this is comment 4 - -foo. IN A 10.0.0.5 -; this is comment5 - -foo. IN A 10.0.0.6 - -foo. IN DNSKEY 256 3 5 AwEAAb+8l ; this is comment 6 -foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7 -foo. IN TXT "THIS IS TEXT MAN"; this is comment 8 -` - for x := range ParseZone(strings.NewReader(zone), ".", "") { - if x.Error == nil { - if x.Comment != "" { - if _, ok := comments[x.Comment]; !ok { - t.Logf("wrong comment %s", x.Comment) - t.Fail() - } - } - } - } -} - -func TestEUIxx(t *testing.T) { - tests := map[string]string{ - "host.example. IN EUI48 00-00-5e-90-01-2a": "host.example.\t3600\tIN\tEUI48\t00-00-5e-90-01-2a", - "host.example. IN EUI64 00-00-5e-ef-00-00-00-2a": "host.example.\t3600\tIN\tEUI64\t00-00-5e-ef-00-00-00-2a", - } - for i, o := range tests { - r, e := NewRR(i) - if e != nil { - t.Logf("failed to parse %s: %s\n", i, e.Error()) - t.Fail() - } - if r.String() != o { - t.Logf("want %s, got %s\n", o, r.String()) - t.Fail() - } - } -} - -func TestUserRR(t *testing.T) { - tests := map[string]string{ - "host.example. IN UID 1234": "host.example.\t3600\tIN\tUID\t1234", - "host.example. IN GID 1234556": "host.example.\t3600\tIN\tGID\t1234556", - "host.example. IN UINFO \"Miek Gieben\"": "host.example.\t3600\tIN\tUINFO\t\"Miek Gieben\"", - } - for i, o := range tests { - r, e := NewRR(i) - if e != nil { - t.Logf("failed to parse %s: %s\n", i, e.Error()) - t.Fail() - } - if r.String() != o { - t.Logf("want %s, got %s\n", o, r.String()) - t.Fail() - } - } -} - -func TestTXT(t *testing.T) { - // Test single entry TXT record - rr, err := NewRR(`_raop._tcp.local. 60 IN TXT "single value"`) - if err != nil { - t.Error("failed to parse single value TXT record", err) - } else if rr, ok := rr.(*TXT); !ok { - t.Error("wrong type, record should be of type TXT") - } else { - if len(rr.Txt) != 1 { - t.Error("bad size of TXT value:", len(rr.Txt)) - } else if rr.Txt[0] != "single value" { - t.Error("bad single value") - } - if rr.String() != `_raop._tcp.local. 60 IN TXT "single value"` { - t.Error("bad representation of TXT record:", rr.String()) - } - if rr.len() != 28+1+12 { - t.Error("bad size of serialized record:", rr.len()) - } - } - - // Test multi entries TXT record - rr, err = NewRR(`_raop._tcp.local. 60 IN TXT "a=1" "b=2" "c=3" "d=4"`) - if err != nil { - t.Error("failed to parse multi-values TXT record", err) - } else if rr, ok := rr.(*TXT); !ok { - t.Error("wrong type, record should be of type TXT") - } else { - if len(rr.Txt) != 4 { - t.Error("bad size of TXT multi-value:", len(rr.Txt)) - } else if rr.Txt[0] != "a=1" || rr.Txt[1] != "b=2" || rr.Txt[2] != "c=3" || rr.Txt[3] != "d=4" { - t.Error("bad values in TXT records") - } - if rr.String() != `_raop._tcp.local. 60 IN TXT "a=1" "b=2" "c=3" "d=4"` { - t.Error("bad representation of TXT multi value record:", rr.String()) - } - if rr.len() != 28+1+3+1+3+1+3+1+3 { - t.Error("bad size of serialized multi value record:", rr.len()) - } - } - - // Test empty-string in TXT record - rr, err = NewRR(`_raop._tcp.local. 60 IN TXT ""`) - if err != nil { - t.Error("failed to parse empty-string TXT record", err) - } else if rr, ok := rr.(*TXT); !ok { - t.Error("wrong type, record should be of type TXT") - } else { - if len(rr.Txt) != 1 { - t.Error("bad size of TXT empty-string value:", len(rr.Txt)) - } else if rr.Txt[0] != "" { - t.Error("bad value for empty-string TXT record") - } - if rr.String() != `_raop._tcp.local. 60 IN TXT ""` { - t.Error("bad representation of empty-string TXT record:", rr.String()) - } - if rr.len() != 28+1 { - t.Error("bad size of serialized record:", rr.len()) - } - } -} - -func TestTypeXXXX(t *testing.T) { - _, err := NewRR("example.com IN TYPE1234 \\# 4 aabbccdd") - if err != nil { - t.Logf("failed to parse TYPE1234 RR: %s", err.Error()) - t.Fail() - } - _, err = NewRR("example.com IN TYPE655341 \\# 8 aabbccddaabbccdd") - if err == nil { - t.Logf("this should not work, for TYPE655341") - t.Fail() - } - _, err = NewRR("example.com IN TYPE1 \\# 4 0a000001") - if err == nil { - t.Logf("this should not work") - t.Fail() - } -} - -func TestPTR(t *testing.T) { - _, err := NewRR("144.2.0.192.in-addr.arpa. 900 IN PTR ilouse03146p0\\(.example.com.") - if err != nil { - t.Error("failed to parse ", err.Error()) - } -} - -func TestDigit(t *testing.T) { - tests := map[string]byte{ - "miek\\000.nl. 100 IN TXT \"A\"": 0, - "miek\\001.nl. 100 IN TXT \"A\"": 1, - "miek\\254.nl. 100 IN TXT \"A\"": 254, - "miek\\255.nl. 100 IN TXT \"A\"": 255, - "miek\\256.nl. 100 IN TXT \"A\"": 0, - "miek\\257.nl. 100 IN TXT \"A\"": 1, - "miek\\004.nl. 100 IN TXT \"A\"": 4, - } - for s, i := range tests { - r, e := NewRR(s) - buf := make([]byte, 40) - if e != nil { - t.Fatalf("failed to parse %s\n", e.Error()) - } - PackRR(r, buf, 0, nil, false) - t.Logf("%v\n", buf) - if buf[5] != i { - t.Fatalf("5 pos must be %d, is %d", i, buf[5]) - } - r1, _, _ := UnpackRR(buf, 0) - if r1.Header().Ttl != 100 { - t.Fatalf("TTL should %d, is %d", 100, r1.Header().Ttl) - } - } -} - -func TestParseRRSIGTimestamp(t *testing.T) { - tests := map[string]bool{ - `miek.nl. IN RRSIG SOA 8 2 43200 20140210031301 20140111031301 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`: true, - `miek.nl. IN RRSIG SOA 8 2 43200 315565800 4102477800 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`: true, - } - for r, _ := range tests { - _, e := NewRR(r) - if e != nil { - t.Fail() - t.Logf("%s\n", e.Error()) - } - } -} - -func TestTxtEqual(t *testing.T) { - rr1 := new(TXT) - rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0} - rr1.Txt = []string{"a\"a", "\"", "b"} - rr2, _ := NewRR(rr1.String()) - if rr1.String() != rr2.String() { - t.Logf("these two TXT records should match") - t.Logf("\n%s\n%s\n", rr1.String(), rr2.String()) - t.Fail() // This is not an error, but keep this test. - } - t.Logf("\n%s\n%s\n", rr1.String(), rr2.String()) -} - -func TestTxtLong(t *testing.T) { - rr1 := new(TXT) - rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0} - // Make a long txt record, this breaks when sending the packet, - // but not earlier. - rr1.Txt = []string{"start-"} - for i := 0; i < 200; i++ { - rr1.Txt[0] += "start-" - } - str := rr1.String() - if len(str) < len(rr1.Txt[0]) { - t.Logf("string conversion should work") - t.Fail() - } -} - -// Basically, don't crash. -func TestMalformedPackets(t *testing.T) { - var packets = []string{ - "0021641c0000000100000000000078787878787878787878787303636f6d0000100001", - } - - // com = 63 6f 6d - for _, packet := range packets { - data, _ := hex.DecodeString(packet) - // for _, v := range data { - // t.Logf("%s ", string(v)) - // } - var msg Msg - msg.Unpack(data) - // println(msg.String()) - } -} - -type algorithm struct { - name uint8 - bits int -} - -func TestNewPrivateKey(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - algorithms := []algorithm{ - algorithm{ECDSAP256SHA256, 256}, - algorithm{ECDSAP384SHA384, 384}, - algorithm{RSASHA1, 1024}, - algorithm{RSASHA256, 2048}, - algorithm{DSA, 1024}, - } - - for _, algo := range algorithms { - key := new(DNSKEY) - key.Hdr.Rrtype = TypeDNSKEY - key.Hdr.Name = "miek.nl." - key.Hdr.Class = ClassINET - key.Hdr.Ttl = 14400 - key.Flags = 256 - key.Protocol = 3 - key.Algorithm = algo.name - privkey, err := key.Generate(algo.bits) - if err != nil { - t.Fatal(err.Error()) - } - - newPrivKey, err := key.NewPrivateKey(key.PrivateKeyString(privkey)) - if err != nil { - t.Log(key.String()) - t.Log(key.PrivateKeyString(privkey)) - - t.Fatal(err.Error()) - } - - switch newPrivKey := newPrivKey.(type) { - case *rsa.PrivateKey: - newPrivKey.Precompute() - } - - if !reflect.DeepEqual(privkey, newPrivKey) { - t.Errorf("[%v] Private keys differ:\n%#v\n%#v\n", AlgorithmToString[algo.name], privkey, newPrivKey) - } - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/privaterr_test.go b/Godeps/_workspace/src/github.com/miekg/dns/privaterr_test.go deleted file mode 100644 index 6f1dff89c6a..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/privaterr_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package dns_test - -import ( - "github.com/miekg/dns" - "strings" - "testing" -) - -const TypeISBN uint16 = 0x0F01 - -// A crazy new RR type :) -type ISBN struct { - x string // rdata with 10 or 13 numbers, dashes or spaces allowed -} - -func NewISBN() dns.PrivateRdata { return &ISBN{""} } - -func (rd *ISBN) Len() int { return len([]byte(rd.x)) } -func (rd *ISBN) String() string { return rd.x } - -func (rd *ISBN) Parse(txt []string) error { - rd.x = strings.TrimSpace(strings.Join(txt, " ")) - return nil -} - -func (rd *ISBN) Pack(buf []byte) (int, error) { - b := []byte(rd.x) - n := copy(buf, b) - if n != len(b) { - return n, dns.ErrBuf - } - return n, nil -} - -func (rd *ISBN) Unpack(buf []byte) (int, error) { - rd.x = string(buf) - return len(buf), nil -} - -func (rd *ISBN) Copy(dest dns.PrivateRdata) error { - isbn, ok := dest.(*ISBN) - if !ok { - return dns.ErrRdata - } - isbn.x = rd.x - return nil -} - -var testrecord = strings.Join([]string{"example.org.", "3600", "IN", "ISBN", "12-3 456789-0-123"}, "\t") - -func TestPrivateText(t *testing.T) { - dns.PrivateHandle("ISBN", TypeISBN, NewISBN) - defer dns.PrivateHandleRemove(TypeISBN) - - rr, err := dns.NewRR(testrecord) - if err != nil { - t.Fatal(err) - } - if rr.String() != testrecord { - t.Errorf("record string representation did not match original %#v != %#v", rr.String(), testrecord) - } else { - t.Log(rr.String()) - } -} - -func TestPrivateByteSlice(t *testing.T) { - dns.PrivateHandle("ISBN", TypeISBN, NewISBN) - defer dns.PrivateHandleRemove(TypeISBN) - - rr, err := dns.NewRR(testrecord) - if err != nil { - t.Fatal(err) - } - - buf := make([]byte, 100) - off, err := dns.PackRR(rr, buf, 0, nil, false) - if err != nil { - t.Errorf("got error packing ISBN: %s", err) - } - - custrr := rr.(*dns.PrivateRR) - if ln := custrr.Data.Len() + len(custrr.Header().Name) + 11; ln != off { - t.Errorf("offset is not matching to length of Private RR: %d!=%d", off, ln) - } - - rr1, off1, err := dns.UnpackRR(buf[:off], 0) - if err != nil { - t.Errorf("got error unpacking ISBN: %s", err) - } - - if off1 != off { - t.Errorf("Offset after unpacking differs: %d != %d", off1, off) - } - - if rr1.String() != testrecord { - t.Errorf("Record string representation did not match original %#v != %#v", rr1.String(), testrecord) - } else { - t.Log(rr1.String()) - } -} - -const TypeVERSION uint16 = 0x0F02 - -type VERSION struct { - x string -} - -func NewVersion() dns.PrivateRdata { return &VERSION{""} } - -func (rd *VERSION) String() string { return rd.x } -func (rd *VERSION) Parse(txt []string) error { - rd.x = strings.TrimSpace(strings.Join(txt, " ")) - return nil -} - -func (rd *VERSION) Pack(buf []byte) (int, error) { - b := []byte(rd.x) - n := copy(buf, b) - if n != len(b) { - return n, dns.ErrBuf - } - return n, nil -} - -func (rd *VERSION) Unpack(buf []byte) (int, error) { - rd.x = string(buf) - return len(buf), nil -} - -func (rd *VERSION) Copy(dest dns.PrivateRdata) error { - isbn, ok := dest.(*VERSION) - if !ok { - return dns.ErrRdata - } - isbn.x = rd.x - return nil -} - -func (rd *VERSION) Len() int { - return len([]byte(rd.x)) -} - -var smallzone = `$ORIGIN example.org. -@ SOA sns.dns.icann.org. noc.dns.icann.org. ( - 2014091518 7200 3600 1209600 3600 -) - A 1.2.3.4 -ok ISBN 1231-92110-12 -go VERSION ( - 1.3.1 ; comment -) -www ISBN 1231-92110-16 -* CNAME @ -` - -func TestPrivateZoneParser(t *testing.T) { - dns.PrivateHandle("ISBN", TypeISBN, NewISBN) - dns.PrivateHandle("VERSION", TypeVERSION, NewVersion) - defer dns.PrivateHandleRemove(TypeISBN) - defer dns.PrivateHandleRemove(TypeVERSION) - - r := strings.NewReader(smallzone) - for x := range dns.ParseZone(r, ".", "") { - if err := x.Error; err != nil { - t.Fatal(err) - } - t.Log(x.RR) - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/server_test.go b/Godeps/_workspace/src/github.com/miekg/dns/server_test.go deleted file mode 100644 index 5efb1cf8973..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/server_test.go +++ /dev/null @@ -1,401 +0,0 @@ -package dns - -import ( - "fmt" - "net" - "runtime" - "sync" - "testing" -) - -func HelloServer(w ResponseWriter, req *Msg) { - m := new(Msg) - m.SetReply(req) - - m.Extra = make([]RR, 1) - m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}} - w.WriteMsg(m) -} - -func AnotherHelloServer(w ResponseWriter, req *Msg) { - m := new(Msg) - m.SetReply(req) - - m.Extra = make([]RR, 1) - m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello example"}} - w.WriteMsg(m) -} - -func RunLocalUDPServer(laddr string) (*Server, string, error) { - pc, err := net.ListenPacket("udp", laddr) - if err != nil { - return nil, "", err - } - server := &Server{PacketConn: pc} - - waitLock := sync.Mutex{} - waitLock.Lock() - server.NotifyStartedFunc = waitLock.Unlock - - go func() { - server.ActivateAndServe() - pc.Close() - }() - - waitLock.Lock() - return server, pc.LocalAddr().String(), nil -} - -func RunLocalUDPServerUnsafe(laddr string) (*Server, string, error) { - pc, err := net.ListenPacket("udp", laddr) - if err != nil { - return nil, "", err - } - server := &Server{PacketConn: pc, Unsafe: true} - - waitLock := sync.Mutex{} - waitLock.Lock() - server.NotifyStartedFunc = waitLock.Unlock - - go func() { - server.ActivateAndServe() - pc.Close() - }() - - waitLock.Lock() - return server, pc.LocalAddr().String(), nil -} - -func RunLocalTCPServer(laddr string) (*Server, string, error) { - l, err := net.Listen("tcp", laddr) - if err != nil { - return nil, "", err - } - - server := &Server{Listener: l} - - waitLock := sync.Mutex{} - waitLock.Lock() - server.NotifyStartedFunc = waitLock.Unlock - - go func() { - server.ActivateAndServe() - l.Close() - }() - - waitLock.Lock() - return server, l.Addr().String(), nil -} - -func TestServing(t *testing.T) { - HandleFunc("miek.nl.", HelloServer) - HandleFunc("example.com.", AnotherHelloServer) - defer HandleRemove("miek.nl.") - defer HandleRemove("example.com.") - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - c := new(Client) - m := new(Msg) - m.SetQuestion("miek.nl.", TypeTXT) - r, _, err := c.Exchange(m, addrstr) - if err != nil || len(r.Extra) == 0 { - t.Log("failed to exchange miek.nl", err) - t.Fatal() - } - txt := r.Extra[0].(*TXT).Txt[0] - if txt != "Hello world" { - t.Log("Unexpected result for miek.nl", txt, "!= Hello world") - t.Fail() - } - - m.SetQuestion("example.com.", TypeTXT) - r, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Log("failed to exchange example.com", err) - t.Fatal() - } - txt = r.Extra[0].(*TXT).Txt[0] - if txt != "Hello example" { - t.Log("Unexpected result for example.com", txt, "!= Hello example") - t.Fail() - } - - // Test Mixes cased as noticed by Ask. - m.SetQuestion("eXaMplE.cOm.", TypeTXT) - r, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Log("failed to exchange eXaMplE.cOm", err) - t.Fail() - } - txt = r.Extra[0].(*TXT).Txt[0] - if txt != "Hello example" { - t.Log("Unexpected result for example.com", txt, "!= Hello example") - t.Fail() - } -} - -func BenchmarkServe(b *testing.B) { - b.StopTimer() - HandleFunc("miek.nl.", HelloServer) - defer HandleRemove("miek.nl.") - a := runtime.GOMAXPROCS(4) - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - b.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - c := new(Client) - m := new(Msg) - m.SetQuestion("miek.nl", TypeSOA) - - b.StartTimer() - for i := 0; i < b.N; i++ { - c.Exchange(m, addrstr) - } - runtime.GOMAXPROCS(a) -} - -func benchmarkServe6(b *testing.B) { - b.StopTimer() - HandleFunc("miek.nl.", HelloServer) - defer HandleRemove("miek.nl.") - a := runtime.GOMAXPROCS(4) - s, addrstr, err := RunLocalUDPServer("[::1]:0") - if err != nil { - b.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - c := new(Client) - m := new(Msg) - m.SetQuestion("miek.nl", TypeSOA) - - b.StartTimer() - for i := 0; i < b.N; i++ { - c.Exchange(m, addrstr) - } - runtime.GOMAXPROCS(a) -} - -func HelloServerCompress(w ResponseWriter, req *Msg) { - m := new(Msg) - m.SetReply(req) - m.Extra = make([]RR, 1) - m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}} - m.Compress = true - w.WriteMsg(m) -} - -func BenchmarkServeCompress(b *testing.B) { - b.StopTimer() - HandleFunc("miek.nl.", HelloServerCompress) - defer HandleRemove("miek.nl.") - a := runtime.GOMAXPROCS(4) - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - b.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - c := new(Client) - m := new(Msg) - m.SetQuestion("miek.nl", TypeSOA) - b.StartTimer() - for i := 0; i < b.N; i++ { - c.Exchange(m, addrstr) - } - runtime.GOMAXPROCS(a) -} - -func TestDotAsCatchAllWildcard(t *testing.T) { - mux := NewServeMux() - mux.Handle(".", HandlerFunc(HelloServer)) - mux.Handle("example.com.", HandlerFunc(AnotherHelloServer)) - - handler := mux.match("www.miek.nl.", TypeTXT) - if handler == nil { - t.Error("wildcard match failed") - } - - handler = mux.match("www.example.com.", TypeTXT) - if handler == nil { - t.Error("example.com match failed") - } - - handler = mux.match("a.www.example.com.", TypeTXT) - if handler == nil { - t.Error("a.www.example.com match failed") - } - - handler = mux.match("boe.", TypeTXT) - if handler == nil { - t.Error("boe. match failed") - } -} - -func TestCaseFolding(t *testing.T) { - mux := NewServeMux() - mux.Handle("_udp.example.com.", HandlerFunc(HelloServer)) - - handler := mux.match("_dns._udp.example.com.", TypeSRV) - if handler == nil { - t.Error("case sensitive characters folded") - } - - handler = mux.match("_DNS._UDP.EXAMPLE.COM.", TypeSRV) - if handler == nil { - t.Error("case insensitive characters not folded") - } -} - -func TestRootServer(t *testing.T) { - mux := NewServeMux() - mux.Handle(".", HandlerFunc(HelloServer)) - - handler := mux.match(".", TypeNS) - if handler == nil { - t.Error("root match failed") - } -} - -type maxRec struct { - max int - sync.RWMutex -} - -var M = new(maxRec) - -func HelloServerLargeResponse(resp ResponseWriter, req *Msg) { - m := new(Msg) - m.SetReply(req) - m.Authoritative = true - m1 := 0 - M.RLock() - m1 = M.max - M.RUnlock() - for i := 0; i < m1; i++ { - aRec := &A{ - Hdr: RR_Header{ - Name: req.Question[0].Name, - Rrtype: TypeA, - Class: ClassINET, - Ttl: 0, - }, - A: net.ParseIP(fmt.Sprintf("127.0.0.%d", i+1)).To4(), - } - m.Answer = append(m.Answer, aRec) - } - resp.WriteMsg(m) -} - -func TestServingLargeResponses(t *testing.T) { - HandleFunc("example.", HelloServerLargeResponse) - defer HandleRemove("example.") - - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - // Create request - m := new(Msg) - m.SetQuestion("web.service.example.", TypeANY) - - c := new(Client) - c.Net = "udp" - M.Lock() - M.max = 2 - M.Unlock() - _, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Logf("failed to exchange: %s", err.Error()) - t.Fail() - } - // This must fail - M.Lock() - M.max = 20 - M.Unlock() - _, _, err = c.Exchange(m, addrstr) - if err == nil { - t.Logf("failed to fail exchange, this should generate packet error") - t.Fail() - } - // But this must work again - c.UDPSize = 7000 - _, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Logf("failed to exchange: %s", err.Error()) - t.Fail() - } -} - -func TestServingResponse(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - HandleFunc("miek.nl.", HelloServer) - s, addrstr, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - - c := new(Client) - m := new(Msg) - m.SetQuestion("miek.nl.", TypeTXT) - m.Response = false - _, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Log("failed to exchange", err) - t.Fatal() - } - m.Response = true - _, _, err = c.Exchange(m, addrstr) - if err == nil { - t.Log("exchanged response message") - t.Fatal() - } - - s.Shutdown() - s, addrstr, err = RunLocalUDPServerUnsafe("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - defer s.Shutdown() - - m.Response = true - _, _, err = c.Exchange(m, addrstr) - if err != nil { - t.Log("could exchanged response message in Unsafe mode") - t.Fatal() - } -} - -func TestShutdownTCP(t *testing.T) { - s, _, err := RunLocalTCPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - err = s.Shutdown() - if err != nil { - t.Errorf("Could not shutdown test TCP server, %s", err) - } -} - -func TestShutdownUDP(t *testing.T) { - s, _, err := RunLocalUDPServer("127.0.0.1:0") - if err != nil { - t.Fatalf("Unable to run test server: %s", err) - } - err = s.Shutdown() - if err != nil { - t.Errorf("Could not shutdown test UDP server, %s", err) - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/sig0_test.go b/Godeps/_workspace/src/github.com/miekg/dns/sig0_test.go deleted file mode 100644 index 6ca76fb848a..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/sig0_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package dns - -import ( - "testing" - "time" -) - -func TestSIG0(t *testing.T) { - if testing.Short() { - t.Skip("skipping test in short mode.") - } - m := new(Msg) - m.SetQuestion("example.org.", TypeSOA) - for _, alg := range []uint8{DSA, ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256, RSASHA512} { - algstr := AlgorithmToString[alg] - keyrr := new(KEY) - keyrr.Hdr.Name = algstr + "." - keyrr.Hdr.Rrtype = TypeKEY - keyrr.Hdr.Class = ClassINET - keyrr.Algorithm = alg - keysize := 1024 - switch alg { - case ECDSAP256SHA256: - keysize = 256 - case ECDSAP384SHA384: - keysize = 384 - } - pk, err := keyrr.Generate(keysize) - if err != nil { - t.Logf("Failed to generate key for “%s”: %v", algstr, err) - t.Fail() - continue - } - now := uint32(time.Now().Unix()) - sigrr := new(SIG) - sigrr.Hdr.Name = "." - sigrr.Hdr.Rrtype = TypeSIG - sigrr.Hdr.Class = ClassANY - sigrr.Algorithm = alg - sigrr.Expiration = now + 300 - sigrr.Inception = now - 300 - sigrr.KeyTag = keyrr.KeyTag() - sigrr.SignerName = keyrr.Hdr.Name - mb, err := sigrr.Sign(pk, m) - if err != nil { - t.Logf("Failed to sign message using “%s”: %v", algstr, err) - t.Fail() - continue - } - m := new(Msg) - if err := m.Unpack(mb); err != nil { - t.Logf("Failed to unpack message signed using “%s”: %v", algstr, err) - t.Fail() - continue - } - if len(m.Extra) != 1 { - t.Logf("Missing SIG for message signed using “%s”", algstr) - t.Fail() - continue - } - var sigrrwire *SIG - switch rr := m.Extra[0].(type) { - case *SIG: - sigrrwire = rr - default: - t.Logf("Expected SIG RR, instead: %v", rr) - t.Fail() - continue - } - for _, rr := range []*SIG{sigrr, sigrrwire} { - id := "sigrr" - if rr == sigrrwire { - id = "sigrrwire" - } - if err := rr.Verify(keyrr, mb); err != nil { - t.Logf("Failed to verify “%s” signed SIG(%s): %v", algstr, id, err) - t.Fail() - continue - } - } - mb[13]++ - if err := sigrr.Verify(keyrr, mb); err == nil { - t.Logf("Verify succeeded on an altered message using “%s”", algstr) - t.Fail() - continue - } - sigrr.Expiration = 2 - sigrr.Inception = 1 - mb, _ = sigrr.Sign(pk, m) - if err := sigrr.Verify(keyrr, mb); err == nil { - t.Logf("Verify succeeded on an expired message using “%s”", algstr) - t.Fail() - continue - } - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/types_test.go b/Godeps/_workspace/src/github.com/miekg/dns/types_test.go deleted file mode 100644 index 118612946bc..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/types_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package dns - -import ( - "testing" -) - -func TestCmToM(t *testing.T) { - s := cmToM(0, 0) - if s != "0.00" { - t.Error("0, 0") - } - - s = cmToM(1, 0) - if s != "0.01" { - t.Error("1, 0") - } - - s = cmToM(3, 1) - if s != "0.30" { - t.Error("3, 1") - } - - s = cmToM(4, 2) - if s != "4" { - t.Error("4, 2") - } - - s = cmToM(5, 3) - if s != "50" { - t.Error("5, 3") - } - - s = cmToM(7, 5) - if s != "7000" { - t.Error("7, 5") - } - - s = cmToM(9, 9) - if s != "90000000" { - t.Error("9, 9") - } -} diff --git a/Godeps/_workspace/src/github.com/miekg/dns/update_test.go b/Godeps/_workspace/src/github.com/miekg/dns/update_test.go deleted file mode 100644 index fc22536e38e..00000000000 --- a/Godeps/_workspace/src/github.com/miekg/dns/update_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package dns - -import ( - "bytes" - "testing" -) - -func TestDynamicUpdateParsing(t *testing.T) { - prefix := "example.com. IN " - for _, typ := range TypeToString { - if typ == "CAA" || typ == "OPT" || typ == "AXFR" || typ == "IXFR" || typ == "ANY" || typ == "TKEY" || - typ == "TSIG" || typ == "ISDN" || typ == "UNSPEC" || typ == "NULL" || typ == "ATMA" { - continue - } - r, e := NewRR(prefix + typ) - if e != nil { - t.Log("failure to parse: " + prefix + typ) - t.Fail() - } else { - t.Logf("parsed: %s", r.String()) - } - } -} - -func TestDynamicUpdateUnpack(t *testing.T) { - // From https://github.com/miekg/dns/issues/150#issuecomment-62296803 - // It should be an update message for the zone "example.", - // deleting the A RRset "example." and then adding an A record at "example.". - // class ANY, TYPE A - buf := []byte{171, 68, 40, 0, 0, 1, 0, 0, 0, 2, 0, 0, 7, 101, 120, 97, 109, 112, 108, 101, 0, 0, 6, 0, 1, 192, 12, 0, 1, 0, 255, 0, 0, 0, 0, 0, 0, 192, 12, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 127, 0, 0, 1} - msg := new(Msg) - err := msg.Unpack(buf) - if err != nil { - t.Log("failed to unpack: " + err.Error() + "\n" + msg.String()) - t.Fail() - } -} - -func TestDynamicUpdateZeroRdataUnpack(t *testing.T) { - m := new(Msg) - rr := &RR_Header{Name: ".", Rrtype: 0, Class: 1, Ttl: ^uint32(0), Rdlength: 0} - m.Answer = []RR{rr, rr, rr, rr, rr} - m.Ns = m.Answer - for n, s := range TypeToString { - rr.Rrtype = n - bytes, err := m.Pack() - if err != nil { - t.Logf("failed to pack %s: %v", s, err) - t.Fail() - continue - } - if err := new(Msg).Unpack(bytes); err != nil { - t.Logf("failed to unpack %s: %v", s, err) - t.Fail() - } - } -} - -func TestRemoveRRset(t *testing.T) { - // Should add a zero data RR in Class ANY with a TTL of 0 - // for each set mentioned in the RRs provided to it. - rr, err := NewRR(". 100 IN A 127.0.0.1") - if err != nil { - t.Fatalf("Error constructing RR: %v", err) - } - m := new(Msg) - m.Ns = []RR{&RR_Header{Name: ".", Rrtype: TypeA, Class: ClassANY, Ttl: 0, Rdlength: 0}} - expectstr := m.String() - expect, err := m.Pack() - if err != nil { - t.Fatalf("Error packing expected msg: %v", err) - } - - m.Ns = nil - m.RemoveRRset([]RR{rr}) - actual, err := m.Pack() - if err != nil { - t.Fatalf("Error packing actual msg: %v", err) - } - if !bytes.Equal(actual, expect) { - tmp := new(Msg) - if err := tmp.Unpack(actual); err != nil { - t.Fatalf("Error unpacking actual msg: %v", err) - } - t.Logf("Expected msg:\n%s", expectstr) - t.Logf("Actual msg:\n%v", tmp) - t.Fail() - } - - m.Ns = nil - m.RemoveRRset([]RR{rr, rr}) - actual, err = m.Pack() - if err != nil { - t.Fatalf("Error packing actual msg: %v", err) - } - if !bytes.Equal(actual, expect) { - tmp := new(Msg) - if err := tmp.Unpack(actual); err != nil { - t.Fatalf("Error unpacking actual msg: %v", err) - } - t.Logf("Expected msg:\n%v", expectstr) - t.Logf("Actual msg:\n%v", tmp) - t.Fail() - } -} 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 b417deeb64d..00000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package mapstructure - -import ( - "errors" - "reflect" - "testing" -) - -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 := f(reflect.String, reflect.Slice, "") - 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 := f(reflect.String, reflect.Slice, 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 := f(reflect.String, reflect.Slice, "") - if err != nil { - t.Fatalf("bad: %s", err) - } - if f2From != reflect.Int { - t.Fatalf("bad: %#v", f2From) - } -} - -func TestStringToSliceHookFunc(t *testing.T) { - f := StringToSliceHookFunc(",") - - cases := []struct { - f, t reflect.Kind - data interface{} - result interface{} - err bool - }{ - {reflect.Slice, reflect.Slice, 42, 42, false}, - {reflect.String, reflect.String, 42, 42, false}, - { - reflect.String, - reflect.Slice, - "foo,bar,baz", - []string{"foo", "bar", "baz"}, - false, - }, - { - reflect.String, - reflect.Slice, - "", - []string{}, - false, - }, - } - - for i, tc := range cases { - actual, err := 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 - - cases := []struct { - f, t reflect.Kind - data interface{} - result interface{} - err bool - }{ - // TO STRING - { - reflect.Bool, - reflect.String, - false, - "0", - false, - }, - - { - reflect.Bool, - reflect.String, - true, - "1", - false, - }, - - { - reflect.Float32, - reflect.String, - float32(7), - "7", - false, - }, - - { - reflect.Int, - reflect.String, - int(7), - "7", - false, - }, - - { - reflect.Slice, - reflect.String, - []uint8("foo"), - "foo", - false, - }, - - { - reflect.Uint, - reflect.String, - uint(7), - "7", - false, - }, - } - - for i, tc := range cases { - actual, err := 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 b50ac36e5d0..00000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package mapstructure - -import ( - "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) - } -} - -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 7054f1ac9ab..00000000000 --- 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 aa393cc5721..00000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_examples_test.go +++ /dev/null @@ -1,169 +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: - // - // * 'Name' expected type 'string', got unconvertible type 'int' - // * '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' -} - -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} -} 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 23029c7c4aa..00000000000 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go +++ /dev/null @@ -1,828 +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 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 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_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_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 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) - } -} - -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{"Vfoo", "Vbar.Vstring", "Vbar.Vuint", "Vbar"} - 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/mxk/go-flowrate/flowrate/io_test.go b/Godeps/_workspace/src/github.com/mxk/go-flowrate/flowrate/io_test.go deleted file mode 100644 index fa7f4b4ae07..00000000000 --- a/Godeps/_workspace/src/github.com/mxk/go-flowrate/flowrate/io_test.go +++ /dev/null @@ -1,146 +0,0 @@ -// -// Written by Maxim Khitrov (November 2012) -// - -package flowrate - -import ( - "bytes" - "reflect" - "testing" - "time" -) - -const ( - _50ms = 50 * time.Millisecond - _100ms = 100 * time.Millisecond - _200ms = 200 * time.Millisecond - _300ms = 300 * time.Millisecond - _400ms = 400 * time.Millisecond - _500ms = 500 * time.Millisecond -) - -func nextStatus(m *Monitor) Status { - samples := m.samples - for i := 0; i < 30; i++ { - if s := m.Status(); s.Samples != samples { - return s - } - time.Sleep(5 * time.Millisecond) - } - return m.Status() -} - -func TestReader(t *testing.T) { - in := make([]byte, 100) - for i := range in { - in[i] = byte(i) - } - b := make([]byte, 100) - r := NewReader(bytes.NewReader(in), 100) - start := time.Now() - - // Make sure r implements Limiter - _ = Limiter(r) - - // 1st read of 10 bytes is performed immediately - if n, err := r.Read(b); n != 10 || err != nil { - t.Fatalf("r.Read(b) expected 10 (); got %v (%v)", n, err) - } else if rt := time.Since(start); rt > _50ms { - t.Fatalf("r.Read(b) took too long (%v)", rt) - } - - // No new Reads allowed in the current sample - r.SetBlocking(false) - if n, err := r.Read(b); n != 0 || err != nil { - t.Fatalf("r.Read(b) expected 0 (); got %v (%v)", n, err) - } else if rt := time.Since(start); rt > _50ms { - t.Fatalf("r.Read(b) took too long (%v)", rt) - } - - status := [6]Status{0: r.Status()} // No samples in the first status - - // 2nd read of 10 bytes blocks until the next sample - r.SetBlocking(true) - if n, err := r.Read(b[10:]); n != 10 || err != nil { - t.Fatalf("r.Read(b[10:]) expected 10 (); got %v (%v)", n, err) - } else if rt := time.Since(start); rt < _100ms { - t.Fatalf("r.Read(b[10:]) returned ahead of time (%v)", rt) - } - - status[1] = r.Status() // 1st sample - status[2] = nextStatus(r.Monitor) // 2nd sample - status[3] = nextStatus(r.Monitor) // No activity for the 3rd sample - - if n := r.Done(); n != 20 { - t.Fatalf("r.Done() expected 20; got %v", n) - } - - status[4] = r.Status() - status[5] = nextStatus(r.Monitor) // Timeout - start = status[0].Start - - // Active, Start, Duration, Idle, Bytes, Samples, InstRate, CurRate, AvgRate, PeakRate, BytesRem, TimeRem, Progress - want := []Status{ - Status{true, start, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - Status{true, start, _100ms, 0, 10, 1, 100, 100, 100, 100, 0, 0, 0}, - Status{true, start, _200ms, _100ms, 20, 2, 100, 100, 100, 100, 0, 0, 0}, - Status{true, start, _300ms, _200ms, 20, 3, 0, 90, 67, 100, 0, 0, 0}, - Status{false, start, _300ms, 0, 20, 3, 0, 0, 67, 100, 0, 0, 0}, - Status{false, start, _300ms, 0, 20, 3, 0, 0, 67, 100, 0, 0, 0}, - } - for i, s := range status { - if !reflect.DeepEqual(&s, &want[i]) { - t.Errorf("r.Status(%v) expected %v; got %v", i, want[i], s) - } - } - if !bytes.Equal(b[:20], in[:20]) { - t.Errorf("r.Read() input doesn't match output") - } -} - -func TestWriter(t *testing.T) { - b := make([]byte, 100) - for i := range b { - b[i] = byte(i) - } - w := NewWriter(&bytes.Buffer{}, 200) - start := time.Now() - - // Make sure w implements Limiter - _ = Limiter(w) - - // Non-blocking 20-byte write for the first sample returns ErrLimit - w.SetBlocking(false) - if n, err := w.Write(b); n != 20 || err != ErrLimit { - t.Fatalf("w.Write(b) expected 20 (ErrLimit); got %v (%v)", n, err) - } else if rt := time.Since(start); rt > _50ms { - t.Fatalf("w.Write(b) took too long (%v)", rt) - } - - // Blocking 80-byte write - w.SetBlocking(true) - if n, err := w.Write(b[20:]); n != 80 || err != nil { - t.Fatalf("w.Write(b[20:]) expected 80 (); got %v (%v)", n, err) - } else if rt := time.Since(start); rt < _400ms { - t.Fatalf("w.Write(b[20:]) returned ahead of time (%v)", rt) - } - - w.SetTransferSize(100) - status := []Status{w.Status(), nextStatus(w.Monitor)} - start = status[0].Start - - // Active, Start, Duration, Idle, Bytes, Samples, InstRate, CurRate, AvgRate, PeakRate, BytesRem, TimeRem, Progress - want := []Status{ - Status{true, start, _400ms, 0, 80, 4, 200, 200, 200, 200, 20, _100ms, 80000}, - Status{true, start, _500ms, _100ms, 100, 5, 200, 200, 200, 200, 0, 0, 100000}, - } - for i, s := range status { - if !reflect.DeepEqual(&s, &want[i]) { - t.Errorf("w.Status(%v) expected %v; got %v", i, want[i], s) - } - } - if !bytes.Equal(b, w.Writer.(*bytes.Buffer).Bytes()) { - t.Errorf("w.Write() input doesn't match output") - } -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go deleted file mode 100644 index ca4613e6f57..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_suite_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package nodot_test - -import ( - "github.com/onsi/ginkgo" - "github.com/onsi/gomega" - - "testing" -) - -func TestNodot(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Nodot Suite") -} - -// Declarations for Ginkgo DSL -type Done ginkgo.Done -type Benchmarker ginkgo.Benchmarker - -var GinkgoWriter = ginkgo.GinkgoWriter -var GinkgoParallelNode = ginkgo.GinkgoParallelNode -var GinkgoT = ginkgo.GinkgoT -var CurrentGinkgoTestDescription = ginkgo.CurrentGinkgoTestDescription -var RunSpecs = ginkgo.RunSpecs -var RunSpecsWithDefaultAndCustomReporters = ginkgo.RunSpecsWithDefaultAndCustomReporters -var RunSpecsWithCustomReporters = ginkgo.RunSpecsWithCustomReporters -var Fail = ginkgo.Fail -var GinkgoRecover = ginkgo.GinkgoRecover -var Describe = ginkgo.Describe -var FDescribe = ginkgo.FDescribe -var PDescribe = ginkgo.PDescribe -var XDescribe = ginkgo.XDescribe -var Context = ginkgo.Context -var FContext = ginkgo.FContext -var PContext = ginkgo.PContext -var XContext = ginkgo.XContext -var It = ginkgo.It -var FIt = ginkgo.FIt -var PIt = ginkgo.PIt -var XIt = ginkgo.XIt -var Measure = ginkgo.Measure -var FMeasure = ginkgo.FMeasure -var PMeasure = ginkgo.PMeasure -var XMeasure = ginkgo.XMeasure -var BeforeSuite = ginkgo.BeforeSuite -var AfterSuite = ginkgo.AfterSuite -var SynchronizedBeforeSuite = ginkgo.SynchronizedBeforeSuite -var SynchronizedAfterSuite = ginkgo.SynchronizedAfterSuite -var BeforeEach = ginkgo.BeforeEach -var JustBeforeEach = ginkgo.JustBeforeEach -var AfterEach = ginkgo.AfterEach - -// Declarations for Gomega DSL -var RegisterFailHandler = gomega.RegisterFailHandler -var RegisterTestingT = gomega.RegisterTestingT -var InterceptGomegaFailures = gomega.InterceptGomegaFailures -var Ω = gomega.Ω -var Expect = gomega.Expect -var ExpectWithOffset = gomega.ExpectWithOffset -var Eventually = gomega.Eventually -var EventuallyWithOffset = gomega.EventuallyWithOffset -var Consistently = gomega.Consistently -var ConsistentlyWithOffset = gomega.ConsistentlyWithOffset -var SetDefaultEventuallyTimeout = gomega.SetDefaultEventuallyTimeout -var SetDefaultEventuallyPollingInterval = gomega.SetDefaultEventuallyPollingInterval -var SetDefaultConsistentlyDuration = gomega.SetDefaultConsistentlyDuration -var SetDefaultConsistentlyPollingInterval = gomega.SetDefaultConsistentlyPollingInterval - -// Declarations for Gomega Matchers -var Equal = gomega.Equal -var BeEquivalentTo = gomega.BeEquivalentTo -var BeNil = gomega.BeNil -var BeTrue = gomega.BeTrue -var BeFalse = gomega.BeFalse -var HaveOccurred = gomega.HaveOccurred -var MatchError = gomega.MatchError -var BeClosed = gomega.BeClosed -var Receive = gomega.Receive -var MatchRegexp = gomega.MatchRegexp -var ContainSubstring = gomega.ContainSubstring -var MatchJSON = gomega.MatchJSON -var BeEmpty = gomega.BeEmpty -var HaveLen = gomega.HaveLen -var BeZero = gomega.BeZero -var ContainElement = gomega.ContainElement -var ConsistOf = gomega.ConsistOf -var HaveKey = gomega.HaveKey -var HaveKeyWithValue = gomega.HaveKeyWithValue -var BeNumerically = gomega.BeNumerically -var BeTemporally = gomega.BeTemporally -var BeAssignableToTypeOf = gomega.BeAssignableToTypeOf -var Panic = gomega.Panic diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go deleted file mode 100644 index 37260a89f20..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/nodot/nodot_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package nodot_test - -import ( - . "github.com/onsi/ginkgo/ginkgo/nodot" - "strings" -) - -var _ = Describe("ApplyNoDot", func() { - var result string - - apply := func(input string) string { - output, err := ApplyNoDot([]byte(input)) - Ω(err).ShouldNot(HaveOccurred()) - return string(output) - } - - Context("when no declarations have been imported yet", func() { - BeforeEach(func() { - result = apply("") - }) - - It("should add headings for the various declarations", func() { - Ω(result).Should(ContainSubstring("// Declarations for Ginkgo DSL")) - Ω(result).Should(ContainSubstring("// Declarations for Gomega DSL")) - Ω(result).Should(ContainSubstring("// Declarations for Gomega Matchers")) - }) - - It("should import Ginkgo's declarations", func() { - Ω(result).Should(ContainSubstring("var It = ginkgo.It")) - Ω(result).Should(ContainSubstring("var XDescribe = ginkgo.XDescribe")) - }) - - It("should import Ginkgo's types", func() { - Ω(result).Should(ContainSubstring("type Done ginkgo.Done")) - Ω(result).Should(ContainSubstring("type Benchmarker ginkgo.Benchmarker")) - Ω(strings.Count(result, "type ")).Should(Equal(2)) - }) - - It("should import Gomega's DSL and matchers", func() { - Ω(result).Should(ContainSubstring("var Ω = gomega.Ω")) - Ω(result).Should(ContainSubstring("var ContainSubstring = gomega.ContainSubstring")) - Ω(result).Should(ContainSubstring("var Equal = gomega.Equal")) - }) - - It("should not import blacklisted things", func() { - Ω(result).ShouldNot(ContainSubstring("GINKGO_VERSION")) - Ω(result).ShouldNot(ContainSubstring("GINKGO_PANIC")) - Ω(result).ShouldNot(ContainSubstring("GOMEGA_VERSION")) - }) - }) - - It("should be idempotent (module empty lines - go fmt can fix those for us)", func() { - first := apply("") - second := apply(first) - first = strings.Trim(first, "\n") - second = strings.Trim(second, "\n") - Ω(first).Should(Equal(second)) - }) - - It("should not mess with other things in the input", func() { - result = apply("var MyThing = SomethingThatsMine") - Ω(result).Should(ContainSubstring("var MyThing = SomethingThatsMine")) - }) - - Context("when the user has redefined a name", func() { - It("should honor the redefinition", func() { - result = apply(` -var _ = gomega.Ω -var When = ginkgo.It - `) - - Ω(result).Should(ContainSubstring("var _ = gomega.Ω")) - Ω(result).ShouldNot(ContainSubstring("var Ω = gomega.Ω")) - - Ω(result).Should(ContainSubstring("var When = ginkgo.It")) - Ω(result).ShouldNot(ContainSubstring("var It = ginkgo.It")) - - Ω(result).Should(ContainSubstring("var Context = ginkgo.Context")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go deleted file mode 100644 index d1e8b21d37e..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package testsuite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTestsuite(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Testsuite Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go deleted file mode 100644 index 8681ffc11a0..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/ginkgo/testsuite/testsuite_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package testsuite_test - -import ( - "io/ioutil" - "os" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/ginkgo/testsuite" - . "github.com/onsi/gomega" -) - -var _ = Describe("TestSuite", func() { - var tmpDir string - var relTmpDir string - - writeFile := func(folder string, filename string, content string, mode os.FileMode) { - path := filepath.Join(tmpDir, folder) - err := os.MkdirAll(path, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - path = filepath.Join(path, filename) - ioutil.WriteFile(path, []byte(content), mode) - } - - BeforeEach(func() { - var err error - tmpDir, err = ioutil.TempDir("/tmp", "ginkgo") - Ω(err).ShouldNot(HaveOccurred()) - - cwd, err := os.Getwd() - Ω(err).ShouldNot(HaveOccurred()) - relTmpDir, err = filepath.Rel(cwd, tmpDir) - relTmpDir = "./" + relTmpDir - Ω(err).ShouldNot(HaveOccurred()) - - //go files in the root directory (no tests) - writeFile("/", "main.go", "package main", 0666) - - //non-go files in a nested directory - writeFile("/redherring", "big_test.jpg", "package ginkgo", 0666) - - //non-ginkgo tests in a nested directory - writeFile("/professorplum", "professorplum_test.go", `import "testing"`, 0666) - - //ginkgo tests in a nested directory - writeFile("/colonelmustard", "colonelmustard_test.go", `import "github.com/onsi/ginkgo"`, 0666) - - //ginkgo tests in a deeply nested directory - writeFile("/colonelmustard/library", "library_test.go", `import "github.com/onsi/ginkgo"`, 0666) - - //a precompiled ginkgo test - writeFile("/precompiled-dir", "precompiled.test", `fake-binary-file`, 0777) - writeFile("/precompiled-dir", "some-other-binary", `fake-binary-file`, 0777) - writeFile("/precompiled-dir", "nonexecutable.test", `fake-binary-file`, 0666) - }) - - AfterEach(func() { - os.RemoveAll(tmpDir) - }) - - Describe("Finding precompiled test suites", func() { - Context("if pointed at an executable file that ends with .test", func() { - It("should return a precompiled test suite", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "precompiled.test")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(suite).Should(Equal(TestSuite{ - Path: relTmpDir + "/precompiled-dir", - PackageName: "precompiled", - IsGinkgo: true, - Precompiled: true, - })) - }) - }) - - Context("if pointed at a directory", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at an executable that doesn't have .test", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "some-other-binary")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at a .test that isn't executable", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "nonexecutable.test")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if pointed at a nonexisting file", func() { - It("should error", func() { - suite, err := PrecompiledTestSuite(filepath.Join(tmpDir, "precompiled-dir", "nope-nothing-to-see-here")) - Ω(suite).Should(BeZero()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Describe("scanning for suites in a directory", func() { - Context("when there are no tests in the specified directory", func() { - It("should come up empty", func() { - suites := SuitesInDir(tmpDir, false) - Ω(suites).Should(BeEmpty()) - }) - }) - - Context("when there are ginkgo tests in the specified directory", func() { - It("should return an appropriately configured suite", func() { - suites := SuitesInDir(filepath.Join(tmpDir, "colonelmustard"), false) - Ω(suites).Should(HaveLen(1)) - - Ω(suites[0].Path).Should(Equal(relTmpDir + "/colonelmustard")) - Ω(suites[0].PackageName).Should(Equal("colonelmustard")) - Ω(suites[0].IsGinkgo).Should(BeTrue()) - Ω(suites[0].Precompiled).Should(BeFalse()) - }) - }) - - Context("when there are non-ginkgo tests in the specified directory", func() { - It("should return an appropriately configured suite", func() { - suites := SuitesInDir(filepath.Join(tmpDir, "professorplum"), false) - Ω(suites).Should(HaveLen(1)) - - Ω(suites[0].Path).Should(Equal(relTmpDir + "/professorplum")) - Ω(suites[0].PackageName).Should(Equal("professorplum")) - Ω(suites[0].IsGinkgo).Should(BeFalse()) - Ω(suites[0].Precompiled).Should(BeFalse()) - }) - }) - - Context("when recursively scanning", func() { - It("should return suites for corresponding test suites, only", func() { - suites := SuitesInDir(tmpDir, true) - Ω(suites).Should(HaveLen(3)) - - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/colonelmustard", - PackageName: "colonelmustard", - IsGinkgo: true, - Precompiled: false, - })) - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/professorplum", - PackageName: "professorplum", - IsGinkgo: false, - Precompiled: false, - })) - Ω(suites).Should(ContainElement(TestSuite{ - Path: relTmpDir + "/colonelmustard/library", - PackageName: "library", - IsGinkgo: true, - Precompiled: false, - })) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go deleted file mode 100644 index f4fd678c5f6..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/convert_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ginkgo convert", func() { - var tmpDir string - - readConvertedFileNamed := func(pathComponents ...string) string { - pathToFile := filepath.Join(tmpDir, "convert_fixtures", filepath.Join(pathComponents...)) - bytes, err := ioutil.ReadFile(pathToFile) - ExpectWithOffset(1, err).NotTo(HaveOccurred()) - - return string(bytes) - } - - readGoldMasterNamed := func(filename string) string { - bytes, err := ioutil.ReadFile(filepath.Join("_fixtures", "convert_goldmasters", filename)) - Ω(err).ShouldNot(HaveOccurred()) - - return string(bytes) - } - - BeforeEach(func() { - var err error - - tmpDir, err = ioutil.TempDir("", "ginkgo-convert") - Ω(err).ShouldNot(HaveOccurred()) - - err = exec.Command("cp", "-r", filepath.Join("_fixtures", "convert_fixtures"), tmpDir).Run() - Ω(err).ShouldNot(HaveOccurred()) - }) - - JustBeforeEach(func() { - cwd, err := os.Getwd() - Ω(err).ShouldNot(HaveOccurred()) - - relPath, err := filepath.Rel(cwd, filepath.Join(tmpDir, "convert_fixtures")) - Ω(err).ShouldNot(HaveOccurred()) - - cmd := exec.Command(pathToGinkgo, "convert", relPath) - cmd.Env = os.Environ() - for i, env := range cmd.Env { - if strings.HasPrefix(env, "PATH") { - cmd.Env[i] = cmd.Env[i] + ":" + filepath.Dir(pathToGinkgo) - break - } - } - err = cmd.Run() - Ω(err).ShouldNot(HaveOccurred()) - }) - - AfterEach(func() { - err := os.RemoveAll(tmpDir) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("rewrites xunit tests as ginkgo tests", func() { - convertedFile := readConvertedFileNamed("xunit_test.go") - goldMaster := readGoldMasterNamed("xunit_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites all usages of *testing.T as mr.T()", func() { - convertedFile := readConvertedFileNamed("extra_functions_test.go") - goldMaster := readGoldMasterNamed("extra_functions_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites tests in the package dir that belong to other packages", func() { - convertedFile := readConvertedFileNamed("outside_package_test.go") - goldMaster := readGoldMasterNamed("outside_package_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - It("rewrites tests in nested packages", func() { - convertedFile := readConvertedFileNamed("nested", "nested_test.go") - goldMaster := readGoldMasterNamed("nested_test.go") - Ω(convertedFile).Should(Equal(goldMaster)) - }) - - Context("ginkgo test suite files", func() { - It("creates a ginkgo test suite file for the package you specified", func() { - testsuite := readConvertedFileNamed("convert_fixtures_suite_test.go") - goldMaster := readGoldMasterNamed("suite_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - - It("converts go tests in deeply nested packages (some may not contain go files)", func() { - testsuite := readConvertedFileNamed("nested_without_gofiles", "subpackage", "nested_subpackage_test.go") - goldMaster := readGoldMasterNamed("nested_subpackage_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - - It("creates ginkgo test suites for all nested packages", func() { - testsuite := readConvertedFileNamed("nested", "nested_suite_test.go") - goldMaster := readGoldMasterNamed("nested_suite_test.go") - Ω(testsuite).Should(Equal(goldMaster)) - }) - }) - - Context("with an existing test suite file", func() { - BeforeEach(func() { - goldMaster := readGoldMasterNamed("fixtures_suite_test.go") - err := ioutil.WriteFile(filepath.Join(tmpDir, "convert_fixtures", "tmp_suite_test.go"), []byte(goldMaster), 0600) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("gracefully handles existing test suite files", func() { - //nothing should have gone wrong! - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go deleted file mode 100644 index 4a20b0d6e3f..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/coverage_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package integration_test - -import ( - "os" - "os/exec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Coverage Specs", func() { - AfterEach(func() { - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - }) - - It("runs coverage analysis in series and in parallel", func() { - session := startGinkgo("./_fixtures/coverage_fixture", "-cover") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - Ω(output).Should(ContainSubstring("coverage: 80.0% of statements")) - - serialCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - - Eventually(startGinkgo("./_fixtures/coverage_fixture", "-cover", "-nodes=4")).Should(gexec.Exit(0)) - - parallelCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - Ω(parallelCoverProfileOutput).Should(Equal(serialCoverProfileOutput)) - }) - - It("runs coverage analysis on external packages in series and in parallel", func() { - session := startGinkgo("./_fixtures/coverage_fixture", "-coverpkg=github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture,github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - Ω(output).Should(ContainSubstring("coverage: 71.4% of statements in github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture, github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture")) - - serialCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - os.RemoveAll("./_fixtures/coverage_fixture/coverage_fixture.coverprofile") - - Eventually(startGinkgo("./_fixtures/coverage_fixture", "-coverpkg=github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture,github.com/onsi/ginkgo/integration/_fixtures/coverage_fixture/external_coverage_fixture", "-nodes=4")).Should(gexec.Exit(0)) - - parallelCoverProfileOutput, err := exec.Command("go", "tool", "cover", "-func=./_fixtures/coverage_fixture/coverage_fixture.coverprofile").CombinedOutput() - Ω(err).ShouldNot(HaveOccurred()) - - Ω(parallelCoverProfileOutput).Should(Equal(serialCoverProfileOutput)) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go deleted file mode 100644 index 8dcf5e4ad92..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/fail_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Failing Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("failing") - copyIn("fail_fixture", pathToTest) - }) - - It("should fail in all the possible ways", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - - Ω(output).Should(ContainSubstring("a top level failure on line 9")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:9")) - Ω(output).Should(ContainSubstring("an async top level failure on line 14")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:14")) - Ω(output).Should(ContainSubstring("a top level goroutine failure on line 21")) - Ω(output).Should(ContainSubstring("fail_fixture_test.go:21")) - - Ω(output).Should(ContainSubstring("a sync failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a sync panic`)) - Ω(output).Should(ContainSubstring("a sync FAIL failure")) - Ω(output).Should(ContainSubstring("async timeout [It]")) - Ω(output).Should(ContainSubstring("Timed out")) - Ω(output).Should(ContainSubstring("an async failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+an async panic`)) - Ω(output).Should(ContainSubstring("an async FAIL failure")) - Ω(output).Should(ContainSubstring("a goroutine FAIL failure")) - Ω(output).Should(ContainSubstring("a goroutine failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a goroutine panic`)) - Ω(output).Should(ContainSubstring("a measure failure")) - Ω(output).Should(ContainSubstring("a measure FAIL failure")) - Ω(output).Should(MatchRegexp(`Test Panicked\n\s+a measure panic`)) - - Ω(output).Should(ContainSubstring("0 Passed | 16 Failed")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go deleted file mode 100644 index 0a23f5964d9..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/flags_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package integration_test - -import ( - "os" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Flags Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("flags") - copyIn("flags_tests", pathToTest) - }) - - getRandomOrders := func(output string) []int { - return []int{strings.Index(output, "RANDOM_A"), strings.Index(output, "RANDOM_B"), strings.Index(output, "RANDOM_C")} - } - - It("normally passes, runs measurements, prints out noisy pendings, does not randomize tests, and honors the programmatic focus", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Ran 3 samples:"), "has a measurement") - Ω(output).Should(ContainSubstring("10 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("2 Skipped")) - Ω(output).Should(ContainSubstring("[PENDING]")) - Ω(output).Should(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("CUSTOM_FLAG: default")) - Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE)) - Ω(output).ShouldNot(ContainSubstring("smores")) - Ω(output).ShouldNot(ContainSubstring("SLOW TEST")) - Ω(output).ShouldNot(ContainSubstring("should honor -slowSpecThreshold")) - - orders := getRandomOrders(output) - Ω(orders[0]).Should(BeNumerically("<", orders[1])) - Ω(orders[1]).Should(BeNumerically("<", orders[2])) - }) - - It("should run a coverprofile when passed -cover", func() { - session := startGinkgo(pathToTest, "--noColor", "--cover", "--focus=the focused set") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - _, err := os.Stat(filepath.Join(pathToTest, "flags.coverprofile")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(output).Should(ContainSubstring("coverage: ")) - }) - - It("should fail when there are pending tests and it is passed --failOnPending", func() { - session := startGinkgo(pathToTest, "--noColor", "--failOnPending") - Eventually(session).Should(gexec.Exit(1)) - }) - - It("should not print out pendings when --noisyPendings=false", func() { - session := startGinkgo(pathToTest, "--noColor", "--noisyPendings=false") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("[PENDING]")) - Ω(output).Should(ContainSubstring("1 Pending")) - }) - - It("should override the programmatic focus when told to focus", func() { - session := startGinkgo(pathToTest, "--noColor", "--focus=smores") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("smores")) - Ω(output).Should(ContainSubstring("3 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("0 Pending")) - Ω(output).Should(ContainSubstring("10 Skipped")) - }) - - It("should override the programmatic focus when told to skip", func() { - session := startGinkgo(pathToTest, "--noColor", "--skip=marshmallow|failing") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("marshmallow")) - Ω(output).Should(ContainSubstring("chocolate")) - Ω(output).Should(ContainSubstring("smores")) - Ω(output).Should(ContainSubstring("10 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("2 Skipped")) - }) - - It("should run the race detector when told to", func() { - session := startGinkgo(pathToTest, "--noColor", "--race") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("WARNING: DATA RACE")) - }) - - It("should randomize tests when told to", func() { - session := startGinkgo(pathToTest, "--noColor", "--randomizeAllSpecs", "--seed=21") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - orders := getRandomOrders(output) - Ω(orders[0]).ShouldNot(BeNumerically("<", orders[1])) - }) - - It("should skip measurements when told to", func() { - session := startGinkgo(pathToTest, "--skipMeasurements") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("Ran 3 samples:"), "has a measurement") - Ω(output).Should(ContainSubstring("3 Skipped")) - }) - - It("should watch for slow specs", func() { - session := startGinkgo(pathToTest, "--slowSpecThreshold=0.05") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("SLOW TEST")) - Ω(output).Should(ContainSubstring("should honor -slowSpecThreshold")) - }) - - It("should pass additional arguments in", func() { - session := startGinkgo(pathToTest, "--", "--customFlag=madagascar") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("CUSTOM_FLAG: madagascar")) - }) - - It("should print out full stack traces for failures when told to", func() { - session := startGinkgo(pathToTest, "--focus=a failing test", "--trace") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Full Stack Trace")) - }) - - It("should fail fast when told to", func() { - pathToTest = tmpPath("fail") - copyIn("fail_fixture", pathToTest) - session := startGinkgo(pathToTest, "--failFast") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("1 Failed")) - Ω(output).Should(ContainSubstring("15 Skipped")) - }) - - It("should perform a dry run when told to", func() { - pathToTest = tmpPath("fail") - copyIn("fail_fixture", pathToTest) - session := startGinkgo(pathToTest, "--dryRun", "-v") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("synchronous failures")) - Ω(output).Should(ContainSubstring("16 Specs")) - Ω(output).Should(ContainSubstring("0 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go deleted file mode 100644 index 0ad407c8453..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/integration_suite_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package integration_test - -import ( - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" - - "testing" - "time" -) - -var tmpDir string -var pathToGinkgo string - -func TestIntegration(t *testing.T) { - SetDefaultEventuallyTimeout(15 * time.Second) - RegisterFailHandler(Fail) - RunSpecs(t, "Integration Suite") -} - -var _ = SynchronizedBeforeSuite(func() []byte { - pathToGinkgo, err := gexec.Build("github.com/onsi/ginkgo/ginkgo") - Ω(err).ShouldNot(HaveOccurred()) - return []byte(pathToGinkgo) -}, func(computedPathToGinkgo []byte) { - pathToGinkgo = string(computedPathToGinkgo) -}) - -var _ = BeforeEach(func() { - var err error - tmpDir, err = ioutil.TempDir("", "ginkgo-run") - Ω(err).ShouldNot(HaveOccurred()) -}) - -var _ = AfterEach(func() { - err := os.RemoveAll(tmpDir) - Ω(err).ShouldNot(HaveOccurred()) -}) - -var _ = SynchronizedAfterSuite(func() {}, func() { - gexec.CleanupBuildArtifacts() -}) - -func tmpPath(destination string) string { - return filepath.Join(tmpDir, destination) -} - -func copyIn(fixture string, destination string) { - err := os.MkdirAll(destination, 0777) - Ω(err).ShouldNot(HaveOccurred()) - - filepath.Walk(filepath.Join("_fixtures", fixture), func(path string, info os.FileInfo, err error) error { - if info.IsDir() { - return nil - } - - base := filepath.Base(path) - - src, err := os.Open(path) - Ω(err).ShouldNot(HaveOccurred()) - - dst, err := os.Create(filepath.Join(destination, base)) - Ω(err).ShouldNot(HaveOccurred()) - - _, err = io.Copy(dst, src) - Ω(err).ShouldNot(HaveOccurred()) - return nil - }) -} - -func ginkgoCommand(dir string, args ...string) *exec.Cmd { - cmd := exec.Command(pathToGinkgo, args...) - cmd.Dir = dir - - return cmd -} - -func startGinkgo(dir string, args ...string) *gexec.Session { - cmd := ginkgoCommand(dir, args...) - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - return session -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go deleted file mode 100644 index dc3bf2842b1..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/interrupt_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package integration_test - -import ( - "os/exec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Interrupt", func() { - var pathToTest string - BeforeEach(func() { - pathToTest = tmpPath("hanging") - copyIn("hanging_suite", pathToTest) - }) - - Context("when interrupting a suite", func() { - var session *gexec.Session - BeforeEach(func() { - //we need to signal the actual process, so we must compile the test first - var err error - cmd := exec.Command("go", "test", "-c") - cmd.Dir = pathToTest - session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - Eventually(session).Should(gexec.Exit(0)) - - //then run the compiled test directly - cmd = exec.Command("./hanging.test", "--test.v=true", "--ginkgo.noColor") - cmd.Dir = pathToTest - session, err = gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - Eventually(session).Should(gbytes.Say("Sleeping...")) - session.Interrupt() - Eventually(session, 1000).Should(gexec.Exit(1)) - }) - - It("should emit the contents of the GinkgoWriter", func() { - Ω(session).Should(gbytes.Say("Just beginning")) - Ω(session).Should(gbytes.Say("Almost there...")) - Ω(session).Should(gbytes.Say("Hanging Out")) - }) - - It("should run the AfterSuite", func() { - Ω(session).Should(gbytes.Say("Heading Out After Suite")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go deleted file mode 100644 index d9b78e0b275..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/precompiled_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package integration_test - -import ( - "os" - "os/exec" - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("ginkgo build", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("passing_ginkgo_tests") - copyIn("passing_ginkgo_tests", pathToTest) - session := startGinkgo(pathToTest, "build") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Compiling passing_ginkgo_tests")) - Ω(output).Should(ContainSubstring("compiled passing_ginkgo_tests.test")) - }) - - It("should build a test binary", func() { - _, err := os.Stat(filepath.Join(pathToTest, "passing_ginkgo_tests.test")) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should be possible to run the test binary directly", func() { - cmd := exec.Command("./passing_ginkgo_tests.test") - cmd.Dir = pathToTest - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - }) - - It("should be possible to run the test binary via ginkgo", func() { - session := startGinkgo(pathToTest, "./passing_ginkgo_tests.test") - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - }) - - It("should be possible to run the test binary in parallel", func() { - session := startGinkgo(pathToTest, "--nodes=4", "--noColor", "./passing_ginkgo_tests.test") - Eventually(session).Should(gexec.Exit(0)) - Ω(session).Should(gbytes.Say("Running Suite: Passing_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("Running in parallel across 4 nodes")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go deleted file mode 100644 index 8589c338a84..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/progress_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Emitting progress", func() { - var pathToTest string - var session *gexec.Session - var args []string - - BeforeEach(func() { - args = []string{"--noColor"} - pathToTest = tmpPath("progress") - copyIn("progress_fixture", pathToTest) - }) - - JustBeforeEach(func() { - session = startGinkgo(pathToTest, args...) - Eventually(session).Should(gexec.Exit(0)) - }) - - Context("with the -progress flag, but no -v flag", func() { - BeforeEach(func() { - args = append(args, "-progress") - }) - - It("should not emit progress", func() { - Ω(session).ShouldNot(gbytes.Say("[bB]efore")) - }) - }) - - Context("with the -v flag", func() { - BeforeEach(func() { - args = append(args, "-v") - }) - - It("should not emit progress", func() { - Ω(session).ShouldNot(gbytes.Say(`\[BeforeEach\]`)) - Ω(session).Should(gbytes.Say(`>outer before<`)) - }) - }) - - Context("with the -progress flag and the -v flag", func() { - BeforeEach(func() { - args = append(args, "-progress", "-v") - }) - - It("should emit progress (by writing to the GinkgoWriter)", func() { - Ω(session).Should(gbytes.Say(`\[BeforeEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer before<`)) - - Ω(session).Should(gbytes.Say(`\[BeforeEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner before<`)) - - Ω(session).Should(gbytes.Say(`\[JustBeforeEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer just before<`)) - - Ω(session).Should(gbytes.Say(`\[JustBeforeEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner just before<`)) - - Ω(session).Should(gbytes.Say(`\[It\] should emit progress as it goes`)) - Ω(session).Should(gbytes.Say(`>it<`)) - - Ω(session).Should(gbytes.Say(`\[AfterEach\] Inner Context`)) - Ω(session).Should(gbytes.Say(`>inner after<`)) - - Ω(session).Should(gbytes.Say(`\[AfterEach\] ProgressFixture`)) - Ω(session).Should(gbytes.Say(`>outer after<`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go deleted file mode 100644 index 698f96b427a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/run_test.go +++ /dev/null @@ -1,373 +0,0 @@ -package integration_test - -import ( - "runtime" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Running Specs", func() { - var pathToTest string - - Context("when pointed at the current directory", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should run the tests in the working directory", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("••••")) - Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed an explicit package to run", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should run the ginkgo style tests", func() { - session := startGinkgo(tmpDir, "--noColor", pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("••••")) - Ω(output).Should(ContainSubstring("SUCCESS! -- 4 Passed")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed a number of packages to run", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - It("should run the ginkgo style tests", func() { - session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "ginkgo", "./other") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when passed a number of packages to run, some of which have focused tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - focusedPathToTest := tmpPath("focused") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - copyIn("focused_fixture", focusedPathToTest) - }) - - It("should exit with a status code of 2 and explain why", func() { - session := startGinkgo(tmpDir, "--noColor", "--succinct=false", "-r") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - Ω(output).Should(ContainSubstring("Detected Programmatic Focus - setting exit status to %d", types.GINKGO_FOCUS_EXIT_CODE)) - }) - }) - - Context("when told to skipPackages", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - focusedPathToTest := tmpPath("focused") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - copyIn("focused_fixture", focusedPathToTest) - }) - - It("should skip packages that match the list", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Passing_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - - Context("when all packages are skipped", func() { - It("should not run anything, but still exit 0", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused,ginkgo", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("All tests skipped!")) - Ω(output).ShouldNot(ContainSubstring("Passing_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).ShouldNot(ContainSubstring("Focused_fixture Suite")) - Ω(output).ShouldNot(ContainSubstring("Test Suite Passed")) - }) - }) - }) - - Context("when there are no tests to run", func() { - It("should exit 1", func() { - session := startGinkgo(tmpDir, "--noColor", "--skipPackage=other,focused", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Err.Contents()) - - Ω(output).Should(ContainSubstring("Found no test suites")) - }) - }) - - Context("when told to randomizeSuites", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - otherPathToTest := tmpPath("other") - copyIn("passing_ginkgo_tests", pathToTest) - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - It("should skip packages that match the regexp", func() { - session := startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=2") - Eventually(session).Should(gexec.Exit(0)) - - Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) - - session = startGinkgo(tmpDir, "--noColor", "--randomizeSuites", "-r", "--seed=3") - Eventually(session).Should(gexec.Exit(0)) - - Ω(session).Should(gbytes.Say("Passing_ginkgo_tests Suite")) - Ω(session).Should(gbytes.Say("More_ginkgo_tests Suite")) - }) - }) - - Context("when pointed at a package with xunit style tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("xunit") - copyIn("xunit_tests", pathToTest) - }) - - It("should run the xunit style tests", func() { - session := startGinkgo(pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("--- PASS: TestAlwaysTrue")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when pointed at a package with no tests", func() { - BeforeEach(func() { - pathToTest = tmpPath("no_tests") - copyIn("no_tests", pathToTest) - }) - - It("should fail", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - - Ω(session.Err.Contents()).Should(ContainSubstring("Found no test suites")) - }) - }) - - Context("when pointed at a package that fails to compile", func() { - BeforeEach(func() { - pathToTest = tmpPath("does_not_compile") - copyIn("does_not_compile", pathToTest) - }) - - It("should fail", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Failed to compile")) - }) - }) - - Context("when running in parallel", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - Context("with a specific number of -nodes", func() { - It("should use the specified number of nodes", func() { - session := startGinkgo(pathToTest, "--noColor", "-succinct", "-nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - 2 nodes •••• SUCCESS! \d+(\.\d+)?[muµ]s`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("with -p", func() { - It("it should autocompute the number of nodes", func() { - session := startGinkgo(pathToTest, "--noColor", "-succinct", "-p") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - nodes := runtime.NumCPU() - if nodes > 4 { - nodes = nodes - 1 - } - Ω(output).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs - %d nodes •••• SUCCESS! \d+(\.\d+)?[muµ]s`, nodes)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - }) - - Context("when streaming in parallel", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should print output in realtime", func() { - session := startGinkgo(pathToTest, "--noColor", "-stream", "-nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring(`[1] Parallel test node 1/2.`)) - Ω(output).Should(ContainSubstring(`[2] Parallel test node 2/2.`)) - Ω(output).Should(ContainSubstring(`[1] SUCCESS!`)) - Ω(output).Should(ContainSubstring(`[2] SUCCESS!`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when running recursively", func() { - BeforeEach(func() { - passingTest := tmpPath("A") - otherPassingTest := tmpPath("E") - copyIn("passing_ginkgo_tests", passingTest) - copyIn("more_ginkgo_tests", otherPassingTest) - }) - - Context("when all the tests pass", func() { - It("should run all the tests (in succinct mode) and succeed", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - }) - }) - - Context("when one of the packages has a failing tests", func() { - BeforeEach(func() { - failingTest := tmpPath("C") - copyIn("failing_ginkgo_tests", failingTest) - }) - - It("should fail and stop running tests", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(outputLines[1]).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) - Ω(output).Should(ContainSubstring("• Failure")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - - Ω(output).Should(ContainSubstring("Summarizing 1 Failure:")) - Ω(output).Should(ContainSubstring("[Fail] FailingGinkgoTests [It] should fail")) - }) - }) - - Context("when one of the packages fails to compile", func() { - BeforeEach(func() { - doesNotCompileTest := tmpPath("C") - copyIn("does_not_compile", doesNotCompileTest) - }) - - It("should fail and stop running tests", func() { - session := startGinkgo(tmpDir, "--noColor", "-r") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(outputLines[1]).Should(ContainSubstring("Failed to compile C:")) - Ω(output).ShouldNot(ContainSubstring("More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - }) - }) - - Context("when either is the case, but the keepGoing flag is set", func() { - BeforeEach(func() { - doesNotCompileTest := tmpPath("B") - copyIn("does_not_compile", doesNotCompileTest) - - failingTest := tmpPath("C") - copyIn("failing_ginkgo_tests", failingTest) - }) - - It("should soldier on", func() { - session := startGinkgo(tmpDir, "--noColor", "-r", "-keepGoing") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - outputLines := strings.Split(output, "\n") - Ω(outputLines[0]).Should(MatchRegexp(`\[\d+\] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(outputLines[1]).Should(ContainSubstring("Failed to compile B:")) - Ω(output).Should(MatchRegexp(`\[\d+\] Failing_ginkgo_tests Suite - 2/2 specs`)) - Ω(output).Should(ContainSubstring("• Failure")) - Ω(output).Should(MatchRegexp(`\[\d+\] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS! \d+(\.\d+)?[muµ]s PASS`)) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - }) - }) - }) - - Context("when told to keep going --untilItFails", func() { - BeforeEach(func() { - copyIn("eventually_failing", tmpDir) - }) - - It("should keep rerunning the tests, until a failure occurs", func() { - session := startGinkgo(tmpDir, "--untilItFails", "--noColor") - Eventually(session).Should(gexec.Exit(1)) - Ω(session).Should(gbytes.Say("This was attempt #1")) - Ω(session).Should(gbytes.Say("This was attempt #2")) - Ω(session).Should(gbytes.Say("Tests failed on attempt #3")) - - //it should change the random seed between each test - lines := strings.Split(string(session.Out.Contents()), "\n") - randomSeeds := []string{} - for _, line := range lines { - if strings.Contains(line, "Random Seed:") { - randomSeeds = append(randomSeeds, strings.Split(line, ": ")[1]) - } - } - Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[1])) - Ω(randomSeeds[1]).ShouldNot(Equal(randomSeeds[2])) - Ω(randomSeeds[0]).ShouldNot(Equal(randomSeeds[2])) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/skip_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/skip_test.go deleted file mode 100644 index 59a12ee6815..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/skip_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Skipping Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("skipping") - copyIn("skip_fixture", pathToTest) - }) - - It("should skip in all the possible ways", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - - Ω(output).Should(ContainSubstring("a top level skip on line 9")) - Ω(output).Should(ContainSubstring("skip_fixture_test.go:9")) - Ω(output).Should(ContainSubstring("an async top level skip on line 14")) - Ω(output).Should(ContainSubstring("skip_fixture_test.go:14")) - Ω(output).Should(ContainSubstring("a top level goroutine skip on line 21")) - Ω(output).Should(ContainSubstring("skip_fixture_test.go:21")) - - Ω(output).Should(ContainSubstring("a sync SKIP")) - Ω(output).Should(ContainSubstring("an async SKIP")) - Ω(output).Should(ContainSubstring("a goroutine SKIP")) - Ω(output).Should(ContainSubstring("a measure SKIP")) - - Ω(output).Should(ContainSubstring("S [SKIPPING] in Spec Setup (BeforeEach) [")) - Ω(output).Should(ContainSubstring("a BeforeEach SKIP")) - Ω(output).Should(ContainSubstring("S [SKIPPING] in Spec Teardown (AfterEach) [")) - Ω(output).Should(ContainSubstring("an AfterEach SKIP")) - - Ω(output).Should(ContainSubstring("0 Passed | 0 Failed | 0 Pending | 9 Skipped")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go deleted file mode 100644 index 32dfa0ea94b..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/subcommand_test.go +++ /dev/null @@ -1,364 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "strings" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Subcommand", func() { - Describe("ginkgo bootstrap", func() { - var pkgPath string - BeforeEach(func() { - pkgPath = tmpPath("foo") - os.Mkdir(pkgPath, 0777) - }) - - It("should generate a bootstrap file, as long as one does not exist", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - - session = startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(1)) - output = session.Out.Contents() - Ω(output).Should(ContainSubstring("foo_suite_test.go already exists")) - }) - - It("should import nodot declarations when told to", func() { - session := startGinkgo(pkgPath, "bootstrap", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("var It = ginkgo.It")) - Ω(content).Should(ContainSubstring("var Ω = gomega.Ω")) - - Ω(content).Should(ContainSubstring("\t" + `"github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/onsi/gomega"`)) - }) - - It("should generate an agouti bootstrap file when told to", func() { - session := startGinkgo(pkgPath, "bootstrap", "--agouti") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_suite_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_test")) - Ω(content).Should(ContainSubstring("func TestFoo(t *testing.T) {")) - Ω(content).Should(ContainSubstring("RegisterFailHandler")) - Ω(content).Should(ContainSubstring("RunSpecs")) - - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/sclevine/agouti"`)) - }) - }) - - Describe("nodot", func() { - It("should update the declarations in the bootstrap file", func() { - pkgPath := tmpPath("foo") - os.Mkdir(pkgPath, 0777) - - session := startGinkgo(pkgPath, "bootstrap", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - - byteContent, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - - content := string(byteContent) - content = strings.Replace(content, "var It =", "var MyIt =", -1) - content = strings.Replace(content, "var Ω = gomega.Ω\n", "", -1) - - err = ioutil.WriteFile(filepath.Join(pkgPath, "foo_suite_test.go"), []byte(content), os.ModePerm) - Ω(err).ShouldNot(HaveOccurred()) - - session = startGinkgo(pkgPath, "nodot") - Eventually(session).Should(gexec.Exit(0)) - - byteContent, err = ioutil.ReadFile(filepath.Join(pkgPath, "foo_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(byteContent).Should(ContainSubstring("var MyIt = ginkgo.It")) - Ω(byteContent).ShouldNot(ContainSubstring("var It = ginkgo.It")) - Ω(byteContent).Should(ContainSubstring("var Ω = gomega.Ω")) - }) - }) - - Describe("ginkgo generate", func() { - var pkgPath string - - BeforeEach(func() { - pkgPath = tmpPath("foo_bar") - os.Mkdir(pkgPath, 0777) - }) - - Context("with no arguments", func() { - It("should generate a test file named after the package", func() { - session := startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("FooBar", func() {`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(1)) - output = session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go already exists")) - }) - }) - - Context("with an argument of the form: foo", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with an argument of the form: foo.go", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz.go") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - - }) - }) - - Context("with an argument of the form: foo_test", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz_test") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with an argument of the form: foo_test.go", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz_buzz_test.go") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("BazBuzz", func() {`)) - }) - }) - - Context("with multiple arguments", func() { - It("should generate a test file named after the argument", func() { - session := startGinkgo(pkgPath, "generate", "baz", "buzz") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("baz_test.go")) - Ω(output).Should(ContainSubstring("buzz_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "baz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("Baz", func() {`)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "buzz_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring(`var _ = Describe("Buzz", func() {`)) - }) - }) - - Context("with nodot", func() { - It("should not import ginkgo or gomega", func() { - session := startGinkgo(pkgPath, "generate", "--nodot") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).ShouldNot(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).ShouldNot(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - }) - }) - - Context("with agouti", func() { - It("should generate an agouti test file", func() { - session := startGinkgo(pkgPath, "generate", "--agouti") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("foo_bar_test.go")) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "foo_bar_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package foo_bar_test")) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/ginkgo"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/onsi/gomega"`)) - Ω(content).Should(ContainSubstring("\t" + `. "github.com/sclevine/agouti/matchers"`)) - Ω(content).Should(ContainSubstring("\t" + `"github.com/sclevine/agouti"`)) - Ω(content).Should(ContainSubstring("page, err = agoutiDriver.NewPage()")) - }) - }) - }) - - Describe("ginkgo bootstrap/generate", func() { - var pkgPath string - BeforeEach(func() { - pkgPath = tmpPath("some crazy-thing") - os.Mkdir(pkgPath, 0777) - }) - - Context("when the working directory is empty", func() { - It("generates correctly named bootstrap and generate files with a package name derived from the directory", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package some_crazy_thing_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing Suite")) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package some_crazy_thing_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing")) - }) - }) - - Context("when the working directory contains a file with a package name", func() { - BeforeEach(func() { - Ω(ioutil.WriteFile(filepath.Join(pkgPath, "foo.go"), []byte("package main\n\nfunc main() {}"), 0777)).Should(Succeed()) - }) - - It("generates correctly named bootstrap and generate files with the package name", func() { - session := startGinkgo(pkgPath, "bootstrap") - Eventually(session).Should(gexec.Exit(0)) - - content, err := ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_suite_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package main_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing Suite")) - - session = startGinkgo(pkgPath, "generate") - Eventually(session).Should(gexec.Exit(0)) - - content, err = ioutil.ReadFile(filepath.Join(pkgPath, "some_crazy_thing_test.go")) - Ω(err).ShouldNot(HaveOccurred()) - Ω(content).Should(ContainSubstring("package main_test")) - Ω(content).Should(ContainSubstring("SomeCrazyThing")) - }) - }) - }) - - Describe("ginkgo blur", func() { - It("should unfocus tests", func() { - pathToTest := tmpPath("focused") - copyIn("focused_fixture", pathToTest) - - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(types.GINKGO_FOCUS_EXIT_CODE)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("3 Passed")) - Ω(output).Should(ContainSubstring("3 Skipped")) - - session = startGinkgo(pathToTest, "blur") - Eventually(session).Should(gexec.Exit(0)) - - session = startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output = session.Out.Contents() - Ω(output).Should(ContainSubstring("6 Passed")) - Ω(output).Should(ContainSubstring("0 Skipped")) - }) - }) - - Describe("ginkgo version", func() { - It("should print out the version info", func() { - session := startGinkgo("", "version") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(MatchRegexp(`Ginkgo Version \d+\.\d+\.\d+`)) - }) - }) - - Describe("ginkgo help", func() { - It("should print out usage information", func() { - session := startGinkgo("", "help") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Err.Contents()) - - Ω(output).Should(MatchRegexp(`Ginkgo Version \d+\.\d+\.\d+`)) - Ω(output).Should(ContainSubstring("ginkgo watch")) - Ω(output).Should(ContainSubstring("-succinct")) - Ω(output).Should(ContainSubstring("-nodes")) - Ω(output).Should(ContainSubstring("ginkgo generate")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_command_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_command_test.go deleted file mode 100644 index 4bd46f01563..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_command_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Suite Command Specs", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("suite_command") - copyIn("suite_command_tests", pathToTest) - }) - - It("Runs command after suite echoing out suite data, properly reporting suite name and passing status in successful command output", func() { - command := "-afterSuiteHook=echo THIS IS A (ginkgo-suite-passed) TEST OF THE (ginkgo-suite-name) SYSTEM, THIS IS ONLY A TEST" - expected := "THIS IS A [PASS] TEST OF THE suite_command SYSTEM, THIS IS ONLY A TEST" - session := startGinkgo(pathToTest, command) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("1 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("0 Skipped")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - Ω(output).Should(ContainSubstring("Post-suite command succeeded:")) - Ω(output).Should(ContainSubstring(expected)) - }) - - It("Runs command after suite reporting that command failed", func() { - command := "-afterSuiteHook=exit 1" - session := startGinkgo(pathToTest, command) - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("1 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("0 Skipped")) - Ω(output).Should(ContainSubstring("Test Suite Passed")) - Ω(output).Should(ContainSubstring("Post-suite command failed:")) - }) - - It("Runs command after suite echoing out suite data, properly reporting suite name and failing status in successful command output", func() { - command := "-afterSuiteHook=echo THIS IS A (ginkgo-suite-passed) TEST OF THE (ginkgo-suite-name) SYSTEM, THIS IS ONLY A TEST" - expected := "THIS IS A [FAIL] TEST OF THE suite_command SYSTEM, THIS IS ONLY A TEST" - session := startGinkgo(pathToTest, "-failOnPending=true", command) - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("1 Passed")) - Ω(output).Should(ContainSubstring("0 Failed")) - Ω(output).Should(ContainSubstring("1 Pending")) - Ω(output).Should(ContainSubstring("0 Skipped")) - Ω(output).Should(ContainSubstring("Test Suite Failed")) - Ω(output).Should(ContainSubstring("Post-suite command succeeded:")) - Ω(output).Should(ContainSubstring(expected)) - }) - -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go deleted file mode 100644 index b9313db59ab..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/suite_setup_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package integration_test - -import ( - "strings" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("SuiteSetup", func() { - var pathToTest string - - Context("when the BeforeSuite and AfterSuite pass", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("passing_suite_setup", pathToTest) - }) - - It("should run the BeforeSuite once, then run all the tests", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - }) - - It("should run the BeforeSuite once per parallel node, then run all the tests", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("failing_before_suite", pathToTest) - }) - - It("should run the BeforeSuite once, none of the tests, but it should run the AfterSuite", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - }) - - It("should run the BeforeSuite once per parallel node, none of the tests, but it should run the AfterSuite for each node", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - Ω(output).ShouldNot(ContainSubstring("NEVER SEE THIS")) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("failing_after_suite", pathToTest) - }) - - It("should run the BeforeSuite once, none of the tests, but it should run the AfterSuite", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(1)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(1)) - Ω(strings.Count(output, "A TEST")).Should(Equal(2)) - }) - - It("should run the BeforeSuite once per parallel node, none of the tests, but it should run the AfterSuite for each node", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=2") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(strings.Count(output, "BEFORE SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "AFTER SUITE")).Should(Equal(2)) - Ω(strings.Count(output, "Test Panicked")).Should(Equal(2)) - Ω(strings.Count(output, "A TEST")).Should(Equal(2)) - }) - }) - - Context("With passing synchronized before and after suites", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("synchronized_setup_tests", pathToTest) - }) - - Context("when run with one node", func() { - It("should do all the work on that one node", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("BEFORE_A_1\nBEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("AFTER_A_1\nAFTER_B_1")) - }) - }) - - Context("when run across multiple nodes", func() { - It("should run the first BeforeSuite function (BEFORE_A) on node 1, the second (BEFORE_B) on all the nodes, the first AfterSuite (AFTER_A) on all the nodes, and then the second (AFTER_B) on Node 1 *after* everything else is finished", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("BEFORE_A_1")) - Ω(output).Should(ContainSubstring("BEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("BEFORE_B_2: DATA")) - Ω(output).Should(ContainSubstring("BEFORE_B_3: DATA")) - - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_2")) - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_3")) - - Ω(output).Should(ContainSubstring("AFTER_A_1")) - Ω(output).Should(ContainSubstring("AFTER_A_2")) - Ω(output).Should(ContainSubstring("AFTER_A_3")) - Ω(output).Should(ContainSubstring("AFTER_B_1")) - - Ω(output).ShouldNot(ContainSubstring("AFTER_B_2")) - Ω(output).ShouldNot(ContainSubstring("AFTER_B_3")) - }) - }) - - Context("when streaming across multiple nodes", func() { - It("should run the first BeforeSuite function (BEFORE_A) on node 1, the second (BEFORE_B) on all the nodes, the first AfterSuite (AFTER_A) on all the nodes, and then the second (AFTER_B) on Node 1 *after* everything else is finished", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3", "--stream") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("[1] BEFORE_A_1")) - Ω(output).Should(ContainSubstring("[1] BEFORE_B_1: DATA")) - Ω(output).Should(ContainSubstring("[2] BEFORE_B_2: DATA")) - Ω(output).Should(ContainSubstring("[3] BEFORE_B_3: DATA")) - - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_2")) - Ω(output).ShouldNot(ContainSubstring("BEFORE_A_3")) - - Ω(output).Should(ContainSubstring("[1] AFTER_A_1")) - Ω(output).Should(ContainSubstring("[2] AFTER_A_2")) - Ω(output).Should(ContainSubstring("[3] AFTER_A_3")) - Ω(output).Should(ContainSubstring("[1] AFTER_B_1")) - - Ω(output).ShouldNot(ContainSubstring("AFTER_B_2")) - Ω(output).ShouldNot(ContainSubstring("AFTER_B_3")) - }) - }) - }) - - Context("With a failing synchronized before suite", func() { - BeforeEach(func() { - pathToTest = tmpPath("suite_setup") - copyIn("exiting_synchronized_setup_tests", pathToTest) - }) - - It("should fail and let the user know that node 1 disappeared prematurely", func() { - session := startGinkgo(pathToTest, "--noColor", "--nodes=3") - Eventually(session).Should(gexec.Exit(1)) - output := string(session.Out.Contents()) - - Ω(output).Should(ContainSubstring("Node 1 disappeared before completing BeforeSuite")) - Ω(output).Should(ContainSubstring("Ginkgo timed out waiting for all parallel nodes to report back!")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go deleted file mode 100644 index 626635bf5c5..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/tags_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Tags", func() { - var pathToTest string - BeforeEach(func() { - pathToTest = tmpPath("tags") - copyIn("tags_tests", pathToTest) - }) - - It("should honor the passed in -tags flag", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Ran 1 of 1 Specs")) - - session = startGinkgo(pathToTest, "--noColor", "-tags=complex_tests") - Eventually(session).Should(gexec.Exit(0)) - output = string(session.Out.Contents()) - Ω(output).Should(ContainSubstring("Ran 3 of 3 Specs")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go deleted file mode 100644 index 70a8f04ef0c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/test_description_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("TestDescription", func() { - var pathToTest string - - BeforeEach(func() { - pathToTest = tmpPath("test_description") - copyIn("test_description", pathToTest) - }) - - It("should capture and emit information about the current test", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(1)) - - Ω(session).Should(gbytes.Say("TestDescription should pass:false")) - Ω(session).Should(gbytes.Say("TestDescription should fail:true")) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go deleted file mode 100644 index 470affdf7c6..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/verbose_and_succinct_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package integration_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Verbose And Succinct Mode", func() { - var pathToTest string - var otherPathToTest string - - Context("when running one package", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - }) - - It("should default to non-succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor") - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - }) - }) - - Context("when running more than one package", func() { - BeforeEach(func() { - pathToTest = tmpPath("ginkgo") - copyIn("passing_ginkgo_tests", pathToTest) - otherPathToTest = tmpPath("more_ginkgo") - copyIn("more_ginkgo_tests", otherPathToTest) - }) - - Context("with no flags set", func() { - It("should default to succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("] Passing_ginkgo_tests Suite - 4/4 specs •••• SUCCESS!")) - Ω(output).Should(ContainSubstring("] More_ginkgo_tests Suite - 2/2 specs •• SUCCESS!")) - }) - }) - - Context("with --succinct=false", func() { - It("should not be in succinct mode", func() { - session := startGinkgo(pathToTest, "--noColor", "--succinct=false", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - }) - }) - - Context("with -v", func() { - It("should not be in succinct mode, but should be verbose", func() { - session := startGinkgo(pathToTest, "--noColor", "-v", pathToTest, otherPathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("Running Suite: Passing_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("Running Suite: More_ginkgo_tests Suite")) - Ω(output).Should(ContainSubstring("should proxy strings")) - Ω(output).Should(ContainSubstring("should always pass")) - }) - - It("should emit output from Bys", func() { - session := startGinkgo(pathToTest, "--noColor", "-v", pathToTest) - Eventually(session).Should(gexec.Exit(0)) - output := session.Out.Contents() - - Ω(output).Should(ContainSubstring("emitting one By")) - Ω(output).Should(ContainSubstring("emitting another By")) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go deleted file mode 100644 index bbbcf36aa98..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/integration/watch_test.go +++ /dev/null @@ -1,239 +0,0 @@ -package integration_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Watch", func() { - var rootPath string - var pathA string - var pathB string - var pathC string - var session *gexec.Session - - BeforeEach(func() { - rootPath = tmpPath("root") - pathA = filepath.Join(rootPath, "src", "github.com", "onsi", "A") - pathB = filepath.Join(rootPath, "src", "github.com", "onsi", "B") - pathC = filepath.Join(rootPath, "src", "github.com", "onsi", "C") - - err := os.MkdirAll(pathA, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - err = os.MkdirAll(pathB, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - err = os.MkdirAll(pathC, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - copyIn(filepath.Join("watch_fixtures", "A"), pathA) - copyIn(filepath.Join("watch_fixtures", "B"), pathB) - copyIn(filepath.Join("watch_fixtures", "C"), pathC) - }) - - startGinkgoWithGopath := func(args ...string) *gexec.Session { - cmd := ginkgoCommand(rootPath, args...) - cmd.Env = append([]string{"GOPATH=" + rootPath + ":" + os.Getenv("GOPATH")}, os.Environ()...) - session, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - return session - } - - modifyFile := func(path string) { - time.Sleep(time.Second) - content, err := ioutil.ReadFile(path) - Ω(err).ShouldNot(HaveOccurred()) - content = append(content, []byte("//")...) - err = ioutil.WriteFile(path, content, 0666) - Ω(err).ShouldNot(HaveOccurred()) - } - - modifyCode := func(pkgToModify string) { - modifyFile(filepath.Join(rootPath, "src", "github.com", "onsi", pkgToModify, pkgToModify+".go")) - } - - modifyTest := func(pkgToModify string) { - modifyFile(filepath.Join(rootPath, "src", "github.com", "onsi", pkgToModify, pkgToModify+"_test.go")) - } - - AfterEach(func() { - if session != nil { - session.Kill().Wait() - } - }) - - It("should be set up correctly", func() { - session = startGinkgoWithGopath("-r") - Eventually(session).Should(gexec.Exit(0)) - Ω(session.Out.Contents()).Should(ContainSubstring("A Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("B Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("C Suite")) - Ω(session.Out.Contents()).Should(ContainSubstring("Ginkgo ran 3 suites")) - }) - - Context("when watching just one test suite", func() { - It("should immediately run, and should rerun when the test suite changes", func() { - session = startGinkgoWithGopath("watch", "-succinct", pathA) - Eventually(session).Should(gbytes.Say("A Suite")) - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - session.Kill().Wait() - }) - }) - - Context("when watching several test suites", func() { - It("should not immediately run, but should rerun a test when its code changes", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite|C Suite")) - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - session.Kill().Wait() - }) - }) - - Describe("watching dependencies", func() { - Context("with a depth of 2", func() { - It("should watch down to that depth", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=2") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[2 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - }) - }) - - Context("with a depth of 1", func() { - It("should watch down to that depth", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=1") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite")) - }) - }) - - Context("with a depth of 0", func() { - It("should not watch any dependencies", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=0") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[0 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[0 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyCode("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyCode("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|C Suite")) - - modifyCode("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite")) - }) - }) - - It("should not trigger dependents when tests are changed", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r", "-depth=2") - Eventually(session).Should(gbytes.Say("Identified 3 test suites")) - Eventually(session).Should(gbytes.Say(`A \[2 dependencies\]`)) - Eventually(session).Should(gbytes.Say(`B \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say(`C \[0 dependencies\]`)) - - modifyTest("A") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("A Suite")) - Consistently(session).ShouldNot(gbytes.Say("B Suite|C Suite")) - - modifyTest("B") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("B Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|C Suite")) - - modifyTest("C") - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Consistently(session).ShouldNot(gbytes.Say("A Suite|B Suite")) - }) - }) - - Describe("when new test suite is added", func() { - It("should start monitoring that test suite", func() { - session = startGinkgoWithGopath("watch", "-succinct", "-r") - - Eventually(session).Should(gbytes.Say("Watching 3 suites")) - - pathD := filepath.Join(rootPath, "src", "github.com", "onsi", "D") - - err := os.MkdirAll(pathD, 0700) - Ω(err).ShouldNot(HaveOccurred()) - - copyIn(filepath.Join("watch_fixtures", "D"), pathD) - - Eventually(session).Should(gbytes.Say("Detected 1 new suite")) - Eventually(session).Should(gbytes.Say(`D \[1 dependency\]`)) - Eventually(session).Should(gbytes.Say("D Suite")) - - modifyCode("D") - - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("D Suite")) - - modifyCode("C") - - Eventually(session).Should(gbytes.Say("Detected changes in")) - Eventually(session).Should(gbytes.Say("C Suite")) - Eventually(session).Should(gbytes.Say("D Suite")) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go deleted file mode 100644 index f06abf3c560..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCodelocation(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "CodeLocation Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go deleted file mode 100644 index 55a9e9d036c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "runtime" -) - -var _ = Describe("CodeLocation", func() { - var ( - codeLocation types.CodeLocation - expectedFileName string - expectedLineNumber int - ) - - caller0 := func() { - codeLocation = codelocation.New(1) - } - - caller1 := func() { - _, expectedFileName, expectedLineNumber, _ = runtime.Caller(0) - expectedLineNumber += 2 - caller0() - } - - BeforeEach(func() { - caller1() - }) - - It("should use the passed in skip parameter to pick out the correct file & line number", func() { - Ω(codeLocation.FileName).Should(Equal(expectedFileName)) - Ω(codeLocation.LineNumber).Should(Equal(expectedLineNumber)) - }) - - Describe("stringer behavior", func() { - It("should stringify nicely", func() { - Ω(codeLocation.String()).Should(ContainSubstring("code_location_test.go:%d", expectedLineNumber)) - }) - }) - - //There's no better way than to test this private method as it - //goes out of its way to prune out ginkgo related code in the stack trace - Describe("PruneStack", func() { - It("should remove any references to ginkgo and pkg/testing and pkg/runtime", func() { - input := `/Skip/me -Skip: skip() -/Skip/me -Skip: skip() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever.go:10 (0x12314) -Something: Func() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever_else.go:10 (0x12314) -SomethingInternalToGinkgo: Func() -/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite") -/usr/goroot/pkg/testing/testing.go:12 (0x37f08) -TestingT: Blah() -/usr/goroot/pkg/runtime/runtime.go:12 (0x37f08) -Something: Func() -` - prunedStack := codelocation.PruneStack(input, 1) - Ω(prunedStack).Should(Equal(`/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite")`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go deleted file mode 100644 index c6fc314ff57..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package containernode_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestContainernode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Containernode Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go deleted file mode 100644 index b8d61b13fc2..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package containernode_test - -import ( - "github.com/onsi/ginkgo/internal/leafnodes" - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - . "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Container Node", func() { - var ( - codeLocation types.CodeLocation - container *ContainerNode - ) - - BeforeEach(func() { - codeLocation = codelocation.New(0) - container = New("description text", types.FlagTypeFocused, codeLocation) - }) - - Describe("creating a container node", func() { - It("can answer questions about itself", func() { - Ω(container.Text()).Should(Equal("description text")) - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(container.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("pushing setup nodes", func() { - It("can append setup nodes of various types and fetch them by type", func() { - befA := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - befB := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftA := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftB := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefA := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefB := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - - container.PushSetupNode(befA) - container.PushSetupNode(befB) - container.PushSetupNode(aftA) - container.PushSetupNode(aftB) - container.PushSetupNode(jusBefA) - container.PushSetupNode(jusBefB) - - subject := leafnodes.NewItNode("subject", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(subject) - - Ω(container.SetupNodesOfType(types.SpecComponentTypeBeforeEach)).Should(Equal([]leafnodes.BasicNode{befA, befB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeAfterEach)).Should(Equal([]leafnodes.BasicNode{aftA, aftB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach)).Should(Equal([]leafnodes.BasicNode{jusBefA, jusBefB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeIt)).Should(BeEmpty()) //subjects are not setup nodes - }) - }) - - Context("With appended containers and subject nodes", func() { - var ( - itA, itB, innerItA, innerItB leafnodes.SubjectNode - innerContainer *ContainerNode - ) - - BeforeEach(func() { - itA = leafnodes.NewItNode("Banana", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - itB = leafnodes.NewItNode("Apple", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerItB = leafnodes.NewItNode("inner B", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - - container.PushSubjectNode(itA) - container.PushContainerNode(innerContainer) - innerContainer.PushSubjectNode(innerItA) - innerContainer.PushSubjectNode(innerItB) - container.PushSubjectNode(itB) - }) - - Describe("Collating", func() { - It("should return a collated set of containers and subject nodes in the correct order", func() { - collated := container.Collate() - Ω(collated).Should(HaveLen(4)) - - Ω(collated[0]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itA, - })) - - Ω(collated[1]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItA, - })) - - Ω(collated[2]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItB, - })) - - Ω(collated[3]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itB, - })) - }) - }) - - Describe("Backpropagating Programmatic Focus", func() { - //This allows inner focused specs to override the focus of outer focussed - //specs and more closely maps to what a developer wants to happen - //when debugging a test suite - - Context("when a parent is focused *and* an inner subject is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - - Context("when a parent is focused *and* an inner container is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeFocused, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeNone)) - }) - }) - - Context("when a parent is pending and a child is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypePending, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should not do anything", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypePending)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - }) - - Describe("Shuffling", func() { - var unshuffledCollation []CollatedNodes - BeforeEach(func() { - unshuffledCollation = container.Collate() - - r := rand.New(rand.NewSource(17)) - container.Shuffle(r) - }) - - It("should sort, and then shuffle, the top level contents of the container", func() { - shuffledCollation := container.Collate() - Ω(shuffledCollation).Should(HaveLen(len(unshuffledCollation))) - Ω(shuffledCollation).ShouldNot(Equal(unshuffledCollation)) - - for _, entry := range unshuffledCollation { - Ω(shuffledCollation).Should(ContainElement(entry)) - } - - innerAIndex, innerBIndex := 0, 0 - for i, entry := range shuffledCollation { - if entry.Subject == innerItA { - innerAIndex = i - } else if entry.Subject == innerItB { - innerBIndex = i - } - } - - Ω(innerAIndex).Should(Equal(innerBIndex - 1)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go deleted file mode 100644 index 8dce7be9ac5..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFailer(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Failer Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go deleted file mode 100644 index 65210a40a7c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/failer/failer_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/failer" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Failer", func() { - var ( - failer *Failer - codeLocationA types.CodeLocation - codeLocationB types.CodeLocation - ) - - BeforeEach(func() { - codeLocationA = codelocation.New(0) - codeLocationB = codelocation.New(0) - failer = New() - }) - - Context("with no failures", func() { - It("should return success when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) - - Describe("Skip", func() { - It("should handle failures", func() { - failer.Skip("something skipped", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something skipped", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("Fail", func() { - It("should handle failures", func() { - failer.Fail("something failed", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - }) - - Describe("Panic", func() { - It("should handle panics", func() { - failer.Panic(codeLocationA, "some forwarded panic") - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Test Panicked", - Location: codeLocationA, - ForwardedPanic: "some forwarded panic", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStatePanicked)) - }) - }) - - Describe("Timeout", func() { - It("should handle timeouts", func() { - failer.Timeout(codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when multiple failures are registered", func() { - BeforeEach(func() { - failer.Fail("something failed", codeLocationA) - failer.Fail("something else failed", codeLocationA) - }) - - It("should only report the first one when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report subsequent failures after being drained", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failer.Fail("yet another thing failed", codeLocationA) - - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "yet another thing failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report sucess on subsequent drains if no errors occur", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go deleted file mode 100644 index 29fa0c6e2a6..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("It Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - it := NewItNode("my it node", func() {}, types.FlagTypeFocused, codeLocation, 0, nil, 3) - Ω(it.Type()).Should(Equal(types.SpecComponentTypeIt)) - Ω(it.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(it.Text()).Should(Equal("my it node")) - Ω(it.CodeLocation()).Should(Equal(codeLocation)) - Ω(it.Samples()).Should(Equal(1)) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go deleted file mode 100644 index a7ba9e006ee..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestLeafNode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "LeafNode Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go deleted file mode 100644 index 4dcd00bb362..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("Measure Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - measure := NewMeasureNode("my measure node", func(b Benchmarker) {}, types.FlagTypeFocused, codeLocation, 10, nil, 3) - Ω(measure.Type()).Should(Equal(types.SpecComponentTypeMeasure)) - Ω(measure.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(measure.Text()).Should(Equal("my measure node")) - Ω(measure.CodeLocation()).Should(Equal(codeLocation)) - Ω(measure.Samples()).Should(Equal(10)) - }) - - Describe("benchmarking", func() { - var measure *MeasureNode - - Describe("Value", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.RecordValue("foo", 7, "info!") - b.RecordValue("foo", 2) - b.RecordValue("foo", 3) - b.RecordValue("bar", 0.3) - b.RecordValue("bar", 0.1) - b.RecordValue("bar", 0.5) - b.RecordValue("bar", 0.7) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(2)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].Order).Should(Equal(0)) - Ω(report["foo"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["foo"].LargestLabel).Should(Equal(" Largest")) - Ω(report["foo"].AverageLabel).Should(Equal(" Average")) - Ω(report["foo"].Units).Should(Equal("")) - Ω(report["foo"].Results).Should(Equal([]float64{7, 2, 3})) - Ω(report["foo"].Smallest).Should(BeNumerically("==", 2)) - Ω(report["foo"].Largest).Should(BeNumerically("==", 7)) - Ω(report["foo"].Average).Should(BeNumerically("==", 4)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 2.16, 0.01)) - - Ω(report["bar"].Name).Should(Equal("bar")) - Ω(report["bar"].Info).Should(BeNil()) - Ω(report["bar"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["bar"].Order).Should(Equal(1)) - Ω(report["bar"].LargestLabel).Should(Equal(" Largest")) - Ω(report["bar"].AverageLabel).Should(Equal(" Average")) - Ω(report["bar"].Units).Should(Equal("")) - Ω(report["bar"].Results).Should(Equal([]float64{0.3, 0.1, 0.5, 0.7})) - Ω(report["bar"].Smallest).Should(BeNumerically("==", 0.1)) - Ω(report["bar"].Largest).Should(BeNumerically("==", 0.7)) - Ω(report["bar"].Average).Should(BeNumerically("==", 0.4)) - Ω(report["bar"].StdDeviation).Should(BeNumerically("~", 0.22, 0.01)) - }) - }) - - Describe("Time", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.Time("foo", func() { - time.Sleep(100 * time.Millisecond) - }, "info!") - b.Time("foo", func() { - time.Sleep(200 * time.Millisecond) - }) - b.Time("foo", func() { - time.Sleep(170 * time.Millisecond) - }) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(1)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].SmallestLabel).Should(Equal("Fastest Time")) - Ω(report["foo"].LargestLabel).Should(Equal("Slowest Time")) - Ω(report["foo"].AverageLabel).Should(Equal("Average Time")) - Ω(report["foo"].Units).Should(Equal("s")) - Ω(report["foo"].Results).Should(HaveLen(3)) - Ω(report["foo"].Results[0]).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Results[1]).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Results[2]).Should(BeNumerically("~", 0.17, 0.01)) - Ω(report["foo"].Smallest).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Largest).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Average).Should(BeNumerically("~", 0.16, 0.01)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 0.04, 0.01)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go deleted file mode 100644 index d5b9251f652..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "github.com/onsi/ginkgo/internal/codelocation" -) - -var _ = Describe("Setup Nodes", func() { - Describe("BeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - beforeEach := NewBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(beforeEach.Type()).Should(Equal(types.SpecComponentTypeBeforeEach)) - Ω(beforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("AfterEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - afterEach := NewAfterEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(afterEach.Type()).Should(Equal(types.SpecComponentTypeAfterEach)) - Ω(afterEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("JustBeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - justBeforeEach := NewJustBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(justBeforeEach.Type()).Should(Equal(types.SpecComponentTypeJustBeforeEach)) - Ω(justBeforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go deleted file mode 100644 index f27fc55e148..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go +++ /dev/null @@ -1,361 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "reflect" - "runtime" - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type runnable interface { - Run() (outcome types.SpecState, failure types.SpecFailure) - CodeLocation() types.CodeLocation -} - -func SynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("synchronous functions", func() { - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - }, 0, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when a failure occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - failer.Fail("bam", innerCodeLocation) - panic("should not matter") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when a panic occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - - Context("when a panic occurs with a nil value", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic(nil) - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the nil-valued panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("")) - }) - }) - - }) -} - -func AsynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("asynchronous functions", func() { - var timeoutDuration time.Duration - - BeforeEach(func() { - timeoutDuration = time.Duration(1 * float64(time.Second)) - }) - - Context("when running", func() { - It("should run the function as a goroutine, and block until it's done", func() { - initialNumberOfGoRoutines := runtime.NumGoroutine() - numberOfGoRoutines := 0 - - build(func(done Done) { - didRun = true - numberOfGoRoutines = runtime.NumGoroutine() - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - - Ω(didRun).Should(BeTrue()) - Ω(numberOfGoRoutines).Should(BeNumerically(">=", initialNumberOfGoRoutines+1)) - }) - }) - - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when the function fails", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - failer.Fail("bam", innerCodeLocation) - time.Sleep(20 * time.Millisecond) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function times out", func() { - var guard chan struct{} - - BeforeEach(func() { - guard = make(chan struct{}) - outcome, failure = build(func(done Done) { - didRun = true - time.Sleep(20 * time.Millisecond) - close(guard) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the timeout", func() { - <-guard - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateTimedOut)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: componentCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function panics", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - - Context("when the function panics with a nil value", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic(nil) - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the nil-valued panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("")) - }) - }) - }) -} - -func InvalidSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType) { - var ( - failer *Failer.Failer - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Describe("invalid functions", func() { - Context("when passed something that's not a function", func() { - It("should panic", func() { - Ω(func() { - build("not a function", 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes the wrong kind of argument", func() { - It("should panic", func() { - Ω(func() { - build(func(oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes more than one argument", func() { - It("should panic", func() { - Ω(func() { - build(func(done Done, oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - }) -} - -var _ = Describe("Shared RunnableNode behavior", func() { - Describe("It Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewItNode("", body, types.FlagTypeFocused, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeIt) - }) - - Describe("Measure Nodes", func() { - build := func(body interface{}, _ time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewMeasureNode("", func(Benchmarker) { - reflect.ValueOf(body).Call([]reflect.Value{}) - }, types.FlagTypeFocused, componentCodeLocation, 10, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeMeasure, 3) - }) - - Describe("BeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach) - }) - - Describe("AfterEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewAfterEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach) - }) - - Describe("JustBeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewJustBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go deleted file mode 100644 index 246b329fe2b..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("SuiteNodes", func() { - Describe("BeforeSuite nodes", func() { - var befSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(befSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - - Describe("AfterSuite nodes", func() { - var aftSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(aftSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go deleted file mode 100644 index 4266a4bce6c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "sync" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "time" -) - -var _ = Describe("SynchronizedAfterSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - var things []string - var lock *sync.Mutex - - BeforeEach(func() { - things = []string{} - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - lock = &sync.Mutex{} - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - ranThing := func(thing string) { - lock.Lock() - defer lock.Unlock() - things = append(things, thing) - } - - thingsThatRan := func() []string { - lock.Lock() - defer lock.Unlock() - return things - } - - Context("when not running in parallel", func() { - Context("when all is well", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - failer.Fail("bam", innerCodeLocation) - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should still run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - failer.Fail("bam", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run all the things", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - }) - - Context("when running in parallel", func() { - Context("as the first node", func() { - BeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request1") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request2") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request3") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{true}), - )) - - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 3, server.URL()) - }) - - It("should run A and, when the server says its time, run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "Request1", "Request2", "Request3", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("as any other node", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(2, 3, server.URL()) - }) - - It("should run A, and not run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A"})) - }) - - It("should not talk to the server", func() { - Ω(server.ReceivedRequests()).Should(BeEmpty()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go deleted file mode 100644 index dbf2426748a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go +++ /dev/null @@ -1,445 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("SynchronizedBeforeSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - - BeforeEach(func() { - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - Describe("when not running in parallel", func() { - Context("when all is well", func() { - var data []byte - BeforeEach(func() { - data = nil - - node = newNode(func() []byte { - return []byte("my data") - }, func(d []byte) { - data = d - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B passing the output from A to B", func() { - Ω(data).Should(Equal([]byte("my data"))) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func() []byte { - failer.Fail("boom", innerCodeLocation) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte) { - failer.Fail("boom", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when A times out", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func(Done) []byte { - time.Sleep(time.Second) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when B times out", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte, Done) { - time.Sleep(time.Second) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - }) - - Describe("when running in parallel", func() { - var ranB bool - var parallelNode, parallelTotal int - BeforeEach(func() { - ranB = false - parallelNode, parallelTotal = 1, 3 - }) - - Context("as the first node, it runs A", func() { - var expectedState types.RemoteBeforeSuiteData - - BeforeEach(func() { - parallelNode, parallelTotal = 1, 3 - }) - - JustBeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("POST", "/BeforeSuiteState"), - ghttp.VerifyJSONRepresenting(expectedState), - )) - - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - Context("when A succeeds", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - - node = newNode(func() []byte { - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A succeeding", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should run B", func() { - Ω(ranB).Should(BeTrue()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateFailed} - - node = newNode(func() []byte { - panic("BAM") - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A failing", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - }) - }) - }) - - Context("as the Nth node", func() { - var statusCode int - var response interface{} - var ranA bool - var bData []byte - - BeforeEach(func() { - ranA = false - bData = nil - - statusCode = http.StatusOK - - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWithJSONEncodedPtr(&statusCode, &response), - )) - - node = newNode(func() []byte { - ranA = true - return nil - }, func(data []byte) { - bData = data - }) - - parallelNode, parallelTotal = 2, 3 - }) - - Context("when A on node1 succeeds", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should run B when the polling succeeds", func() { - Ω(bData).Should(Equal([]byte("my data"))) - }) - - It("should succeed", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - }) - }) - - Context("when A on node1 fails", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateFailed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("BeforeSuite on Node 1 failed")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when node1 disappears", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateDisappeared} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("Node 1 disappeared before completing BeforeSuite")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - }) - - Describe("construction", func() { - Describe("the first function", func() { - Context("when the first function returns a byte array", func() { - Context("and takes nothing", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes a done function", func() { - It("should be fine", func() { - Ω(func() { - newNode(func(Done) []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes more than one thing", func() { - It("should panic", func() { - Ω(func() { - newNode(func(Done, Done) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - - Context("and takes something else", func() { - It("should panic", func() { - Ω(func() { - newNode(func(bool) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Context("when the first function does not return a byte array", func() { - It("should panic", func() { - Ω(func() { - newNode(func() {}, func([]byte) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []int { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Describe("the second function", func() { - Context("when the second function takes a byte array", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("when it also takes a done channel", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, Done) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("if it takes anything else", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, chan bool) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []byte { return nil }, func(string) {}) - }).Should(Panic()) - }) - }) - - Context("if it takes nothing at all", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func() {}) - }).Should(Panic()) - }) - }) - - Context("if it returns something", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) []byte { return nil }) - }).Should(Panic()) - }) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go deleted file mode 100644 index 377a016d6cc..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/aggregator_test.go +++ /dev/null @@ -1,311 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("Aggregator", func() { - var ( - aggregator *Aggregator - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - result chan bool - - ginkgoConfig1 config.GinkgoConfigType - ginkgoConfig2 config.GinkgoConfigType - - suiteSummary1 *types.SuiteSummary - suiteSummary2 *types.SuiteSummary - - beforeSummary *types.SetupSummary - afterSummary *types.SetupSummary - specSummary *types.SpecSummary - - suiteDescription string - ) - - BeforeEach(func() { - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Succinct: false, - Verbose: true, - } - stenographer = st.NewFakeStenographer() - result = make(chan bool, 1) - aggregator = NewAggregator(2, result, reporterConfig, stenographer) - - // - // now set up some fixture data - // - - ginkgoConfig1 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 1, - ParallelTotal: 2, - } - - ginkgoConfig2 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 2, - ParallelTotal: 2, - } - - suiteDescription = "My Parallel Suite" - - suiteSummary1 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 17, - NumberOfSpecsThatWillBeRun: 15, - NumberOfPendingSpecs: 1, - NumberOfSkippedSpecs: 1, - } - - suiteSummary2 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 13, - NumberOfSpecsThatWillBeRun: 8, - NumberOfPendingSpecs: 2, - NumberOfSkippedSpecs: 3, - } - - beforeSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "BeforeSuiteOutput", - } - - afterSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "AfterSuiteOutput", - } - - specSummary = &types.SpecSummary{ - State: types.SpecStatePassed, - CapturedOutput: "SpecOutput", - } - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - beginSuite := func() { - stenographer.Reset() - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return len(stenographer.Calls()) - }).Should(BeNumerically(">=", 3)) - } - - Describe("Announcing the beginning of the suite", func() { - Context("When one of the parallel-suites starts", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites have started", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(3)) - }) - - It("should announce the beginning of the suite", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", suiteDescription, ginkgoConfig1.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 23, 30, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceAggregatedParallelRun", 2, false))) - }) - }) - }) - - Describe("Announcing specs and before suites", func() { - Context("when the parallel-suites have not all started", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.AfterSuiteDidRun(afterSummary) - aggregator.SpecDidComplete(specSummary) - }) - - It("should not announce any specs", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - Context("when the parallel-suites subsequently start", func() { - BeforeEach(func() { - beginSuite() - }) - - It("should announce the specs, the before suites and the after suites", func() { - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(ContainElement(call("AnnounceSuccesfulSpec", specSummary))) - - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - - Context("When the parallel-suites have all started", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.SpecDidComplete(specSummary) - aggregator.AfterSuiteDidRun(afterSummary) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(5)) - }) - - It("should announce the captured output of the BeforeSuite", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - }) - - It("should announce that the spec will run (when in verbose mode)", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecWillRun", specSummary))) - }) - - It("should announce the captured stdout of the spec", func() { - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceCapturedOutput", specSummary.CapturedOutput))) - }) - - It("should announce completion", func() { - Ω(stenographer.Calls()[3]).Should(Equal(call("AnnounceSuccesfulSpec", specSummary))) - }) - - It("should announce the captured output of the AfterSuite", func() { - Ω(stenographer.Calls()[4]).Should(Equal(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - }) - - Describe("Announcing the end of the suite", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When one of the parallel-suites ends", func() { - BeforeEach(func() { - aggregator.SpecSuiteDidEnd(suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - It("should not notify the channel", func() { - Ω(result).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites end", func() { - BeforeEach(func() { - time.Sleep(200 * time.Millisecond) - - suiteSummary1.SuiteSucceeded = true - suiteSummary1.NumberOfPassedSpecs = 15 - suiteSummary1.NumberOfFailedSpecs = 0 - suiteSummary2.SuiteSucceeded = false - suiteSummary2.NumberOfPassedSpecs = 5 - suiteSummary2.NumberOfFailedSpecs = 3 - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should announce the end of the suite", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - Ω(compositeSummary.NumberOfSpecsThatWillBeRun).Should(Equal(23)) - Ω(compositeSummary.NumberOfTotalSpecs).Should(Equal(30)) - Ω(compositeSummary.NumberOfPassedSpecs).Should(Equal(20)) - Ω(compositeSummary.NumberOfFailedSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfPendingSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfSkippedSpecs).Should(Equal(4)) - Ω(compositeSummary.RunTime.Seconds()).Should(BeNumerically(">", 0.2)) - }) - }) - - Context("when all the parallel-suites pass", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = true - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report success", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeTrue()) - }) - - It("should notify the channel that it succeded", func(done Done) { - Ω(<-result).Should(BeTrue()) - close(done) - }) - }) - - Context("when one of the parallel-suites fails", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = false - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report failure", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - }) - - It("should notify the channel that it failed", func(done Done) { - Ω(<-result).Should(BeFalse()) - close(done) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go deleted file mode 100644 index a928f93d311..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package remote_test - -type fakeOutputInterceptor struct { - DidStartInterceptingOutput bool - DidStopInterceptingOutput bool - InterceptedOutput string -} - -func (interceptor *fakeOutputInterceptor) StartInterceptingOutput() error { - interceptor.DidStartInterceptingOutput = true - return nil -} - -func (interceptor *fakeOutputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - interceptor.DidStopInterceptingOutput = true - return interceptor.InterceptedOutput, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go deleted file mode 100644 index 3543c59c64c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package remote_test - -import ( - "io" - "io/ioutil" - "net/http" -) - -type post struct { - url string - bodyType string - bodyContent []byte -} - -type fakePoster struct { - posts []post -} - -func newFakePoster() *fakePoster { - return &fakePoster{ - posts: make([]post, 0), - } -} - -func (poster *fakePoster) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { - bodyContent, _ := ioutil.ReadAll(body) - poster.posts = append(poster.posts, post{ - url: url, - bodyType: bodyType, - bodyContent: bodyContent, - }) - return nil, nil -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go deleted file mode 100644 index e5f3b1e3071..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package remote_test - -import ( - "encoding/json" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("ForwardingReporter", func() { - var ( - reporter *ForwardingReporter - interceptor *fakeOutputInterceptor - poster *fakePoster - suiteSummary *types.SuiteSummary - specSummary *types.SpecSummary - setupSummary *types.SetupSummary - serverHost string - ) - - BeforeEach(func() { - serverHost = "http://127.0.0.1:7788" - - poster = newFakePoster() - - interceptor = &fakeOutputInterceptor{ - InterceptedOutput: "The intercepted output!", - } - - reporter = NewForwardingReporter(serverHost, poster, interceptor) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - Context("When a suite begins", func() { - BeforeEach(func() { - reporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - }) - - It("should start intercepting output", func() { - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SuiteSummary and Ginkgo Config to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteWillBegin")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var sentData struct { - SentConfig config.GinkgoConfigType `json:"config"` - SentSuiteSummary *types.SuiteSummary `json:"suite-summary"` - } - - err := json.Unmarshal(poster.posts[0].bodyContent, &sentData) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(sentData.SentConfig).Should(Equal(config.GinkgoConfig)) - Ω(sentData.SentSuiteSummary).Should(Equal(suiteSummary)) - }) - }) - - Context("when a BeforeSuite completes", func() { - BeforeEach(func() { - reporter.BeforeSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/BeforeSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("when an AfterSuite completes", func() { - BeforeEach(func() { - reporter.AfterSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/AfterSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("When a spec will run", func() { - BeforeEach(func() { - reporter.SpecWillRun(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecWillRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - Ω(summary).Should(Equal(specSummary)) - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - specSummary.State = types.SpecStatePanicked - reporter.SpecDidComplete(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server and include any intercepted output", func() { - Ω(poster.posts).Should(HaveLen(2)) - Ω(poster.posts[1].url).Should(Equal("http://127.0.0.1:7788/SpecDidComplete")) - Ω(poster.posts[1].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[1].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - specSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(specSummary)) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - }) - }) - - Context("When a suite ends", func() { - BeforeEach(func() { - reporter.SpecSuiteDidEnd(suiteSummary) - }) - - It("should POST the SuiteSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteDidEnd")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SuiteSummary - - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(summary).Should(Equal(suiteSummary)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go deleted file mode 100644 index e6b4e9f32ce..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestRemote(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Remote Spec Forwarding Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go deleted file mode 100644 index eb2eefebe02..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/remote/server_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/remote" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "bytes" - "encoding/json" - "net/http" -) - -var _ = Describe("Server", func() { - var ( - server *Server - ) - - BeforeEach(func() { - var err error - server, err = NewServer(3) - Ω(err).ShouldNot(HaveOccurred()) - - server.Start() - }) - - AfterEach(func() { - server.Close() - }) - - Describe("Streaming endpoints", func() { - var ( - reporterA, reporterB *reporters.FakeReporter - forwardingReporter *ForwardingReporter - - suiteSummary *types.SuiteSummary - setupSummary *types.SetupSummary - specSummary *types.SpecSummary - ) - - BeforeEach(func() { - reporterA = reporters.NewFakeReporter() - reporterB = reporters.NewFakeReporter() - - server.RegisterReporters(reporterA, reporterB) - - forwardingReporter = NewForwardingReporter(server.Address(), &http.Client{}, &fakeOutputInterceptor{}) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - It("should make its address available", func() { - Ω(server.Address()).Should(MatchRegexp(`http://127.0.0.1:\d{2,}`)) - }) - - Describe("/SpecSuiteWillBegin", func() { - It("should decode and forward the Ginkgo config and suite summary", func(done Done) { - forwardingReporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - Ω(reporterA.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterB.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterA.BeginSummary).Should(Equal(suiteSummary)) - Ω(reporterB.BeginSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - - Describe("/BeforeSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.BeforeSuiteDidRun(setupSummary) - Ω(reporterA.BeforeSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.BeforeSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/AfterSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.AfterSuiteDidRun(setupSummary) - Ω(reporterA.AfterSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.AfterSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/SpecWillRun", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecWillRun(specSummary) - Ω(reporterA.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecDidComplete", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecDidComplete(specSummary) - Ω(reporterA.SpecSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecSuiteDidEnd", func() { - It("should decode and forward the suite summary", func(done Done) { - forwardingReporter.SpecSuiteDidEnd(suiteSummary) - Ω(reporterA.EndSummary).Should(Equal(suiteSummary)) - Ω(reporterB.EndSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - }) - - Describe("Synchronization endpoints", func() { - Describe("GETting and POSTing BeforeSuiteState", func() { - getBeforeSuite := func() types.RemoteBeforeSuiteData { - resp, err := http.Get(server.Address() + "/BeforeSuiteState") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - r := types.RemoteBeforeSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&r) - Ω(err).ShouldNot(HaveOccurred()) - - return r - } - - postBeforeSuite := func(r types.RemoteBeforeSuiteData) { - resp, err := http.Post(server.Address()+"/BeforeSuiteState", "application/json", bytes.NewReader(r.ToJSON())) - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - } - - Context("when the first node's Alive has not been registered yet", func() { - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node is Alive but has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return true - }) - }) - - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node has responded", func() { - var state types.RemoteBeforeSuiteData - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - - state = types.RemoteBeforeSuiteData{ - Data: []byte("my data"), - State: types.RemoteBeforeSuiteStatePassed, - } - postBeforeSuite(state) - }) - - It("should return the passed in state", func() { - returnedState := getBeforeSuite() - Ω(returnedState).Should(Equal(state)) - }) - }) - - Context("when the first node is no longer Alive and has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - }) - - It("should return disappeared", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - }) - }) - }) - - Describe("GETting RemoteAfterSuiteData", func() { - getRemoteAfterSuiteData := func() bool { - resp, err := http.Get(server.Address() + "/RemoteAfterSuiteData") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - a := types.RemoteAfterSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&a) - Ω(err).ShouldNot(HaveOccurred()) - - return a.CanRun - } - - Context("when there are unregistered nodes", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-node-1 nodes are still running", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return true - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-1 nodes are done", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return true", func() { - Ω(getRemoteAfterSuiteData()).Should(BeTrue()) - }) - - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go deleted file mode 100644 index 0396d7bde05..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/index_computer_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" -) - -var _ = Describe("ParallelizedIndexRange", func() { - var startIndex, count int - - It("should return the correct index range for 4 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(4, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(4, 2, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(3)) - - startIndex, count = ParallelizedIndexRange(5, 2, 2) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 3 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 3, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 4 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 4, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 4, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 3) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 4) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 5 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 5, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 6 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 6, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 6) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 5 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 7, 6) - Ω(count).Should(Equal(0)) - - startIndex, count = ParallelizedIndexRange(5, 7, 7) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 11 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(11, 7, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 4) - Ω(startIndex).Should(Equal(6)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 5) - Ω(startIndex).Should(Equal(8)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 6) - Ω(startIndex).Should(Equal(9)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 7) - Ω(startIndex).Should(Equal(10)) - Ω(count).Should(Equal(1)) - }) - -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go deleted file mode 100644 index 8681a720684..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpec(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go deleted file mode 100644 index 6d0f58cb044..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/spec_test.go +++ /dev/null @@ -1,626 +0,0 @@ -package spec_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo/internal/spec" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec", func() { - var ( - failer *Failer.Failer - codeLocation types.CodeLocation - nodesThatRan []string - spec *Spec - buffer *gbytes.Buffer - ) - - newBody := func(text string, fail bool) func() { - return func() { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - } - } - - newIt := func(text string, flag types.FlagType, fail bool) *leafnodes.ItNode { - return leafnodes.NewItNode(text, newBody(text, fail), flag, codeLocation, 0, failer, 0) - } - - newItWithBody := func(text string, body interface{}) *leafnodes.ItNode { - return leafnodes.NewItNode(text, body, noneFlag, codeLocation, 0, failer, 0) - } - - newMeasure := func(text string, flag types.FlagType, fail bool, samples int) *leafnodes.MeasureNode { - return leafnodes.NewMeasureNode(text, func(Benchmarker) { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - }, flag, codeLocation, samples, failer, 0) - } - - newBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newAft := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewAfterEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newJusBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewJustBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newContainer := func(text string, flag types.FlagType, setupNodes ...leafnodes.BasicNode) *containernode.ContainerNode { - c := containernode.New(text, flag, codeLocation) - for _, node := range setupNodes { - c.PushSetupNode(node) - } - return c - } - - containers := func(containers ...*containernode.ContainerNode) []*containernode.ContainerNode { - return containers - } - - BeforeEach(func() { - buffer = gbytes.NewBuffer() - failer = Failer.New() - codeLocation = codelocation.New(0) - nodesThatRan = []string{} - }) - - Describe("marking specs focused and pending", func() { - It("should satisfy various caes", func() { - cases := []struct { - ContainerFlags []types.FlagType - SubjectFlag types.FlagType - Pending bool - Focused bool - }{ - {[]types.FlagType{}, noneFlag, false, false}, - {[]types.FlagType{}, focusedFlag, false, true}, - {[]types.FlagType{}, pendingFlag, true, false}, - {[]types.FlagType{noneFlag}, noneFlag, false, false}, - {[]types.FlagType{focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag}, focusedFlag, false, true}, - {[]types.FlagType{focusedFlag}, focusedFlag, false, true}, - {[]types.FlagType{pendingFlag}, focusedFlag, true, true}, - {[]types.FlagType{noneFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag}, pendingFlag, true, true}, - {[]types.FlagType{pendingFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag, noneFlag}, noneFlag, false, true}, - {[]types.FlagType{noneFlag, focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag, noneFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag, pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{focusedFlag, pendingFlag}, noneFlag, true, true}, - } - - for i, c := range cases { - subject := newIt("it node", c.SubjectFlag, false) - containers := []*containernode.ContainerNode{} - for _, flag := range c.ContainerFlags { - containers = append(containers, newContainer("container", flag)) - } - - spec := New(subject, containers, false) - Ω(spec.Pending()).Should(Equal(c.Pending), "Case %d: %#v", i, c) - Ω(spec.Focused()).Should(Equal(c.Focused), "Case %d: %#v", i, c) - - if c.Pending { - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePending)) - } - } - }) - }) - - Describe("Skip", func() { - It("should be skipped", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.Skipped()).Should(BeFalse()) - spec.Skip() - Ω(spec.Skipped()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("IsMeasurement", func() { - It("should be true if the subject is a measurement node", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeFalse()) - Ω(spec.Summary("").IsMeasurement).Should(BeFalse()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(1)) - - spec = New(newMeasure("measure node", noneFlag, false, 10), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeTrue()) - Ω(spec.Summary("").IsMeasurement).Should(BeTrue()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(10)) - }) - }) - - Describe("Passed", func() { - It("should pass when the subject passed", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePassed)) - Ω(spec.Summary("").Failure).Should(BeZero()) - }) - }) - - Describe("Failed", func() { - It("should be failed if the failure was panic", func() { - spec := New(newItWithBody("panicky it", func() { - panic("bam") - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePanicked)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Test Panicked")) - Ω(spec.Summary("").Failure.ForwardedPanic).Should(Equal("bam")) - }) - - It("should be failed if the failure was a timeout", func() { - spec := New(newItWithBody("sleepy it", func(done Done) {}), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateTimedOut)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Timed out")) - }) - - It("should be failed if the failure was... a failure", func() { - spec := New(newItWithBody("failing it", func() { - failer.Fail("bam", codeLocation) - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateFailed)) - Ω(spec.Summary("").Failure.Message).Should(Equal("bam")) - }) - }) - - Describe("Concatenated string", func() { - It("should concatenate the texts of the containers and the subject", func() { - spec := New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag), - newContainer("inner container", noneFlag), - ), - false, - ) - - Ω(spec.ConcatenatedString()).Should(Equal("outer container inner container it node")) - }) - }) - - Describe("running it specs", func() { - Context("with just an it", func() { - Context("that succeeds", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - - Context("that fails", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, true), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - }) - - Context("with a full set of setup nodes", func() { - var failingNodes map[string]bool - - BeforeEach(func() { - failingNodes = map[string]bool{} - }) - - JustBeforeEach(func() { - spec = New( - newIt("it node", noneFlag, failingNodes["it node"]), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", failingNodes["outer bef A"]), - newBef("outer bef B", failingNodes["outer bef B"]), - newJusBef("outer jusbef A", failingNodes["outer jusbef A"]), - newJusBef("outer jusbef B", failingNodes["outer jusbef B"]), - newAft("outer aft A", failingNodes["outer aft A"]), - newAft("outer aft B", failingNodes["outer aft B"]), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", failingNodes["inner bef A"]), - newBef("inner bef B", failingNodes["inner bef B"]), - newJusBef("inner jusbef A", failingNodes["inner jusbef A"]), - newJusBef("inner jusbef B", failingNodes["inner jusbef B"]), - newAft("inner aft A", failingNodes["inner aft A"]), - newAft("inner aft B", failingNodes["inner aft B"]), - ), - ), - false, - ) - spec.Run(buffer) - }) - - Context("that all pass", func() { - It("should walk through the nodes in the correct order", func() { - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - }) - }) - - Context("when the subject fails", func() { - BeforeEach(func() { - failingNodes["it node"] = true - }) - - It("should run the afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - - Context("when an inner before fails", func() { - BeforeEach(func() { - failingNodes["inner bef A"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner bef A")) - }) - }) - - Context("when an outer before fails", func() { - BeforeEach(func() { - failingNodes["outer bef B"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer bef B")) - }) - }) - - Context("when an after fails", func() { - BeforeEach(func() { - failingNodes["inner aft B"] = true - }) - - It("should run all other afters, but mark the test as failed", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner aft B")) - }) - }) - - Context("when a just before each fails", func() { - BeforeEach(func() { - failingNodes["outer jusbef B"] = true - }) - - It("should run the afters, but not the subject", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer jusbef B")) - }) - }) - - Context("when an after fails after an earlier node has failed", func() { - BeforeEach(func() { - failingNodes["it node"] = true - failingNodes["inner aft B"] = true - }) - - It("should record the earlier failure", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - }) - }) - - Describe("running measurement specs", func() { - Context("when the measurement succeeds", func() { - It("should run N samples", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - - Context("when the measurement fails", func() { - It("should bail after the failure occurs", func() { - spec = New( - newMeasure("measure node", noneFlag, true, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - }) - - Describe("Summary", func() { - var ( - subjectCodeLocation types.CodeLocation - outerContainerCodeLocation types.CodeLocation - innerContainerCodeLocation types.CodeLocation - summary *types.SpecSummary - ) - - BeforeEach(func() { - subjectCodeLocation = codelocation.New(0) - outerContainerCodeLocation = codelocation.New(0) - innerContainerCodeLocation = codelocation.New(0) - - spec = New( - leafnodes.NewItNode("it node", func() { - time.Sleep(10 * time.Millisecond) - }, noneFlag, subjectCodeLocation, 0, failer, 0), - containers( - containernode.New("outer container", noneFlag, outerContainerCodeLocation), - containernode.New("inner container", noneFlag, innerContainerCodeLocation), - ), - false, - ) - - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should have the suite id", func() { - Ω(summary.SuiteID).Should(Equal("suite id")) - }) - - It("should have the component texts and code locations", func() { - Ω(summary.ComponentTexts).Should(Equal([]string{"outer container", "inner container", "it node"})) - Ω(summary.ComponentCodeLocations).Should(Equal([]types.CodeLocation{outerContainerCodeLocation, innerContainerCodeLocation, subjectCodeLocation})) - }) - - It("should have a runtime", func() { - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - }) - - It("should not be a measurement, or have a measurement summary", func() { - Ω(summary.IsMeasurement).Should(BeFalse()) - Ω(summary.Measurements).Should(BeEmpty()) - }) - }) - - Describe("Summaries for measurements", func() { - var summary *types.SpecSummary - - BeforeEach(func() { - spec = New(leafnodes.NewMeasureNode("measure node", func(b Benchmarker) { - b.RecordValue("a value", 7, "some info") - }, noneFlag, codeLocation, 4, failer, 0), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should include the number of samples", func() { - Ω(summary.NumberOfSamples).Should(Equal(4)) - }) - - It("should be a measurement", func() { - Ω(summary.IsMeasurement).Should(BeTrue()) - }) - - It("should have the measurements report", func() { - Ω(summary.Measurements).Should(HaveKey("a value")) - - report := summary.Measurements["a value"] - Ω(report.Name).Should(Equal("a value")) - Ω(report.Info).Should(Equal("some info")) - Ω(report.Results).Should(Equal([]float64{7, 7, 7, 7})) - }) - }) - - Describe("When told to emit progress", func() { - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Its", func() { - spec = New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", false), - newJusBef("outer jusbef A", false), - newAft("outer aft A", false), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", false), - newJusBef("inner jusbef A", false), - newAft("inner aft A", false), - ), - ), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[It\] it node`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] outer container`)) - }) - - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Measures", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 2), - containers(), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go deleted file mode 100644 index ce9f5f332f1..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/spec/specs_test.go +++ /dev/null @@ -1,335 +0,0 @@ -package spec_test - -import ( - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Specs", func() { - var specs *Specs - - newSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newMeasureSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewMeasureNode(text, func(Benchmarker) {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecs := func(args ...interface{}) *Specs { - specs := []*Spec{} - for index := 0; index < len(args)-1; index += 2 { - specs = append(specs, newSpec(args[index].(string), args[index+1].(types.FlagType))) - } - return NewSpecs(specs) - } - - specTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - texts = append(texts, spec.ConcatenatedString()) - } - return texts - } - - willRunTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if !(spec.Skipped() || spec.Pending()) { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - skippedTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Skipped() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - pendingTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Pending() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - Describe("Shuffling specs", func() { - It("should shuffle the specs using the passed in randomizer", func() { - specs17 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17.Shuffle(rand.New(rand.NewSource(17))) - texts17 := specTexts(specs17) - - specs17Again := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17Again.Shuffle(rand.New(rand.NewSource(17))) - texts17Again := specTexts(specs17Again) - - specs15 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs15.Shuffle(rand.New(rand.NewSource(15))) - texts15 := specTexts(specs15) - - specsUnshuffled := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - textsUnshuffled := specTexts(specsUnshuffled) - - Ω(textsUnshuffled).Should(Equal([]string{"C", "A", "B"})) - - Ω(texts17).Should(Equal(texts17Again)) - Ω(texts17).ShouldNot(Equal(texts15)) - Ω(texts17).ShouldNot(Equal(textsUnshuffled)) - Ω(texts15).ShouldNot(Equal(textsUnshuffled)) - - Ω(texts17).Should(HaveLen(3)) - Ω(texts17).Should(ContainElement("A")) - Ω(texts17).Should(ContainElement("B")) - Ω(texts17).Should(ContainElement("C")) - - Ω(texts15).Should(HaveLen(3)) - Ω(texts15).Should(ContainElement("A")) - Ω(texts15).Should(ContainElement("B")) - Ω(texts15).Should(ContainElement("C")) - }) - }) - - Describe("with no programmatic focus", func() { - BeforeEach(func() { - specs = newSpecs("A1", noneFlag, "A2", noneFlag, "B1", noneFlag, "B2", pendingFlag) - specs.ApplyFocus("", "", "") - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Describe("Applying focus/skip", func() { - var description, focusString, skipString string - - BeforeEach(func() { - description, focusString, skipString = "", "", "" - }) - - JustBeforeEach(func() { - specs = newSpecs("A1", focusedFlag, "A2", noneFlag, "B1", focusedFlag, "B2", pendingFlag) - specs.ApplyFocus(description, focusString, skipString) - }) - - Context("with neither a focus string nor a skip string", func() { - It("should apply the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeTrue()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "B" - }) - - It("should not override any pendings", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - focusString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2", "B1"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - skipString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(BeEmpty()) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - }) - - Context("with a skip regexp", func() { - BeforeEach(func() { - skipString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with both a focus and a skip regexp", func() { - BeforeEach(func() { - focusString = "1" - skipString = "B" - }) - - It("should AND the two", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - }) - - Describe("With a focused spec within a pending context and a pending spec within a focused context", func() { - BeforeEach(func() { - pendingInFocused := New( - leafnodes.NewItNode("PendingInFocused", func() {}, pendingFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", focusedFlag, codelocation.New(0)), - }, false) - - focusedInPending := New( - leafnodes.NewItNode("FocusedInPending", func() {}, focusedFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", pendingFlag, codelocation.New(0)), - }, false) - - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - pendingInFocused, - focusedInPending, - }) - specs.ApplyFocus("", "", "") - }) - - It("should not have a programmatic focus and should run all tests", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(ConsistOf(ContainSubstring("PendingInFocused"), ContainSubstring("FocusedInPending"))) - }) - }) - - Describe("skipping measurements", func() { - BeforeEach(func() { - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - newSpec("C", pendingFlag), - newMeasureSpec("measurementA", noneFlag), - newMeasureSpec("measurementB", pendingFlag), - }) - }) - - It("should skip measurements", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B", "measurementA"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"C", "measurementB"})) - - specs.SkipMeasurements() - - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"measurementA", "measurementB"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"C"})) - }) - }) - - Describe("when running tests in parallel", func() { - It("should select out a subset of the tests", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag, "C", noneFlag, "D", noneFlag, "E", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A", "B"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"C", "D"})) - Ω(willRunTexts(specsNode3)).Should(Equal([]string{"E"})) - - Ω(specsNode1.Specs()).Should(HaveLen(2)) - Ω(specsNode2.Specs()).Should(HaveLen(2)) - Ω(specsNode3.Specs()).Should(HaveLen(1)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(5)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(5)) - }) - - Context("when way too many nodes are used", func() { - It("should return 0 specs", func() { - specsNode1 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode2 := newSpecs("A", noneFlag, "B", noneFlag) - specsNode3 := newSpecs("A", noneFlag, "B", noneFlag) - - specsNode1.TrimForParallelization(3, 1) - specsNode2.TrimForParallelization(3, 2) - specsNode3.TrimForParallelization(3, 3) - - Ω(willRunTexts(specsNode1)).Should(Equal([]string{"A"})) - Ω(willRunTexts(specsNode2)).Should(Equal([]string{"B"})) - Ω(willRunTexts(specsNode3)).Should(BeEmpty()) - - Ω(specsNode1.Specs()).Should(HaveLen(1)) - Ω(specsNode2.Specs()).Should(HaveLen(1)) - Ω(specsNode3.Specs()).Should(HaveLen(0)) - - Ω(specsNode1.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode2.NumberOfOriginalSpecs()).Should(Equal(2)) - Ω(specsNode3.NumberOfOriginalSpecs()).Should(Equal(2)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go deleted file mode 100644 index c8388fb6f7d..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpecRunner(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Runner Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go deleted file mode 100644 index 99686d3e61f..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go +++ /dev/null @@ -1,623 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec Runner", func() { - var ( - reporter1 *reporters.FakeReporter - reporter2 *reporters.FakeReporter - failer *Failer.Failer - writer *Writer.FakeGinkgoWriter - - thingsThatRan []string - - runner *SpecRunner - ) - - newBefSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewBeforeSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newAftSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewAfterSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newSpec := func(text string, flag types.FlagType, fail bool) *spec.Spec { - subject := leafnodes.NewItNode(text, func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, flag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecWithBody := func(text string, body interface{}) *spec.Spec { - subject := leafnodes.NewItNode(text, body, noneFlag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newRunner := func(config config.GinkgoConfigType, beforeSuiteNode leafnodes.SuiteNode, afterSuiteNode leafnodes.SuiteNode, specs ...*spec.Spec) *SpecRunner { - return New("description", beforeSuiteNode, spec.NewSpecs(specs), afterSuiteNode, []reporters.Reporter{reporter1, reporter2}, writer, config) - } - - BeforeEach(func() { - reporter1 = reporters.NewFakeReporter() - reporter2 = reporters.NewFakeReporter() - writer = Writer.NewFake() - failer = Failer.New() - - thingsThatRan = []string{} - }) - - Describe("Running and Reporting", func() { - var specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec *spec.Spec - var willRunCalls, didCompleteCalls []string - var conf config.GinkgoConfigType - - JustBeforeEach(func() { - willRunCalls = []string{} - didCompleteCalls = []string{} - specA = newSpec("spec A", noneFlag, false) - pendingSpec = newSpec("pending spec", pendingFlag, false) - anotherPendingSpec = newSpec("another pending spec", pendingFlag, false) - failedSpec = newSpec("failed spec", noneFlag, true) - specB = newSpec("spec B", noneFlag, false) - skippedSpec = newSpec("skipped spec", noneFlag, false) - skippedSpec.Skip() - - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter1") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter2") - } - - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter1") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter2") - } - - runner = newRunner(conf, newBefSuite("BefSuite", false), newAftSuite("AftSuite", false), specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec) - runner.Run() - }) - - BeforeEach(func() { - conf = config.GinkgoConfigType{RandomSeed: 17} - }) - - It("should skip skipped/pending tests", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "spec A", "failed spec", "spec B", "AftSuite"})) - }) - - It("should report to any attached reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should report that a spec did end in reverse order", func() { - Ω(willRunCalls[0:4]).Should(Equal([]string{"Reporter1", "Reporter2", "Reporter1", "Reporter2"})) - Ω(didCompleteCalls[0:4]).Should(Equal([]string{"Reporter2", "Reporter1", "Reporter2", "Reporter1"})) - }) - - It("should report the passed in config", func() { - Ω(reporter1.Config.RandomSeed).Should(BeNumerically("==", 17)) - }) - - It("should report the beginning of the suite", func() { - Ω(reporter1.BeginSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.BeginSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.BeginSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.BeginSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.BeginSummary.NumberOfSkippedSpecs).Should(Equal(1)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - }) - - Context("when told to perform a dry run", func() { - BeforeEach(func() { - conf.DryRun = true - }) - - It("should report to the reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should not actually run anything", func() { - Ω(thingsThatRan).Should(BeEmpty()) - }) - - It("report before and after suites as passed", func() { - Ω(reporter1.BeforeSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - Ω(reporter1.AfterSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - }) - - It("should report specs as passed", func() { - summaries := reporter1.SpecSummaries - Ω(summaries).Should(HaveLen(6)) - Ω(summaries[0].ComponentTexts).Should(ContainElement("spec A")) - Ω(summaries[0].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[1].ComponentTexts).Should(ContainElement("pending spec")) - Ω(summaries[1].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[2].ComponentTexts).Should(ContainElement("another pending spec")) - Ω(summaries[2].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[3].ComponentTexts).Should(ContainElement("failed spec")) - Ω(summaries[3].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[4].ComponentTexts).Should(ContainElement("spec B")) - Ω(summaries[4].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[5].ComponentTexts).Should(ContainElement("skipped spec")) - Ω(summaries[5].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(0)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - }) - }) - - Describe("reporting on specs", func() { - var proceed chan bool - var ready chan bool - var finished chan bool - BeforeEach(func() { - ready = make(chan bool) - proceed = make(chan bool) - finished = make(chan bool) - skippedSpec := newSpec("SKIP", noneFlag, false) - skippedSpec.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - newBefSuite("BefSuite", false), - newAftSuite("AftSuite", false), - skippedSpec, - newSpec("PENDING", pendingFlag, false), - newSpecWithBody("RUN", func() { - close(ready) - <-proceed - }), - ) - go func() { - runner.Run() - close(finished) - }() - }) - - It("should report about pending/skipped specs", func() { - <-ready - Ω(reporter1.SpecWillRunSummaries).Should(HaveLen(3)) - - Ω(reporter1.SpecWillRunSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecWillRunSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecWillRunSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - - Ω(reporter1.SpecSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecSummaries).Should(HaveLen(2)) - - close(proceed) - <-finished - - Ω(reporter1.SpecSummaries).Should(HaveLen(3)) - Ω(reporter1.SpecSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - }) - }) - - Describe("Running BeforeSuite & AfterSuite", func() { - var success bool - var befSuite leafnodes.SuiteNode - var aftSuite leafnodes.SuiteNode - Context("with a nil BeforeSuite & AfterSuite", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should not report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(BeNil()) - }) - - It("should not report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(BeNil()) - }) - - It("should run the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "B"})) - }) - }) - - Context("when the BeforeSuite & AfterSuite pass", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", false) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run the BeforeSuite, the AfterSuite and the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report success", func() { - Ω(success).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should not dump the writer", func() { - Ω(writer.EventStream).ShouldNot(ContainElement("DUMP")) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", true) - aftSuite = newBefSuite("AftSuite", false) - - skipped := newSpec("Skipped", noneFlag, false) - skipped.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - newSpec("Pending", pendingFlag, false), - skipped, - ) - success = runner.Run() - }) - - It("should not run the specs, but it should run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(2)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - - Context("when some other test fails", func() { - BeforeEach(func() { - aftSuite = newBefSuite("AftSuite", false) - - runner = newRunner( - config.GinkgoConfigType{}, - nil, - aftSuite, - newSpec("A", noneFlag, true), - ) - success = runner.Run() - }) - - It("should still run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "AftSuite"})) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", true) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run everything", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - }) - - Describe("When instructed to fail fast", func() { - BeforeEach(func() { - conf := config.GinkgoConfigType{ - FailFast: true, - } - runner = newRunner(conf, nil, newAftSuite("after-suite", false), newSpec("passing", noneFlag, false), newSpec("failing", noneFlag, true), newSpec("dont-see", noneFlag, true), newSpec("dont-see", noneFlag, true)) - }) - - It("should return false, report failure, and not run anything past the failing test", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(thingsThatRan).Should(Equal([]string{"passing", "failing", "after-suite"})) - }) - - It("should announce the subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.SpecSummaries).Should(HaveLen(4)) - Ω(reporter1.SpecSummaries[2].State).Should(Equal(types.SpecStateSkipped)) - Ω(reporter1.SpecSummaries[3].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should mark all subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(2)) - }) - }) - - Describe("Marking failure and success", func() { - Context("when all tests pass", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return true and report success", func() { - Ω(runner.Run()).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - }) - }) - - Context("when a test fails", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("failing", noneFlag, true), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - - Context("when there is a pending test, but pendings count as failures", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{FailOnPending: true}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - }) - - Describe("Managing the writer", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, true), - newSpec("C", noneFlag, false), - ) - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.WillRun") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.WillRun") - } - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.DidComplete") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.DidComplete") - } - runner.Run() - }) - - It("should truncate between tests, but only dump if a test fails", func() { - Ω(writer.EventStream).Should(Equal([]string{ - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "A", - "R2.DidComplete", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "B", - "R2.DidComplete", - "DUMP", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "C", - "R2.DidComplete", - "R1.DidComplete", - })) - }) - }) - - Describe("CurrentSpecSummary", func() { - It("should return the spec summary for the currently running spec", func() { - var summary *types.SpecSummary - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpecWithBody("B", func() { - var ok bool - summary, ok = runner.CurrentSpecSummary() - Ω(ok).Should(BeTrue()) - }), - newSpec("C", noneFlag, false), - ) - runner.Run() - - Ω(summary.ComponentTexts).Should(Equal([]string{"B"})) - - summary, ok := runner.CurrentSpecSummary() - Ω(summary).Should(BeNil()) - Ω(ok).Should(BeFalse()) - }) - }) - - Context("When running tests in parallel", func() { - It("reports the correct number of specs before parallelization", func() { - specs := spec.NewSpecs([]*spec.Spec{ - newSpec("A", noneFlag, false), - newSpec("B", pendingFlag, false), - newSpec("C", noneFlag, false), - }) - specs.TrimForParallelization(2, 1) - runner = New("description", nil, specs, nil, []reporters.Reporter{reporter1, reporter2}, writer, config.GinkgoConfigType{}) - runner.Run() - - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(1)) - }) - }) - - Describe("generating a suite id", func() { - It("should generate an id randomly", func() { - runnerA := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerA.Run() - IDA := reporter1.BeginSummary.SuiteID - - runnerB := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerB.Run() - IDB := reporter1.BeginSummary.SuiteID - - IDRegexp := "[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}" - Ω(IDA).Should(MatchRegexp(IDRegexp)) - Ω(IDB).Should(MatchRegexp(IDRegexp)) - - Ω(IDA).ShouldNot(Equal(IDB)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go deleted file mode 100644 index 06fe1d12aba..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package suite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Suite") -} - -var numBeforeSuiteRuns = 0 -var numAfterSuiteRuns = 0 - -var _ = BeforeSuite(func() { - numBeforeSuiteRuns++ -}) - -var _ = AfterSuite(func() { - numAfterSuiteRuns++ - Ω(numBeforeSuiteRuns).Should(Equal(1)) - Ω(numAfterSuiteRuns).Should(Equal(1)) -}) - -//Fakes -type fakeTestingT struct { - didFail bool -} - -func (fakeT *fakeTestingT) Fail() { - fakeT.didFail = true -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go deleted file mode 100644 index dd471b4752e..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/suite/suite_test.go +++ /dev/null @@ -1,399 +0,0 @@ -package suite_test - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/suite" - . "github.com/onsi/gomega" - - "math/rand" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Suite", func() { - var ( - specSuite *Suite - fakeT *fakeTestingT - fakeR *reporters.FakeReporter - writer *Writer.FakeGinkgoWriter - failer *Failer.Failer - ) - - BeforeEach(func() { - writer = Writer.NewFake() - fakeT = &fakeTestingT{} - fakeR = reporters.NewFakeReporter() - failer = Failer.New() - specSuite = New(failer) - }) - - Describe("running a suite", func() { - var ( - runOrder []string - randomizeAllSpecs bool - randomSeed int64 - focusString string - parallelNode int - parallelTotal int - runResult bool - hasProgrammaticFocus bool - ) - - var f = func(runText string) func() { - return func() { - runOrder = append(runOrder, runText) - } - } - - BeforeEach(func() { - randomizeAllSpecs = false - randomSeed = 11 - parallelNode = 1 - parallelTotal = 1 - focusString = "" - - runOrder = make([]string, 0) - specSuite.SetBeforeSuiteNode(f("BeforeSuite"), codelocation.New(0), 0) - specSuite.PushBeforeEachNode(f("top BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("top JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("top AE"), codelocation.New(0), 0) - - specSuite.PushContainerNode("container", func() { - specSuite.PushBeforeEachNode(f("BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("AE"), codelocation.New(0), 0) - specSuite.PushItNode("it", f("IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.PushContainerNode("inner container", func() { - specSuite.PushItNode("inner it", f("inner IT"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushContainerNode("container 2", func() { - specSuite.PushBeforeEachNode(f("BE 2"), codelocation.New(0), 0) - specSuite.PushItNode("it 2", f("IT 2"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushItNode("top level it", f("top IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.SetAfterSuiteNode(f("AfterSuite"), codelocation.New(0), 0) - }) - - JustBeforeEach(func() { - runResult, hasProgrammaticFocus = specSuite.Run(fakeT, "suite description", []reporters.Reporter{fakeR}, writer, config.GinkgoConfigType{ - RandomSeed: randomSeed, - RandomizeAllSpecs: randomizeAllSpecs, - FocusString: focusString, - ParallelNode: parallelNode, - ParallelTotal: parallelTotal, - }) - }) - - It("provides the config and suite description to the reporter", func() { - Ω(fakeR.Config.RandomSeed).Should(Equal(int64(randomSeed))) - Ω(fakeR.Config.RandomizeAllSpecs).Should(Equal(randomizeAllSpecs)) - Ω(fakeR.BeginSummary.SuiteDescription).Should(Equal("suite description")) - }) - - It("reports that the BeforeSuite node ran", func() { - Ω(fakeR.BeforeSuiteSummary).ShouldNot(BeNil()) - }) - - It("reports that the AfterSuite node ran", func() { - Ω(fakeR.AfterSuiteSummary).ShouldNot(BeNil()) - }) - - It("provides information about the current test", func() { - description := CurrentGinkgoTestDescription() - Ω(description.ComponentTexts).Should(Equal([]string{"Suite", "running a suite", "provides information about the current test"})) - Ω(description.FullTestText).Should(Equal("Suite running a suite provides information about the current test")) - Ω(description.TestText).Should(Equal("provides information about the current test")) - Ω(description.IsMeasurement).Should(BeFalse()) - Ω(description.FileName).Should(ContainSubstring("suite_test.go")) - Ω(description.LineNumber).Should(BeNumerically(">", 50)) - Ω(description.LineNumber).Should(BeNumerically("<", 150)) - Ω(description.Failed).Should(BeFalse()) - }) - - Measure("should run measurements", func(b Benchmarker) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - - runtime := b.Time("sleeping", func() { - sleepTime := time.Duration(r.Float64() * 0.01 * float64(time.Second)) - time.Sleep(sleepTime) - }) - Ω(runtime.Seconds()).Should(BeNumerically("<=", 0.015)) - Ω(runtime.Seconds()).Should(BeNumerically(">=", 0)) - - randomValue := r.Float64() * 10.0 - b.RecordValue("random value", randomValue) - Ω(randomValue).Should(BeNumerically("<=", 10.0)) - Ω(randomValue).Should(BeNumerically(">=", 0.0)) - }, 10) - - It("creates a node hierarchy, converts it to a spec collection, and runs it", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "top BE", "top JBE", "top IT", "top AE", - "AfterSuite", - })) - }) - - Context("when told to randomize all specs", func() { - BeforeEach(func() { - randomizeAllSpecs = true - }) - - It("does", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - - Describe("with ginkgo.parallel.total > 1", func() { - BeforeEach(func() { - parallelTotal = 2 - randomizeAllSpecs = true - }) - - Context("for one worker", func() { - BeforeEach(func() { - parallelNode = 1 - }) - - It("should run a subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "AfterSuite", - })) - }) - }) - - Context("for another worker", func() { - BeforeEach(func() { - parallelNode = 2 - }) - - It("should run a (different) subset of tests", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - }) - - Context("when provided with a filter", func() { - BeforeEach(func() { - focusString = `inner|\d` - }) - - It("converts the filter to a regular expression and uses it to filter the running specs", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - - It("should not report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeFalse()) - }) - }) - - Context("with a programatically focused spec", func() { - BeforeEach(func() { - specSuite.PushItNode("focused it", f("focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - - specSuite.PushContainerNode("focused container", func() { - specSuite.PushItNode("inner focused it", f("inner focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - specSuite.PushItNode("inner unfocused it", f("inner unfocused it"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeFocused, codelocation.New(0)) - - }) - - It("should only run the focused test, applying backpropagation to favor most deeply focused leaf nodes", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "focused it", "top AE", - "top BE", "top JBE", "inner focused it", "top AE", - "AfterSuite", - })) - }) - - It("should report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeTrue()) - }) - }) - - Context("when the specs pass", func() { - It("doesn't report a failure", func() { - Ω(fakeT.didFail).Should(BeFalse()) - }) - - It("should return true", func() { - Ω(runResult).Should(BeTrue()) - }) - }) - - Context("when a spec fails", func() { - var location types.CodeLocation - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - location = codelocation.New(0) - failer.Fail("oops!", location) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should return false", func() { - Ω(runResult).Should(BeFalse()) - }) - - It("reports a failure", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - - It("generates the correct failure data", func() { - Ω(fakeR.SpecSummaries[0].Failure.Message).Should(Equal("oops!")) - Ω(fakeR.SpecSummaries[0].Failure.Location).Should(Equal(location)) - }) - }) - - Context("when runnable nodes are nested within other runnable nodes", func() { - Context("when an It is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushItNode("nested it", f("oops"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a Measure is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushMeasureNode("nested measure", func(Benchmarker) {}, types.FlagTypeNone, codelocation.New(0), 10) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a BeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushBeforeEachNode(f("nested bef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a JustBeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushJustBeforeEachNode(f("nested jbef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a AfterEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushAfterEachNode(f("nested aft"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - }) - }) - - Describe("BeforeSuite", func() { - Context("when setting BeforeSuite more than once", func() { - It("should panic", func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - - }) - }) - }) - - Describe("AfterSuite", func() { - Context("when setting AfterSuite more than once", func() { - It("should panic", func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - }) - }) - }) - - Describe("By", func() { - It("writes to the GinkgoWriter", func() { - originalGinkgoWriter := GinkgoWriter - buffer := &bytes.Buffer{} - - GinkgoWriter = buffer - By("Saying Hello GinkgoWriter") - GinkgoWriter = originalGinkgoWriter - - Ω(buffer.String()).Should(ContainSubstring("STEP")) - Ω(buffer.String()).Should(ContainSubstring(": Saying Hello GinkgoWriter\n")) - }) - - It("calls the passed-in callback if present", func() { - a := 0 - By("calling the callback", func() { - a = 1 - }) - Ω(a).Should(Equal(1)) - }) - - It("panics if there is more than one callback", func() { - Ω(func() { - By("registering more than one callback", func() {}, func() {}) - }).Should(Panic()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go deleted file mode 100644 index e206577919a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package writer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestWriter(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Writer Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go deleted file mode 100644 index 3e1d17c6d50..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/writer/writer_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package writer_test - -import ( - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/writer" - . "github.com/onsi/gomega" -) - -var _ = Describe("Writer", func() { - var writer *Writer - var out *gbytes.Buffer - - BeforeEach(func() { - out = gbytes.NewBuffer() - writer = New(out) - }) - - It("should stream directly to the outbuffer by default", func() { - writer.Write([]byte("foo")) - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should not emit the header when asked to DumpOutWitHeader", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - Ω(out).ShouldNot(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - - Context("when told not to stream", func() { - BeforeEach(func() { - writer.SetStream(false) - }) - - It("should only write to the buffer when told to DumpOut", func() { - writer.Write([]byte("foo")) - Ω(out).ShouldNot(gbytes.Say("foo")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should truncate the internal buffer when told to truncate", func() { - writer.Write([]byte("foo")) - writer.Truncate() - writer.DumpOut() - Ω(out).ShouldNot(gbytes.Say("foo")) - - writer.Write([]byte("bar")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("bar")) - }) - - Describe("emitting a header", func() { - Context("when the buffer has content", func() { - It("should emit the header followed by the content", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - - Ω(out).Should(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - }) - - Context("when the buffer has no content", func() { - It("should not emit the header", func() { - writer.DumpOutWithHeader("my header") - - Ω(out).ShouldNot(gbytes.Say("my header")) - }) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go deleted file mode 100644 index 7a877e86c68..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/default_reporter_test.go +++ /dev/null @@ -1,415 +0,0 @@ -package reporters_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("DefaultReporter", func() { - var ( - reporter *reporters.DefaultReporter - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - - ginkgoConfig config.GinkgoConfigType - suite *types.SuiteSummary - spec *types.SpecSummary - ) - - BeforeEach(func() { - stenographer = st.NewFakeStenographer() - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: false, - Verbose: true, - FullTrace: true, - } - - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - Describe("SpecSuiteWillBegin", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{ - SuiteDescription: "A Sweet Suite", - NumberOfTotalSpecs: 10, - NumberOfSpecsThatWillBeRun: 8, - } - - ginkgoConfig = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - } - }) - - Context("when a serial (non-parallel) suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 1 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(2)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - - Context("when a parallel suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 2 - ginkgoConfig.ParallelNode = 1 - suite.NumberOfSpecsBeforeParallelization = 20 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, announce that it's a parallel run, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceParallelRun", 1, 2, 10, 20, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - }) - - Describe("BeforeSuiteDidRun", func() { - Context("when the BeforeSuite passes", func() { - It("should announce nothing", func() { - reporter.BeforeSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the BeforeSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.BeforeSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceBeforeSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("AfterSuiteDidRun", func() { - Context("when the AfterSuite passes", func() { - It("should announce nothing", func() { - reporter.AfterSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the AfterSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.AfterSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceAfterSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("SpecWillRun", func() { - Context("When running in verbose mode", func() { - Context("and the spec will run", func() { - BeforeEach(func() { - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce that the spec will run", func() { - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecWillRun", spec))) - }) - }) - - Context("and the spec will not run", func() { - Context("because it is pending", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStatePending, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("because it is skipped", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStateSkipped, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - }) - - Context("When running in verbose & succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("When not running in verbose mode", func() { - BeforeEach(func() { - reporterConfig.Verbose = false - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - - Describe("SpecDidComplete", func() { - JustBeforeEach(func() { - reporter.SpecDidComplete(spec) - }) - - BeforeEach(func() { - spec = &types.SpecSummary{} - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, false))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, false))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, succinctly", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec, false, true))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, false, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, false, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, false, true))) - }) - }) - - Context("in noisy pendings mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = false - reporterConfig.NoisyPendings = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, noisily", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, true))) - }) - }) - }) - - Context("in succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, true))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, true))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, succinctly", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec, true, true))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, true, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, true, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, true, true))) - }) - }) - }) - }) - - Describe("SpecSuiteDidEnd", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{} - reporter.SpecSuiteDidEnd(suite) - }) - - It("should announce the spec run's completion", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecRunCompletion", suite, false))) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go deleted file mode 100644 index 744f383a05f..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/junit_reporter_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package reporters_test - -import ( - "encoding/xml" - "io/ioutil" - "os" - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("JUnit Reporter", func() { - var ( - outputFile string - reporter Reporter - ) - - readOutputFile := func() reporters.JUnitTestSuite { - bytes, err := ioutil.ReadFile(outputFile) - Ω(err).ShouldNot(HaveOccurred()) - var suite reporters.JUnitTestSuite - err = xml.Unmarshal(bytes, &suite) - Ω(err).ShouldNot(HaveOccurred()) - return suite - } - - BeforeEach(func() { - f, err := ioutil.TempFile("", "output") - Ω(err).ShouldNot(HaveOccurred()) - f.Close() - outputFile = f.Name() - - reporter = reporters.NewJUnitReporter(outputFile) - - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "My test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - AfterEach(func() { - os.RemoveAll(outputFile) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases).Should(HaveLen(1)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage).Should(BeNil()) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - Ω(output.TestCases[0].Time).Should(Equal(5.0)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("BeforeSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(beforeSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("AfterSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(afterSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal(specStateCase.message)) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("I failed")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(spec.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].Skipped).ShouldNot(BeNil()) - }) - }) - } -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go deleted file mode 100644 index cec5a4dbfb0..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/reporters_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package reporters_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestReporters(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Reporters Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go deleted file mode 100644 index de87732113c..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package reporters_test - -import ( - "bytes" - "fmt" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "time" -) - -var _ = Describe("TeamCity Reporter", func() { - var ( - buffer bytes.Buffer - reporter Reporter - ) - - BeforeEach(func() { - buffer.Truncate(0) - reporter = reporters.NewTeamCityReporter(&buffer) - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "Foo's test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='BeforeSuite']"+ - "##teamcity[testFailed name='BeforeSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='BeforeSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", beforeSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='AfterSuite']"+ - "##teamcity[testFailed name='AfterSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='AfterSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", afterSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - actual := buffer.String() - expected := - fmt.Sprintf("##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='A B C']"+ - "##teamcity[testFailed name='A B C' message='%s' details='I failed']"+ - "##teamcity[testFinished name='A B C' duration='5000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", spec.Failure.ComponentCodeLocation.String()) - Ω(actual).Should(Equal(expected)) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as ignored", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testIgnored name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - } -}) diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go deleted file mode 100644 index b026169c12b..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTypes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Types Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go b/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go deleted file mode 100644 index 124b216ec60..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/ginkgo/types/types_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var specStates = []SpecState{ - SpecStatePassed, - SpecStateTimedOut, - SpecStatePanicked, - SpecStateFailed, - SpecStatePending, - SpecStateSkipped, -} - -func verifySpecSummary(caller func(SpecSummary) bool, trueStates ...SpecState) { - summary := SpecSummary{} - trueStateLookup := map[SpecState]bool{} - for _, state := range trueStates { - trueStateLookup[state] = true - summary.State = state - Ω(caller(summary)).Should(BeTrue()) - } - - for _, state := range specStates { - if trueStateLookup[state] { - continue - } - summary.State = state - Ω(caller(summary)).Should(BeFalse()) - } -} - -var _ = Describe("Types", func() { - Describe("SpecSummary", func() { - It("knows when it is in a failure-like state", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.HasFailureState() - }, SpecStateTimedOut, SpecStatePanicked, SpecStateFailed) - }) - - It("knows when it passed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Passed() - }, SpecStatePassed) - }) - - It("knows when it has failed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Failed() - }, SpecStateFailed) - }) - - It("knows when it has panicked", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Panicked() - }, SpecStatePanicked) - }) - - It("knows when it has timed out", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.TimedOut() - }, SpecStateTimedOut) - }) - - It("knows when it is pending", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Pending() - }, SpecStatePending) - }) - - It("knows when it is skipped", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Skipped() - }, SpecStateSkipped) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go deleted file mode 100644 index 8e65a95292d..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package format_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFormat(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Format Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go deleted file mode 100644 index fd926f58ea8..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/format/format_test.go +++ /dev/null @@ -1,449 +0,0 @@ -package format_test - -import ( - "fmt" - "strings" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" -) - -//recursive struct - -type StringAlias string -type ByteAlias []byte -type IntAlias int - -type AStruct struct { - Exported string -} - -type SimpleStruct struct { - Name string - Enumeration int - Veritas bool - Data []byte - secret uint32 -} - -type ComplexStruct struct { - Strings []string - SimpleThings []*SimpleStruct - DataMaps map[int]ByteAlias -} - -type SecretiveStruct struct { - boolValue bool - intValue int - uintValue uint - uintptrValue uintptr - floatValue float32 - complexValue complex64 - chanValue chan bool - funcValue func() - pointerValue *int - sliceValue []string - byteSliceValue []byte - stringValue string - arrValue [3]int - byteArrValue [3]byte - mapValue map[string]int - structValue AStruct - interfaceValue interface{} -} - -type GoStringer struct { -} - -func (g GoStringer) GoString() string { - return "go-string" -} - -func (g GoStringer) String() string { - return "string" -} - -type Stringer struct { -} - -func (g Stringer) String() string { - return "string" -} - -var _ = Describe("Format", func() { - match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - hashMatchingRegexp := func(entries ...string) string { - entriesSwitch := "(" + strings.Join(entries, "|") + ")" - arr := make([]string, len(entries)) - for i := range arr { - arr[i] = entriesSwitch - } - return "{" + strings.Join(arr, ", ") + "}" - } - - Describe("Message", func() { - Context("with only an actual value", func() { - It("should print out an indented formatted representation of the value and the message", func() { - Ω(Message(3, "to be three.")).Should(Equal("Expected\n : 3\nto be three.")) - }) - }) - - Context("with an actual and an expected value", func() { - It("should print out an indented formatted representatino of both values, and the message", func() { - Ω(Message(3, "to equal", 4)).Should(Equal("Expected\n : 3\nto equal\n : 4")) - }) - }) - }) - - Describe("IndentString", func() { - It("should indent the string", func() { - Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz")) - }) - }) - - Describe("Object", func() { - Describe("formatting boolean values", func() { - It("should give the type and format values correctly", func() { - Ω(Object(true, 1)).Should(match("bool", "true")) - Ω(Object(false, 1)).Should(match("bool", "false")) - }) - }) - - Describe("formatting numbers", func() { - It("should give the type and format values correctly", func() { - Ω(Object(int(3), 1)).Should(match("int", "3")) - Ω(Object(int8(3), 1)).Should(match("int8", "3")) - Ω(Object(int16(3), 1)).Should(match("int16", "3")) - Ω(Object(int32(3), 1)).Should(match("int32", "3")) - Ω(Object(int64(3), 1)).Should(match("int64", "3")) - - Ω(Object(uint(3), 1)).Should(match("uint", "3")) - Ω(Object(uint8(3), 1)).Should(match("uint8", "3")) - Ω(Object(uint16(3), 1)).Should(match("uint16", "3")) - Ω(Object(uint32(3), 1)).Should(match("uint32", "3")) - Ω(Object(uint64(3), 1)).Should(match("uint64", "3")) - }) - - It("should handle uintptr differently", func() { - Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3")) - }) - }) - - Describe("formatting channels", func() { - It("should give the type and format values correctly", func() { - c := make(chan<- bool, 3) - c <- true - c <- false - Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c)) - }) - }) - - Describe("formatting strings", func() { - It("should give the type and format values correctly", func() { - s := "a\nb\nc" - Ω(Object(s, 1)).Should(match("string", `a - b - c`)) - }) - }) - - Describe("formatting []byte slices", func() { - It("should present them as strings", func() { - b := []byte("a\nb\nc") - Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a - b - c`)) - }) - }) - - Describe("formatting functions", func() { - It("should give the type and format values correctly", func() { - f := func(a string, b []int) ([]byte, error) { - return []byte("abc"), nil - } - Ω(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f)) - }) - }) - - Describe("formatting pointers", func() { - It("should give the type and dereference the value to format it correctly", func() { - a := 3 - Ω(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3")) - }) - - Context("when there are pointers to pointers...", func() { - It("should recursively deference the pointer until it gets to a value", func() { - a := 3 - var b *int - var c **int - var d ***int - b = &a - c = &b - d = &c - - Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3")) - }) - }) - - Context("when the pointer points to nil", func() { - It("should say nil and not explode", func() { - var a *AStruct - Ω(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - }) - }) - }) - - Describe("formatting arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"} - Ω(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`)) - }) - - Context("with byte arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]byte{17, 28, 19} - Ω(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`)) - }) - }) - }) - - Describe("formatting slices", func() { - It("should include the length and capacity in the type information", func() { - s := make([]bool, 3, 4) - Ω(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]")) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"} - expected := `[ - "Josiah Edward Bartlet", - "Toby Ziegler", - "CJ Cregg", - ]` - Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected)) - }) - }) - }) - - Describe("formatting maps", func() { - It("should include the length in the type information", func() { - m := make(map[int]bool, 5) - m[3] = true - m[4] = false - Ω(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false"))) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - m := map[string][]byte{} - m["Josiah Edward Bartlet"] = []byte("Martin Sheen") - m["Toby Ziegler"] = []byte("Richard Schiff") - m["CJ Cregg"] = []byte("Allison Janney") - expected := `{ - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - }` - Ω(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected)) - }) - }) - }) - - Describe("formatting structs", func() { - It("should include the struct name and the field names", func() { - s := SimpleStruct{ - Name: "Oswald", - Enumeration: 17, - Veritas: true, - Data: []byte("datum"), - secret: 1983, - } - - Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`)) - }) - - Context("when the struct contains long entries", func() { - It("should format the entries with new lines", func() { - s := &SimpleStruct{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: []byte("wizard"), - secret: 3, - } - - Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: "wizard", - secret: 3, - }`)) - }) - }) - }) - - Describe("formatting nil values", func() { - It("should print out nil", func() { - Ω(Object(nil, 1)).Should(match("nil", "nil")) - var typedNil *AStruct - Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - var c chan<- bool - Ω(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil")) - var s []string - Ω(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil")) - var m map[string]bool - Ω(Object(m, 1)).Should(match("map[string]bool | len:0", "nil")) - }) - }) - - Describe("formatting aliased types", func() { - It("should print out the correct alias type", func() { - Ω(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`)) - Ω(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`)) - Ω(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3")) - }) - }) - - Describe("handling nested things", func() { - It("should produce a correctly nested representation", func() { - s := ComplexStruct{ - Strings: []string{"lots", "of", "short", "strings"}, - SimpleThings: []*SimpleStruct{ - {"short", 7, true, []byte("succinct"), 17}, - {"something longer", 427, true, []byte("designed to wrap around nicely"), 30}, - }, - DataMaps: map[int]ByteAlias{ - 17: ByteAlias("some substantially longer chunks of data"), - 1138: ByteAlias("that should make things wrap"), - }, - } - expected := `{ - Strings: \["lots", "of", "short", "strings"\], - SimpleThings: \[ - {Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17}, - { - Name: "something longer", - Enumeration: 427, - Veritas: true, - Data: "designed to wrap around nicely", - secret: 30, - }, - \], - DataMaps: { - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - }, - }` - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected)) - }) - }) - }) - - Describe("Handling unexported fields in structs", func() { - It("should handle all the various types correctly", func() { - a := int(5) - s := SecretiveStruct{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 5, - floatValue: 6.0, - complexValue: complex(5.0, 3.0), - chanValue: make(chan bool, 2), - funcValue: func() {}, - pointerValue: &a, - sliceValue: []string{"string", "slice"}, - byteSliceValue: []byte("bytes"), - stringValue: "a string", - arrValue: [3]int{11, 12, 13}, - byteArrValue: [3]byte{17, 20, 32}, - mapValue: map[string]int{"a key": 20, "b key": 30}, - structValue: AStruct{"exported"}, - interfaceValue: map[string]int{"a key": 17}, - } - - expected := fmt.Sprintf(`{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 0x5, - floatValue: 6, - complexValue: \(5\+3i\), - chanValue: %p, - funcValue: %p, - pointerValue: 5, - sliceValue: \["string", "slice"\], - byteSliceValue: "bytes", - stringValue: "a string", - arrValue: \[11, 12, 13\], - byteArrValue: \[17, 20, 32\], - mapValue: %s, - structValue: {Exported: "exported"}, - interfaceValue: {"a key": 17}, - }`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`)) - - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected)) - }) - }) - - Describe("Handling interfaces", func() { - It("should unpack the interface", func() { - outerHash := map[string]interface{}{} - innerHash := map[string]int{} - - innerHash["inner"] = 3 - outerHash["integer"] = 2 - outerHash["map"] = innerHash - - expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`) - Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected)) - }) - }) - - Describe("Handling recursive things", func() { - It("should not go crazy...", func() { - m := map[string]interface{}{} - m["integer"] = 2 - m["map"] = m - Ω(Object(m, 1)).Should(ContainSubstring("...")) - }) - }) - - Describe("When instructed to use the Stringer representation", func() { - BeforeEach(func() { - UseStringerRepresentation = true - }) - - AfterEach(func() { - UseStringerRepresentation = false - }) - - Context("when passed a GoStringer", func() { - It("should use what GoString() returns", func() { - Ω(Object(GoStringer{}, 1)).Should(ContainSubstring(": go-string")) - }) - }) - - Context("when passed a stringer", func() { - It("should use what String() returns", func() { - Ω(Object(Stringer{}, 1)).Should(ContainSubstring(": string")) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go deleted file mode 100644 index b1111389e1a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/buffer_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package gbytes_test - -import ( - "io" - "time" - - . "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Buffer", func() { - var buffer *Buffer - - BeforeEach(func() { - buffer = NewBuffer() - }) - - Describe("dumping the entire contents of the buffer", func() { - It("should return everything that's been written", func() { - buffer.Write([]byte("abc")) - buffer.Write([]byte("def")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - - Ω(buffer).Should(Say("bcd")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - }) - }) - - Describe("creating a buffer with bytes", func() { - It("should create the buffer with the cursor set to the beginning", func() { - buffer := BufferWithBytes([]byte("abcdef")) - Ω(buffer.Contents()).Should(Equal([]byte("abcdef"))) - Ω(buffer).Should(Say("abc")) - Ω(buffer).ShouldNot(Say("abc")) - Ω(buffer).Should(Say("def")) - }) - }) - - Describe("reading from a buffer", func() { - It("should read the current contents of the buffer", func() { - buffer := BufferWithBytes([]byte("abcde")) - - dest := make([]byte, 3) - n, err := buffer.Read(dest) - Ω(err).ShouldNot(HaveOccurred()) - Ω(n).Should(Equal(3)) - Ω(string(dest)).Should(Equal("abc")) - - dest = make([]byte, 3) - n, err = buffer.Read(dest) - Ω(err).ShouldNot(HaveOccurred()) - Ω(n).Should(Equal(2)) - Ω(string(dest[:n])).Should(Equal("de")) - - n, err = buffer.Read(dest) - Ω(err).Should(Equal(io.EOF)) - Ω(n).Should(Equal(0)) - }) - - Context("after the buffer has been closed", func() { - It("returns an error", func() { - buffer := BufferWithBytes([]byte("abcde")) - - buffer.Close() - - dest := make([]byte, 3) - n, err := buffer.Read(dest) - Ω(err).Should(HaveOccurred()) - Ω(n).Should(Equal(0)) - }) - }) - }) - - Describe("detecting regular expressions", func() { - It("should fire the appropriate channel when the passed in pattern matches, then close it", func(done Done) { - go func() { - time.Sleep(10 * time.Millisecond) - buffer.Write([]byte("abcde")) - }() - - A := buffer.Detect("%s", "a.c") - B := buffer.Detect("def") - - var gotIt bool - select { - case gotIt = <-A: - case <-B: - Fail("should not have gotten here") - } - - Ω(gotIt).Should(BeTrue()) - Eventually(A).Should(BeClosed()) - - buffer.Write([]byte("f")) - Eventually(B).Should(Receive()) - Eventually(B).Should(BeClosed()) - - close(done) - }) - - It("should fast-forward the buffer upon detection", func(done Done) { - buffer.Write([]byte("abcde")) - <-buffer.Detect("abc") - Ω(buffer).ShouldNot(Say("abc")) - Ω(buffer).Should(Say("de")) - close(done) - }) - - It("should only fast-forward the buffer when the channel is read, and only if doing so would not rewind it", func(done Done) { - buffer.Write([]byte("abcde")) - A := buffer.Detect("abc") - time.Sleep(20 * time.Millisecond) //give the goroutine a chance to detect and write to the channel - Ω(buffer).Should(Say("abcd")) - <-A - Ω(buffer).ShouldNot(Say("d")) - Ω(buffer).Should(Say("e")) - Eventually(A).Should(BeClosed()) - close(done) - }) - - It("should be possible to cancel a detection", func(done Done) { - A := buffer.Detect("abc") - B := buffer.Detect("def") - buffer.CancelDetects() - buffer.Write([]byte("abcdef")) - Eventually(A).Should(BeClosed()) - Eventually(B).Should(BeClosed()) - - Ω(buffer).Should(Say("bcde")) - <-buffer.Detect("f") - close(done) - }) - }) - - Describe("closing the buffer", func() { - It("should error when further write attempts are made", func() { - _, err := buffer.Write([]byte("abc")) - Ω(err).ShouldNot(HaveOccurred()) - - buffer.Close() - - _, err = buffer.Write([]byte("def")) - Ω(err).Should(HaveOccurred()) - - Ω(buffer.Contents()).Should(Equal([]byte("abc"))) - }) - - It("should be closed", func() { - Ω(buffer.Closed()).Should(BeFalse()) - - buffer.Close() - - Ω(buffer.Closed()).Should(BeTrue()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go deleted file mode 100644 index 3a7dc06123e..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/gbuffer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package gbytes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestGbytes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Gbytes Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go deleted file mode 100644 index d0ddf1f74ce..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gbytes/say_matcher_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package gbytes_test - -import ( - "time" - . "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type speaker struct { - buffer *Buffer -} - -func (s *speaker) Buffer() *Buffer { - return s.buffer -} - -var _ = Describe("SayMatcher", func() { - var buffer *Buffer - - BeforeEach(func() { - buffer = NewBuffer() - buffer.Write([]byte("abc")) - }) - - Context("when actual is not a gexec Buffer, or a BufferProvider", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("foo").Should(Say("foo")) - }) - Ω(failures[0]).Should(ContainSubstring("*gbytes.Buffer")) - }) - }) - - Context("when a match is found", func() { - It("should succeed", func() { - Ω(buffer).Should(Say("abc")) - }) - - It("should support printf-like formatting", func() { - Ω(buffer).Should(Say("a%sc", "b")) - }) - - It("should use a regular expression", func() { - Ω(buffer).Should(Say("a.c")) - }) - - It("should fastforward the buffer", func() { - buffer.Write([]byte("def")) - Ω(buffer).Should(Say("abcd")) - Ω(buffer).Should(Say("ef")) - Ω(buffer).ShouldNot(Say("[a-z]")) - }) - }) - - Context("when no match is found", func() { - It("should not error", func() { - Ω(buffer).ShouldNot(Say("def")) - }) - - Context("when the buffer is closed", func() { - BeforeEach(func() { - buffer.Close() - }) - - It("should abort an eventually", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(buffer).Should(Say("def")) - }) - Eventually(buffer).ShouldNot(Say("def")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - - t = time.Now() - Eventually(buffer).Should(Say("abc")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - - It("should abort a consistently", func() { - t := time.Now() - Consistently(buffer, 2.0).ShouldNot(Say("def")) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - - It("should not error with a synchronous matcher", func() { - Ω(buffer).ShouldNot(Say("def")) - Ω(buffer).Should(Say("abc")) - }) - }) - }) - - Context("when a positive match fails", func() { - It("should report where it got stuck", func() { - Ω(buffer).Should(Say("abc")) - buffer.Write([]byte("def")) - failures := InterceptGomegaFailures(func() { - Ω(buffer).Should(Say("abc")) - }) - Ω(failures[0]).Should(ContainSubstring("Got stuck at:")) - Ω(failures[0]).Should(ContainSubstring("def")) - }) - }) - - Context("when a negative match fails", func() { - It("should report where it got stuck", func() { - failures := InterceptGomegaFailures(func() { - Ω(buffer).ShouldNot(Say("abc")) - }) - Ω(failures[0]).Should(ContainSubstring("Saw:")) - Ω(failures[0]).Should(ContainSubstring("Which matches the unexpected:")) - Ω(failures[0]).Should(ContainSubstring("abc")) - }) - }) - - Context("when a match is not found", func() { - It("should not fastforward the buffer", func() { - Ω(buffer).ShouldNot(Say("def")) - Ω(buffer).Should(Say("abc")) - }) - }) - - Context("a nice real-life example", func() { - It("should behave well", func() { - Ω(buffer).Should(Say("abc")) - go func() { - time.Sleep(10 * time.Millisecond) - buffer.Write([]byte("def")) - }() - Ω(buffer).ShouldNot(Say("def")) - Eventually(buffer).Should(Say("def")) - }) - }) - - Context("when actual is a BufferProvider", func() { - It("should use actual's buffer", func() { - s := &speaker{ - buffer: NewBuffer(), - } - - Ω(s).ShouldNot(Say("abc")) - - s.Buffer().Write([]byte("abc")) - Ω(s).Should(Say("abc")) - }) - - It("should abort an eventually", func() { - s := &speaker{ - buffer: NewBuffer(), - } - - s.buffer.Close() - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(s).Should(Say("def")) - }) - Ω(failures).Should(HaveLen(1)) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/exit_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gexec/exit_matcher_test.go deleted file mode 100644 index 9f18e2d6e0a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/exit_matcher_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package gexec_test - -import ( - "os/exec" - "time" - . "github.com/onsi/gomega/gexec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type NeverExits struct{} - -func (e NeverExits) ExitCode() int { - return -1 -} - -var _ = Describe("ExitMatcher", func() { - var command *exec.Cmd - var session *Session - - BeforeEach(func() { - var err error - command = exec.Command(fireflyPath, "0") - session, err = Start(command, nil, nil) - Ω(err).ShouldNot(HaveOccurred()) - }) - - Describe("when passed something that is an Exiter", func() { - It("should act normally", func() { - failures := InterceptGomegaFailures(func() { - Ω(NeverExits{}).Should(Exit()) - }) - - Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not.")) - }) - }) - - Describe("when passed something that is not an Exiter", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("aardvark").Should(Exit()) - }) - - Ω(failures[0]).Should(ContainSubstring("Exit must be passed a gexec.Exiter")) - }) - }) - - Context("with no exit code", func() { - It("should say the right things when it fails", func() { - Ω(session).ShouldNot(Exit()) - - failures := InterceptGomegaFailures(func() { - Ω(session).Should(Exit()) - }) - - Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not.")) - - Eventually(session).Should(Exit()) - - Ω(session).Should(Exit()) - - failures = InterceptGomegaFailures(func() { - Ω(session).ShouldNot(Exit()) - }) - - Ω(failures[0]).Should(ContainSubstring("Expected process not to exit. It did.")) - }) - }) - - Context("with an exit code", func() { - It("should say the right things when it fails", func() { - Ω(session).ShouldNot(Exit(0)) - Ω(session).ShouldNot(Exit(1)) - - failures := InterceptGomegaFailures(func() { - Ω(session).Should(Exit(0)) - }) - - Ω(failures[0]).Should(ContainSubstring("Expected process to exit. It did not.")) - - Eventually(session).Should(Exit(0)) - - Ω(session).Should(Exit(0)) - - failures = InterceptGomegaFailures(func() { - Ω(session).Should(Exit(1)) - }) - - Ω(failures[0]).Should(ContainSubstring("to match exit code:")) - - Ω(session).ShouldNot(Exit(1)) - - failures = InterceptGomegaFailures(func() { - Ω(session).ShouldNot(Exit(0)) - }) - - Ω(failures[0]).Should(ContainSubstring("not to match exit code:")) - }) - }) - - Describe("bailing out early", func() { - It("should bail out early once the process exits", func() { - t := time.Now() - - failures := InterceptGomegaFailures(func() { - Eventually(session).Should(Exit(1)) - }) - Ω(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/gexec_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gexec/gexec_suite_test.go deleted file mode 100644 index 87672aafa39..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/gexec_suite_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package gexec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" - - "testing" -) - -var fireflyPath string - -func TestGexec(t *testing.T) { - BeforeSuite(func() { - var err error - fireflyPath, err = gexec.Build("./_fixture/firefly") - Ω(err).ShouldNot(HaveOccurred()) - }) - - AfterSuite(func() { - gexec.CleanupBuildArtifacts() - }) - - RegisterFailHandler(Fail) - RunSpecs(t, "Gexec Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/prefixed_writer_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gexec/prefixed_writer_test.go deleted file mode 100644 index 8657d0c9de0..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/prefixed_writer_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package gexec_test - -import ( - "bytes" - - . "github.com/onsi/gomega/gexec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("PrefixedWriter", func() { - var buffer *bytes.Buffer - var writer *PrefixedWriter - BeforeEach(func() { - buffer = &bytes.Buffer{} - writer = NewPrefixedWriter("[p]", buffer) - }) - - It("should emit the prefix on newlines", func() { - writer.Write([]byte("abc")) - writer.Write([]byte("def\n")) - writer.Write([]byte("hij\n")) - writer.Write([]byte("\n\n")) - writer.Write([]byte("klm\n\nnop")) - writer.Write([]byte("")) - writer.Write([]byte("qrs")) - writer.Write([]byte("\ntuv\nwx")) - writer.Write([]byte("yz\n\n")) - - Ω(buffer.String()).Should(Equal(`[p]abcdef -[p]hij -[p] -[p] -[p]klm -[p] -[p]nopqrs -[p]tuv -[p]wxyz -[p] -`)) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/session_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/gexec/session_test.go deleted file mode 100644 index cd48e6f4dbe..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/gexec/session_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package gexec_test - -import ( - "os/exec" - "syscall" - "time" - . "github.com/onsi/gomega/gbytes" - . "github.com/onsi/gomega/gexec" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Session", func() { - var command *exec.Cmd - var session *Session - - var outWriter, errWriter *Buffer - - BeforeEach(func() { - outWriter = nil - errWriter = nil - }) - - JustBeforeEach(func() { - command = exec.Command(fireflyPath) - var err error - session, err = Start(command, outWriter, errWriter) - Ω(err).ShouldNot(HaveOccurred()) - }) - - Context("running a command", func() { - It("should start the process", func() { - Ω(command.Process).ShouldNot(BeNil()) - }) - - It("should wrap the process's stdout and stderr with gbytes buffers", func(done Done) { - Eventually(session.Out).Should(Say("We've done the impossible, and that makes us mighty")) - Eventually(session.Err).Should(Say("Ah, curse your sudden but inevitable betrayal!")) - defer session.Out.CancelDetects() - - select { - case <-session.Out.Detect("Can we maybe vote on the whole murdering people issue"): - Eventually(session).Should(Exit(0)) - case <-session.Out.Detect("I swear by my pretty floral bonnet, I will end you."): - Eventually(session).Should(Exit(1)) - case <-session.Out.Detect("My work's illegal, but at least it's honest."): - Eventually(session).Should(Exit(2)) - } - - close(done) - }) - - It("should satisfy the gbytes.BufferProvider interface, passing Stdout", func() { - Eventually(session).Should(Say("We've done the impossible, and that makes us mighty")) - Eventually(session).Should(Exit()) - }) - }) - - Describe("providing the exit code", func() { - It("should provide the app's exit code", func() { - Ω(session.ExitCode()).Should(Equal(-1)) - - Eventually(session).Should(Exit()) - Ω(session.ExitCode()).Should(BeNumerically(">=", 0)) - Ω(session.ExitCode()).Should(BeNumerically("<", 3)) - }) - }) - - Describe("wait", func() { - It("should wait till the command exits", func() { - Ω(session.ExitCode()).Should(Equal(-1)) - Ω(session.Wait().ExitCode()).Should(BeNumerically(">=", 0)) - Ω(session.Wait().ExitCode()).Should(BeNumerically("<", 3)) - }) - }) - - Describe("exited", func() { - It("should close when the command exits", func() { - Eventually(session.Exited).Should(BeClosed()) - Ω(session.ExitCode()).ShouldNot(Equal(-1)) - }) - }) - - Describe("kill", func() { - It("should kill the command and wait for it to exit", func() { - session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - session.Kill() - Ω(session).ShouldNot(Exit(), "Should not exit immediately...") - Eventually(session).Should(Exit(128 + 9)) - }) - }) - - Describe("interrupt", func() { - It("should interrupt the command", func() { - session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - session.Interrupt() - Ω(session).ShouldNot(Exit(), "Should not exit immediately...") - Eventually(session).Should(Exit(128 + 2)) - }) - }) - - Describe("terminate", func() { - It("should terminate the command", func() { - session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - session.Terminate() - Ω(session).ShouldNot(Exit(), "Should not exit immediately...") - Eventually(session).Should(Exit(128 + 15)) - }) - }) - - Describe("signal", func() { - It("should send the signal to the command", func() { - session, err := Start(exec.Command("sleep", "10000000"), GinkgoWriter, GinkgoWriter) - Ω(err).ShouldNot(HaveOccurred()) - - session.Signal(syscall.SIGABRT) - Ω(session).ShouldNot(Exit(), "Should not exit immediately...") - Eventually(session).Should(Exit(128 + 6)) - }) - }) - - Context("when the command exits", func() { - It("should close the buffers", func() { - Eventually(session).Should(Exit()) - - Ω(session.Out.Closed()).Should(BeTrue()) - Ω(session.Err.Closed()).Should(BeTrue()) - - Ω(session.Out).Should(Say("We've done the impossible, and that makes us mighty")) - }) - - var So = It - - So("this means that eventually should short circuit", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(session).Should(Say("blah blah blah blah blah")) - }) - Ω(time.Since(t)).Should(BeNumerically("<=", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when wrapping out and err", func() { - BeforeEach(func() { - outWriter = NewBuffer() - errWriter = NewBuffer() - }) - - It("should route to both the provided writers and the gbytes buffers", func() { - Eventually(session.Out).Should(Say("We've done the impossible, and that makes us mighty")) - Eventually(session.Err).Should(Say("Ah, curse your sudden but inevitable betrayal!")) - - Ω(outWriter.Contents()).Should(ContainSubstring("We've done the impossible, and that makes us mighty")) - Ω(errWriter.Contents()).Should(ContainSubstring("Ah, curse your sudden but inevitable betrayal!")) - - Eventually(session).Should(Exit()) - - Ω(outWriter.Contents()).Should(Equal(session.Out.Contents())) - Ω(errWriter.Contents()).Should(Equal(session.Err.Contents())) - }) - }) - - Describe("when the command fails to start", func() { - It("should return an error", func() { - _, err := Start(exec.Command("agklsjdfas"), nil, nil) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_suite_test.go deleted file mode 100644 index 7c123608275..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package ghttp_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestGHTTP(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "GHTTP Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_test.go deleted file mode 100644 index 793ca4a488d..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/ghttp/test_server_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package ghttp_test - -import ( - "bytes" - "io/ioutil" - "net/http" - "regexp" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/ghttp" -) - -var _ = Describe("TestServer", func() { - var ( - resp *http.Response - err error - s *Server - ) - - BeforeEach(func() { - s = NewServer() - }) - - AfterEach(func() { - s.Close() - }) - - Describe("closing client connections", func() { - It("closes", func() { - s.AppendHandlers( - func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte("hello")) - }, - func(w http.ResponseWriter, req *http.Request) { - s.CloseClientConnections() - }, - ) - - resp, err := http.Get(s.URL()) - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(200)) - - body, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(Equal([]byte("hello"))) - - resp, err = http.Get(s.URL()) - Ω(err).Should(HaveOccurred()) - Ω(resp).Should(BeNil()) - }) - }) - - Describe("allowing unhandled requests", func() { - Context("when true", func() { - BeforeEach(func() { - s.AllowUnhandledRequests = true - s.UnhandledRequestStatusCode = http.StatusForbidden - resp, err = http.Get(s.URL() + "/foo") - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should allow unhandled requests and respond with the passed in status code", func() { - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusForbidden)) - - data, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(data).Should(BeEmpty()) - }) - - It("should record the requests", func() { - Ω(s.ReceivedRequests()).Should(HaveLen(1)) - Ω(s.ReceivedRequests()[0].URL.Path).Should(Equal("/foo")) - }) - }) - - Context("when false", func() { - It("should fail when attempting a request", func() { - failures := InterceptGomegaFailures(func() { - http.Get(s.URL() + "/foo") - }) - - Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request")) - }) - }) - }) - - Describe("Managing Handlers", func() { - var called []string - BeforeEach(func() { - called = []string{} - s.RouteToHandler("GET", "/routed", func(w http.ResponseWriter, req *http.Request) { - called = append(called, "r1") - }) - s.RouteToHandler("POST", regexp.MustCompile(`/routed\d`), func(w http.ResponseWriter, req *http.Request) { - called = append(called, "r2") - }) - s.AppendHandlers(func(w http.ResponseWriter, req *http.Request) { - called = append(called, "A") - }, func(w http.ResponseWriter, req *http.Request) { - called = append(called, "B") - }) - }) - - It("should prefer routed handlers if there is a match", func() { - http.Get(s.URL() + "/routed") - http.Post(s.URL()+"/routed7", "application/json", nil) - http.Get(s.URL() + "/foo") - http.Get(s.URL() + "/routed") - http.Post(s.URL()+"/routed9", "application/json", nil) - http.Get(s.URL() + "/bar") - - failures := InterceptGomegaFailures(func() { - http.Get(s.URL() + "/foo") - http.Get(s.URL() + "/routed/not/a/match") - http.Get(s.URL() + "/routed7") - http.Post(s.URL()+"/routed", "application/json", nil) - }) - - Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request")) - Ω(failures).Should(HaveLen(4)) - - http.Post(s.URL()+"/routed3", "application/json", nil) - - Ω(called).Should(Equal([]string{"r1", "r2", "A", "r1", "r2", "B", "r2"})) - }) - - It("should override routed handlers when reregistered", func() { - s.RouteToHandler("GET", "/routed", func(w http.ResponseWriter, req *http.Request) { - called = append(called, "r3") - }) - s.RouteToHandler("POST", regexp.MustCompile(`/routed\d`), func(w http.ResponseWriter, req *http.Request) { - called = append(called, "r4") - }) - - http.Get(s.URL() + "/routed") - http.Post(s.URL()+"/routed7", "application/json", nil) - - Ω(called).Should(Equal([]string{"r3", "r4"})) - }) - - It("should call the appended handlers, in order, as requests come in", func() { - http.Get(s.URL() + "/foo") - Ω(called).Should(Equal([]string{"A"})) - - http.Get(s.URL() + "/foo") - Ω(called).Should(Equal([]string{"A", "B"})) - - failures := InterceptGomegaFailures(func() { - http.Get(s.URL() + "/foo") - }) - - Ω(failures[0]).Should(ContainSubstring("Received Unhandled Request")) - }) - - Describe("Overwriting an existing handler", func() { - BeforeEach(func() { - s.SetHandler(0, func(w http.ResponseWriter, req *http.Request) { - called = append(called, "C") - }) - }) - - It("should override the specified handler", func() { - http.Get(s.URL() + "/foo") - http.Get(s.URL() + "/foo") - Ω(called).Should(Equal([]string{"C", "B"})) - }) - }) - - Describe("Getting an existing handler", func() { - It("should return the handler func", func() { - s.GetHandler(1)(nil, nil) - Ω(called).Should(Equal([]string{"B"})) - }) - }) - - Describe("Wrapping an existing handler", func() { - BeforeEach(func() { - s.WrapHandler(0, func(w http.ResponseWriter, req *http.Request) { - called = append(called, "C") - }) - }) - - It("should wrap the existing handler in a new handler", func() { - http.Get(s.URL() + "/foo") - http.Get(s.URL() + "/foo") - Ω(called).Should(Equal([]string{"A", "C", "B"})) - }) - }) - }) - - Describe("Request Handlers", func() { - Describe("VerifyRequest", func() { - BeforeEach(func() { - s.AppendHandlers(VerifyRequest("GET", "/foo")) - }) - - It("should verify the method, path", func() { - resp, err = http.Get(s.URL() + "/foo?baz=bar") - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the method, path", func() { - failures := InterceptGomegaFailures(func() { - http.Get(s.URL() + "/foo2") - }) - Ω(failures).Should(HaveLen(1)) - }) - - It("should verify the method, path", func() { - failures := InterceptGomegaFailures(func() { - http.Post(s.URL()+"/foo", "application/json", nil) - }) - Ω(failures).Should(HaveLen(1)) - }) - - Context("when passed a rawQuery", func() { - It("should also be possible to verify the rawQuery", func() { - s.SetHandler(0, VerifyRequest("GET", "/foo", "baz=bar")) - resp, err = http.Get(s.URL() + "/foo?baz=bar") - Ω(err).ShouldNot(HaveOccurred()) - }) - }) - - Context("when passed a matcher for path", func() { - It("should apply the matcher", func() { - s.SetHandler(0, VerifyRequest("GET", MatchRegexp(`/foo/[a-f]*/3`))) - resp, err = http.Get(s.URL() + "/foo/abcdefa/3") - Ω(err).ShouldNot(HaveOccurred()) - }) - }) - }) - - Describe("VerifyContentType", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("GET", "/foo"), - VerifyContentType("application/octet-stream"), - )) - }) - - It("should verify the content type", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Set("Content-Type", "application/octet-stream") - - resp, err = http.DefaultClient.Do(req) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the content type", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Set("Content-Type", "application/json") - - failures := InterceptGomegaFailures(func() { - http.DefaultClient.Do(req) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("Verify BasicAuth", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("GET", "/foo"), - VerifyBasicAuth("bob", "password"), - )) - }) - - It("should verify basic auth", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.SetBasicAuth("bob", "password") - - resp, err = http.DefaultClient.Do(req) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify basic auth", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.SetBasicAuth("bob", "bassword") - - failures := InterceptGomegaFailures(func() { - http.DefaultClient.Do(req) - }) - Ω(failures).Should(HaveLen(1)) - }) - - It("should require basic auth header", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - - failures := InterceptGomegaFailures(func() { - http.DefaultClient.Do(req) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("VerifyHeader", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("GET", "/foo"), - VerifyHeader(http.Header{ - "accept": []string{"jpeg", "png"}, - "cache-control": []string{"omicron"}, - "Return-Path": []string{"hobbiton"}, - }), - )) - }) - - It("should verify the headers", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Add("Accept", "jpeg") - req.Header.Add("Accept", "png") - req.Header.Add("Cache-Control", "omicron") - req.Header.Add("return-path", "hobbiton") - - resp, err = http.DefaultClient.Do(req) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the headers", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Add("Schmaccept", "jpeg") - req.Header.Add("Schmaccept", "png") - req.Header.Add("Cache-Control", "omicron") - req.Header.Add("return-path", "hobbiton") - - failures := InterceptGomegaFailures(func() { - http.DefaultClient.Do(req) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("VerifyHeaderKV", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("GET", "/foo"), - VerifyHeaderKV("accept", "jpeg", "png"), - VerifyHeaderKV("cache-control", "omicron"), - VerifyHeaderKV("Return-Path", "hobbiton"), - )) - }) - - It("should verify the headers", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Add("Accept", "jpeg") - req.Header.Add("Accept", "png") - req.Header.Add("Cache-Control", "omicron") - req.Header.Add("return-path", "hobbiton") - - resp, err = http.DefaultClient.Do(req) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the headers", func() { - req, err := http.NewRequest("GET", s.URL()+"/foo", nil) - Ω(err).ShouldNot(HaveOccurred()) - req.Header.Add("Accept", "jpeg") - req.Header.Add("Cache-Control", "omicron") - req.Header.Add("return-path", "hobbiton") - - failures := InterceptGomegaFailures(func() { - http.DefaultClient.Do(req) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("VerifyJSON", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - VerifyJSON(`{"a":3, "b":2}`), - )) - }) - - It("should verify the json body and the content type", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`{"b":2, "a":3}`))) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the json body and the content type", func() { - failures := InterceptGomegaFailures(func() { - http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`{"b":2, "a":4}`))) - }) - Ω(failures).Should(HaveLen(1)) - }) - - It("should verify the json body and the content type", func() { - failures := InterceptGomegaFailures(func() { - http.Post(s.URL()+"/foo", "application/not-json", bytes.NewReader([]byte(`{"b":2, "a":3}`))) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("VerifyJSONRepresenting", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - VerifyJSONRepresenting([]int{1, 3, 5}), - )) - }) - - It("should verify the json body and the content type", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`[1,3,5]`))) - Ω(err).ShouldNot(HaveOccurred()) - }) - - It("should verify the json body and the content type", func() { - failures := InterceptGomegaFailures(func() { - http.Post(s.URL()+"/foo", "application/json", bytes.NewReader([]byte(`[1,3]`))) - }) - Ω(failures).Should(HaveLen(1)) - }) - }) - - Describe("RespondWith", func() { - Context("without headers", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWith(http.StatusCreated, "sweet"), - ), CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWith(http.StatusOK, []byte("sour")), - )) - }) - - It("should return the response", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - - body, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(Equal([]byte("sweet"))) - - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - body, err = ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(Equal([]byte("sour"))) - }) - }) - - Context("with headers", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWith(http.StatusCreated, "sweet", http.Header{"X-Custom-Header": []string{"my header"}}), - )) - }) - - It("should return the headers too", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - Ω(ioutil.ReadAll(resp.Body)).Should(Equal([]byte("sweet"))) - Ω(resp.Header.Get("X-Custom-Header")).Should(Equal("my header")) - }) - }) - }) - - Describe("RespondWithPtr", func() { - var code int - var byteBody []byte - var stringBody string - BeforeEach(func() { - code = http.StatusOK - byteBody = []byte("sweet") - stringBody = "sour" - - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWithPtr(&code, &byteBody), - ), CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWithPtr(&code, &stringBody), - )) - }) - - It("should return the response", func() { - code = http.StatusCreated - byteBody = []byte("tasty") - stringBody = "treat" - - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - - body, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(Equal([]byte("tasty"))) - - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - - body, err = ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(Equal([]byte("treat"))) - }) - - Context("when passed a nil body", func() { - BeforeEach(func() { - s.SetHandler(0, CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWithPtr(&code, nil), - )) - }) - - It("should return an empty body and not explode", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - body, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(BeEmpty()) - - Ω(s.ReceivedRequests()).Should(HaveLen(1)) - }) - }) - }) - - Describe("RespondWithJSON", func() { - BeforeEach(func() { - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWithJSONEncoded(http.StatusCreated, []int{1, 2, 3}), - )) - }) - - It("should return the response", func() { - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - - body, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(MatchJSON("[1,2,3]")) - }) - }) - - Describe("RespondWithJSONPtr", func() { - var code int - var object interface{} - BeforeEach(func() { - code = http.StatusOK - object = []int{1, 2, 3} - - s.AppendHandlers(CombineHandlers( - VerifyRequest("POST", "/foo"), - RespondWithJSONEncodedPtr(&code, &object), - )) - }) - - It("should return the response", func() { - code = http.StatusCreated - object = []int{4, 5, 6} - resp, err = http.Post(s.URL()+"/foo", "application/json", nil) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(resp.StatusCode).Should(Equal(http.StatusCreated)) - - body, err := ioutil.ReadAll(resp.Body) - Ω(err).ShouldNot(HaveOccurred()) - Ω(body).Should(MatchJSON("[4,5,6]")) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go deleted file mode 100644 index dae47a48bf9..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package assertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Assertion Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_test.go deleted file mode 100644 index de9eff2d288..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/internal/assertion/assertion_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package assertion_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/assertion" - "github.com/onsi/gomega/internal/fakematcher" -) - -var _ = Describe("Assertion", func() { - var ( - a *Assertion - failureMessage string - failureCallerSkip int - matcher *fakematcher.FakeMatcher - ) - - input := "The thing I'm testing" - - var fakeFailHandler = func(message string, callerSkip ...int) { - failureMessage = message - if len(callerSkip) == 1 { - failureCallerSkip = callerSkip[0] - } - } - - BeforeEach(func() { - matcher = &fakematcher.FakeMatcher{} - failureMessage = "" - failureCallerSkip = 0 - a = New(input, fakeFailHandler, 1) - }) - - Context("when called", func() { - It("should pass the provided input value to the matcher", func() { - a.Should(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ShouldNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.To(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ToNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.NotTo(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - }) - }) - - Context("when the matcher succeeds", func() { - BeforeEach(func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should not call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.Should(matcher)).Should(BeTrue()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("negative: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - }) - - Context("when the matcher fails", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("positive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should not call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.ShouldNot(matcher)).Should(BeTrue()) - }) - }) - }) - - Context("When reporting a failure", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and there is an optional description", func() { - It("should append the description to the failure message", func() { - a.Should(matcher, "A description") - Ω(failureMessage).Should(Equal("A description\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and there are multiple arguments to the optional description", func() { - It("should append the formatted description to the failure message", func() { - a.Should(matcher, "A description of [%d]", 3) - Ω(failureMessage).Should(Equal("A description of [3]\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("When the matcher returns an error", func() { - BeforeEach(func() { - matcher.ErrToReturn = errors.New("Kaboom!") - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = true - a.Should(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - It("should always be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - - Context("when there are extra parameters", func() { - It("(a simple example)", func() { - Ω(func() (string, int, error) { - return "foo", 0, nil - }()).Should(Equal("foo")) - }) - - Context("when the parameters are all nil or zero", func() { - It("should invoke the matcher", func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - - var typedNil []string - a = New(input, fakeFailHandler, 1, 0, nil, typedNil) - - result := a.Should(matcher) - Ω(result).Should(BeTrue()) - Ω(matcher.ReceivedActual).Should(Equal(input)) - - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when any of the parameters are not nil or zero", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - - a = New(input, fakeFailHandler, 1, errors.New("foo")) - result := a.Should(matcher) - Ω(result).Should(BeFalse()) - Ω(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called") - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 1) - result = a.ShouldNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("1")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.To(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.ToNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.NotTo(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - Ω(true).Should(BeTrue()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go deleted file mode 100644 index bdb0c3d2202..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package asyncassertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAsyncAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "AsyncAssertion Suite") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go deleted file mode 100644 index 4288d4da919..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package asyncassertion_test - -import ( - "errors" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/asyncassertion" -) - -var _ = Describe("Async Assertion", func() { - var ( - failureMessage string - callerSkip int - ) - - var fakeFailHandler = func(message string, skip ...int) { - failureMessage = message - callerSkip = skip[0] - } - - BeforeEach(func() { - failureMessage = "" - callerSkip = 0 - }) - - Describe("Eventually", func() { - Context("the positive case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should continue when the matcher errors", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() interface{} { - counter++ - if counter == 5 { - return "not-a-number" //this should cause the matcher to error - } - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically(">", 100), "My description %d", 2) - - Ω(counter).Should(BeNumerically(">", 8)) - Ω(counter).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(MatchRegexp(`\: \d`), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("the negative case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter += 1 - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically("<", 3)) - - Ω(counter).Should(Equal(3)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should timeout when the matcher errors", func() { - a := New(AsyncAssertionTypeEventually, func() interface{} { - return 0 //this should cause the matcher to error - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(HaveLen(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - a := New(AsyncAssertionTypeEventually, func() int { - return 0 - }, fakeFailHandler, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Equal(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring(": 0"), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should eventually succeed if the additional arguments are nil", func() { - i := 0 - Eventually(func() (int, error) { - i++ - return i, nil - }).Should(Equal(10)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 0 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(Equal(2)) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool, 1) - c <- true - Eventually(c).Should(Receive()) - }) - }) - }) - - Describe("Consistently", func() { - Describe("The positive case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() string { - calls++ - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(calls).Should(BeNumerically(">", 8)) - Ω(calls).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return "bar" - } - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(failureMessage).Should(ContainSubstring("to equal")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return 3 - } - return []int{1, 2, 3} - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(HaveLen(3)) - Ω(failureMessage).Should(ContainSubstring("HaveLen matcher expects")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Describe("The negative case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - c := make(chan bool) - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - c := make(chan bool) - go func() { - time.Sleep(time.Duration(100 * time.Millisecond)) - c <- true - }() - - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(ContainSubstring("not to receive anything")) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - return calls - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically(">", 5)) - Ω(failureMessage).Should(ContainSubstring("not to be >")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should consistently succeed if the additional arguments are nil", func() { - i := 2 - Consistently(func() (int, error) { - i++ - return i, nil - }).Should(BeNumerically(">=", 2)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 2 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(BeNumerically(">=", 2)) - - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occured") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool) - Consistently(c).ShouldNot(Receive()) - }) - }) - }) - - Context("when passed a function with the wrong # or arguments & returns", func() { - It("should panic", func() { - Ω(func() { - New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - }) - }) - - Describe("bailing early", func() { - Context("when actual is a value", func() { - It("Eventually should bail out and fail early if the matcher says to", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when actual is a function", func() { - It("should never bail early", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(func() chan bool { - return c - }, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go deleted file mode 100644 index b9fbd6c6404..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package testingtsupport_test - -import ( - . "github.com/onsi/gomega" - - "testing" -) - -func TestTestingT(t *testing.T) { - RegisterTestingT(t) - Ω(true).Should(BeTrue()) -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go deleted file mode 100644 index d2280e0506d..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("AssignableToTypeOf", func() { - Context("When asserting assignability between types", func() { - It("should do the right thing", func() { - Ω(0).Should(BeAssignableToTypeOf(0)) - Ω(5).Should(BeAssignableToTypeOf(-1)) - Ω("foo").Should(BeAssignableToTypeOf("bar")) - Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) - - Ω(0).ShouldNot(BeAssignableToTypeOf("bar")) - Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{})) - Ω("foo").ShouldNot(BeAssignableToTypeOf(42)) - }) - }) - - Context("When asserting nil values", func() { - It("should error", func() { - success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_closed_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_closed_matcher_test.go deleted file mode 100644 index b2c40c91039..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_closed_matcher_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeClosedMatcher", func() { - Context("when passed a channel", func() { - It("should do the right thing", func() { - openChannel := make(chan bool) - Ω(openChannel).ShouldNot(BeClosed()) - - var openReaderChannel <-chan bool - openReaderChannel = openChannel - Ω(openReaderChannel).ShouldNot(BeClosed()) - - closedChannel := make(chan bool) - close(closedChannel) - - Ω(closedChannel).Should(BeClosed()) - - var closedReaderChannel <-chan bool - closedReaderChannel = closedChannel - Ω(closedReaderChannel).Should(BeClosed()) - }) - }) - - Context("when passed a send-only channel", func() { - It("should error", func() { - openChannel := make(chan bool) - var openWriterChannel chan<- bool - openWriterChannel = openChannel - - success, err := (&BeClosedMatcher{}).Match(openWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - closedChannel := make(chan bool) - close(closedChannel) - - var closedWriterChannel chan<- bool - closedWriterChannel = closedChannel - - success, err = (&BeClosedMatcher{}).Match(closedWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&BeClosedMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(7) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_empty_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_empty_matcher_test.go deleted file mode 100644 index 541c1b951ec..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_empty_matcher_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEmpty", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(BeEmpty()) - Ω(" ").ShouldNot(BeEmpty()) - - Ω([0]int{}).Should(BeEmpty()) - Ω([1]int{1}).ShouldNot(BeEmpty()) - - Ω([]int{}).Should(BeEmpty()) - Ω([]int{1}).ShouldNot(BeEmpty()) - - Ω(map[string]int{}).Should(BeEmpty()) - Ω(map[string]int{"a": 1}).ShouldNot(BeEmpty()) - - c := make(chan bool, 1) - Ω(c).Should(BeEmpty()) - c <- true - Ω(c).ShouldNot(BeEmpty()) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should be true", func() { - var nilSlice []int - Ω(nilSlice).Should(BeEmpty()) - - var nilMap map[int]string - Ω(nilMap).Should(BeEmpty()) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&BeEmptyMatcher{}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeEmptyMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go deleted file mode 100644 index def5104fa75..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEquivalentTo", func() { - Context("when asserting that nil is equivalent to nil", func() { - It("should error", func() { - success, err := (&BeEquivalentToMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting on nil", func() { - It("should do the right thing", func() { - Ω("foo").ShouldNot(BeEquivalentTo(nil)) - Ω(nil).ShouldNot(BeEquivalentTo(3)) - Ω([]int{1, 2}).ShouldNot(BeEquivalentTo(nil)) - }) - }) - - Context("When asserting on type aliases", func() { - It("should the right thing", func() { - Ω(StringAlias("foo")).Should(BeEquivalentTo("foo")) - Ω("foo").Should(BeEquivalentTo(StringAlias("foo"))) - Ω(StringAlias("foo")).ShouldNot(BeEquivalentTo("bar")) - Ω("foo").ShouldNot(BeEquivalentTo(StringAlias("bar"))) - }) - }) - - Context("When asserting on numbers", func() { - It("should convert actual to expected and do the right thing", func() { - Ω(5).Should(BeEquivalentTo(5)) - Ω(5.0).Should(BeEquivalentTo(5.0)) - Ω(5).Should(BeEquivalentTo(5.0)) - - Ω(5).ShouldNot(BeEquivalentTo("5")) - Ω(5).ShouldNot(BeEquivalentTo(3)) - - //Here be dragons! - Ω(5.1).Should(BeEquivalentTo(5)) - Ω(5).ShouldNot(BeEquivalentTo(5.1)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_false_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_false_matcher_test.go deleted file mode 100644 index 3965a2c5392..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_false_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeFalse", func() { - It("should handle true and false correctly", func() { - Ω(true).ShouldNot(BeFalse()) - Ω(false).Should(BeFalse()) - }) - - It("should only support booleans", func() { - success, err := (&BeFalseMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_nil_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_nil_matcher_test.go deleted file mode 100644 index 75332536329..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_nil_matcher_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeNil", func() { - It("should succeed when passed nil", func() { - Ω(nil).Should(BeNil()) - }) - - It("should succeed when passed a typed nil", func() { - var a []int - Ω(a).Should(BeNil()) - }) - - It("should succeed when passing nil pointer", func() { - var f *struct{} - Ω(f).Should(BeNil()) - }) - - It("should not succeed when not passed nil", func() { - Ω(0).ShouldNot(BeNil()) - Ω(false).ShouldNot(BeNil()) - Ω("").ShouldNot(BeNil()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go deleted file mode 100644 index 43fdb1fe0b6..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeNumerically", func() { - Context("when passed a number", func() { - It("should support ==", func() { - Ω(uint32(5)).Should(BeNumerically("==", 5)) - Ω(float64(5.0)).Should(BeNumerically("==", 5)) - Ω(int8(5)).Should(BeNumerically("==", 5)) - }) - - It("should not have false positives", func() { - Ω(5.1).ShouldNot(BeNumerically("==", 5)) - Ω(5).ShouldNot(BeNumerically("==", 5.1)) - }) - - It("should support >", func() { - Ω(uint32(5)).Should(BeNumerically(">", 4)) - Ω(float64(5.0)).Should(BeNumerically(">", 4.9)) - Ω(int8(5)).Should(BeNumerically(">", 4)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically(">", 5)) - }) - - It("should support <", func() { - Ω(uint32(5)).Should(BeNumerically("<", 6)) - Ω(float64(5.0)).Should(BeNumerically("<", 5.1)) - Ω(int8(5)).Should(BeNumerically("<", 6)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically("<", 5)) - }) - - It("should support >=", func() { - Ω(uint32(5)).Should(BeNumerically(">=", 4)) - Ω(float64(5.0)).Should(BeNumerically(">=", 4.9)) - Ω(int8(5)).Should(BeNumerically(">=", 4)) - - Ω(uint32(5)).Should(BeNumerically(">=", 5)) - Ω(float64(5.0)).Should(BeNumerically(">=", 5.0)) - Ω(int8(5)).Should(BeNumerically(">=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">=", 6)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1)) - Ω(int8(5)).ShouldNot(BeNumerically(">=", 6)) - }) - - It("should support <=", func() { - Ω(uint32(5)).Should(BeNumerically("<=", 6)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.1)) - Ω(int8(5)).Should(BeNumerically("<=", 6)) - - Ω(uint32(5)).Should(BeNumerically("<=", 5)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.0)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<=", 4)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - }) - - Context("when passed ~", func() { - Context("when passed a float", func() { - Context("and there is no precision parameter", func() { - It("should default to 1e-8", func() { - Ω(5.00000001).Should(BeNumerically("~", 5.00000002)) - Ω(5.00000001).ShouldNot(BeNumerically("~", 5.0000001)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use the precision parameter", func() { - Ω(5.1).Should(BeNumerically("~", 5.19, 0.1)) - Ω(5.1).Should(BeNumerically("~", 5.01, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1)) - }) - }) - }) - - Context("when passed an int/uint", func() { - Context("and there is no precision parameter", func() { - It("should just do strict equality", func() { - Ω(5).Should(BeNumerically("~", 5)) - Ω(5).ShouldNot(BeNumerically("~", 6)) - Ω(uint(5)).ShouldNot(BeNumerically("~", 6)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use precision paramter", func() { - Ω(5).Should(BeNumerically("~", 6, 2)) - Ω(5).ShouldNot(BeNumerically("~", 8, 2)) - Ω(uint(5)).Should(BeNumerically("~", 6, 1)) - }) - }) - }) - }) - }) - - Context("when passed a non-number", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{5}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "=="}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []interface{}{5}}).Match(4) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_sent_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_sent_matcher_test.go deleted file mode 100644 index 381c2b40289..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_sent_matcher_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package matchers_test - -import ( - "time" - . "github.com/onsi/gomega/matchers" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeSent", func() { - Context("when passed a channel and a matching type", func() { - Context("when the channel is ready to receive", func() { - It("should succeed and send the value down the channel", func() { - c := make(chan string) - d := make(chan string) - go func() { - val := <-c - d <- val - }() - - time.Sleep(10 * time.Millisecond) - - Ω(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - - It("should succeed (with a buffered channel)", func() { - c := make(chan string, 1) - Ω(c).Should(BeSent("foo")) - Ω(<-c).Should(Equal("foo")) - }) - }) - - Context("when the channel is not ready to receive", func() { - It("should fail and not send down the channel", func() { - c := make(chan string) - Ω(c).ShouldNot(BeSent("foo")) - Consistently(c).ShouldNot(Receive()) - }) - }) - - Context("when the channel is eventually ready to receive", func() { - It("should succeed", func() { - c := make(chan string) - d := make(chan string) - go func() { - time.Sleep(30 * time.Millisecond) - val := <-c - d <- val - }() - - Eventually(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - }) - - Context("when the channel is closed", func() { - It("should error", func() { - c := make(chan string) - close(c) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - - It("should short-circuit Eventually", func() { - c := make(chan string) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 10.0).Should(BeSent("foo")) - }) - Ω(failures).Should(HaveLen(1)) - Ω(time.Since(t)).Should(BeNumerically("<", time.Second)) - }) - }) - }) - - Context("when passed a channel and a non-matching type", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match(make(chan int, 1)) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a receive-only channel", func() { - It("should error", func() { - var c <-chan string - c = make(chan string, 1) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a nonchannel", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match("bar") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go deleted file mode 100644 index feb33e5dc13..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" - "time" -) - -var _ = Describe("BeTemporally", func() { - - var t0, t1, t2 time.Time - BeforeEach(func() { - t0 = time.Now() - t1 = t0.Add(time.Second) - t2 = t0.Add(-time.Second) - }) - - Context("When comparing times", func() { - - It("should support ==", func() { - Ω(t0).Should(BeTemporally("==", t0)) - Ω(t1).ShouldNot(BeTemporally("==", t0)) - Ω(t0).ShouldNot(BeTemporally("==", t1)) - Ω(t0).ShouldNot(BeTemporally("==", time.Time{})) - }) - - It("should support >", func() { - Ω(t0).Should(BeTemporally(">", t2)) - Ω(t0).ShouldNot(BeTemporally(">", t0)) - Ω(t2).ShouldNot(BeTemporally(">", t0)) - }) - - It("should support <", func() { - Ω(t0).Should(BeTemporally("<", t1)) - Ω(t0).ShouldNot(BeTemporally("<", t0)) - Ω(t1).ShouldNot(BeTemporally("<", t0)) - }) - - It("should support >=", func() { - Ω(t0).Should(BeTemporally(">=", t2)) - Ω(t0).Should(BeTemporally(">=", t0)) - Ω(t0).ShouldNot(BeTemporally(">=", t1)) - }) - - It("should support <=", func() { - Ω(t0).Should(BeTemporally("<=", t1)) - Ω(t0).Should(BeTemporally("<=", t0)) - Ω(t0).ShouldNot(BeTemporally("<=", t2)) - }) - - Context("when passed ~", func() { - Context("and there is no precision parameter", func() { - BeforeEach(func() { - t1 = t0.Add(time.Millisecond / 2) - t2 = t0.Add(-2 * time.Millisecond) - }) - It("should approximate", func() { - Ω(t0).Should(BeTemporally("~", t0)) - Ω(t0).Should(BeTemporally("~", t1)) - Ω(t0).ShouldNot(BeTemporally("~", t2)) - }) - }) - - Context("and there is a precision parameter", func() { - BeforeEach(func() { - t2 = t0.Add(3 * time.Second) - }) - It("should use precision paramter", func() { - d := 2 * time.Second - Ω(t0).Should(BeTemporally("~", t0, d)) - Ω(t0).Should(BeTemporally("~", t1, d)) - Ω(t0).ShouldNot(BeTemporally("~", t2, d)) - }) - }) - }) - }) - - Context("when passed a non-time", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "==", CompareTo: t0}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeTemporallyMatcher{Comparator: "=="}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "!=", CompareTo: t0}).Match(t2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_true_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_true_matcher_test.go deleted file mode 100644 index ca32e56beaf..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_true_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeTrue", func() { - It("should handle true and false correctly", func() { - Ω(true).Should(BeTrue()) - Ω(false).ShouldNot(BeTrue()) - }) - - It("should only support booleans", func() { - success, err := (&BeTrueMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_zero_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_zero_matcher_test.go deleted file mode 100644 index 8ec3643c28a..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/be_zero_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeZero", func() { - It("should succeed if the passed in object is the zero value for its type", func() { - Ω(nil).Should(BeZero()) - - Ω("").Should(BeZero()) - Ω(" ").ShouldNot(BeZero()) - - Ω(0).Should(BeZero()) - Ω(1).ShouldNot(BeZero()) - - Ω(0.0).Should(BeZero()) - Ω(0.1).ShouldNot(BeZero()) - - // Ω([]int{}).Should(BeZero()) - Ω([]int{1}).ShouldNot(BeZero()) - - // Ω(map[string]int{}).Should(BeZero()) - Ω(map[string]int{"a": 1}).ShouldNot(BeZero()) - - Ω(myCustomType{}).Should(BeZero()) - Ω(myCustomType{s: "a"}).ShouldNot(BeZero()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/consist_of_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/consist_of_test.go deleted file mode 100644 index 0b230e390b2..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/consist_of_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ConsistOf", func() { - Context("with a slice", func() { - It("should do the right thing", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with an array", func() { - It("should do the right thing", func() { - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with a map", func() { - It("should apply to the values", func() { - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - - }) - - Context("with anything else", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("foo").Should(ConsistOf("f", "o", "o")) - }) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when passed matchers", func() { - It("should pass if the matchers pass", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), "baz")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("foo"))) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("turducken"))) - }) - - It("should not depend on the order of the matchers", func() { - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(1), ContainElement(2))) - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(2), ContainElement(1))) - }) - - Context("when a matcher errors", func() { - It("should soldier on", func() { - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar")) - Ω([]interface{}{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar")) - }) - }) - }) - - Context("when passed exactly one argument, and that argument is a slice", func() { - It("should match against the elements of that argument", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf([]string{"foo", "bar", "baz"})) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_element_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_element_matcher_test.go deleted file mode 100644 index 4d29eeb5bf2..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_element_matcher_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainElement", func() { - Context("when passed a supported type", func() { - Context("and expecting a non-matcher", func() { - It("should do the right thing", func() { - Ω([2]int{1, 2}).Should(ContainElement(2)) - Ω([2]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω([]int{1, 2}).Should(ContainElement(2)) - Ω([]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(2)) - Ω(map[int]int{3: 1, 4: 2}).ShouldNot(ContainElement(3)) - - arr := make([]myCustomType, 2) - arr[0] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}} - arr[1] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "c"}} - Ω(arr).Should(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(arr).ShouldNot(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"b", "c"}})) - }) - }) - - Context("and expecting a matcher", func() { - It("should pass each element through the matcher", func() { - Ω([]int{1, 2, 3}).Should(ContainElement(BeNumerically(">=", 3))) - Ω([]int{1, 2, 3}).ShouldNot(ContainElement(BeNumerically(">", 3))) - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(BeNumerically(">=", 2))) - Ω(map[string]int{"foo": 1, "bar": 2}).ShouldNot(ContainElement(BeNumerically(">", 2))) - }) - - It("should fail if the matcher ever fails", func() { - actual := []interface{}{1, 2, "3", 4} - success, err := (&ContainElementMatcher{Element: BeNumerically(">=", 3)}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).ShouldNot(ContainElement(1)) - - var nilMap map[int]string - Ω(nilMap).ShouldNot(ContainElement("foo")) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&ContainElementMatcher{Element: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match("abc") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go deleted file mode 100644 index 6935168e5c0..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainSubstringMatcher", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω("Marvelous").Should(ContainSubstring("rve")) - Ω("Marvelous").ShouldNot(ContainSubstring("boo")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("Marvelous3").Should(ContainSubstring("velous%d", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(ContainSubstring("bc3")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&ContainSubstringMatcher{Substr: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/equal_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/equal_matcher_test.go deleted file mode 100644 index ef0d137dda4..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/equal_matcher_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package matchers_test - -import ( - "errors" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Equal", func() { - Context("when asserting that nil equals nil", func() { - It("should error", func() { - success, err := (&EqualMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting equality between objects", func() { - It("should do the right thing", func() { - Ω(5).Should(Equal(5)) - Ω(5.0).Should(Equal(5.0)) - - Ω(5).ShouldNot(Equal("5")) - Ω(5).ShouldNot(Equal(5.0)) - Ω(5).ShouldNot(Equal(3)) - - Ω("5").Should(Equal("5")) - Ω([]int{1, 2}).Should(Equal([]int{1, 2})) - Ω([]int{1, 2}).ShouldNot(Equal([]int{2, 1})) - Ω(map[string]string{"a": "b", "c": "d"}).Should(Equal(map[string]string{"a": "b", "c": "d"})) - Ω(map[string]string{"a": "b", "c": "d"}).ShouldNot(Equal(map[string]string{"a": "b", "c": "e"})) - Ω(errors.New("foo")).Should(Equal(errors.New("foo"))) - Ω(errors.New("foo")).ShouldNot(Equal(errors.New("bar"))) - - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).Should(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "bar", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 2, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 3.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b", "c"}})) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_matcher_test.go deleted file mode 100644 index c663e302bac..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_matcher_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKey", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]string - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]string{customA: "aardvark", customB: "kangaroo"} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKey("foo")) - Ω(stringKeys).ShouldNot(HaveKey("baz")) - - Ω(intKeys).Should(HaveKey(2)) - Ω(intKeys).ShouldNot(HaveKey(4)) - - Ω(objKeys).Should(HaveKey(customA)) - Ω(objKeys).Should(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}})) - Ω(objKeys).ShouldNot(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}})) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKey("foo")) - }) - }) - - Context("when the passed in key is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKey(ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKey(ContainSubstring("foobar"))) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyMatcher{Key: ContainSubstring("ar")}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyMatcher{Key: "foo"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyMatcher{Key: "foo"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go deleted file mode 100644 index 06a2242aeca..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKeyWithValue", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]*myCustomType - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]*myCustomType{customA: customA, customB: customA} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKeyWithValue("foo", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("foo", 1)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 1)) - - Ω(intKeys).Should(HaveKeyWithValue(2, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(4, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(2, "baz")) - - Ω(objKeys).Should(HaveKeyWithValue(customA, customA)) - Ω(objKeys).Should(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}, &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}})) - Ω(objKeys).ShouldNot(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}}, customA)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKeyWithValue("foo", "bar")) - }) - }) - - Context("when the passed in key or value is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKeyWithValue(ContainSubstring("oo"), 2)) - Ω(intKeys).Should(HaveKeyWithValue(2, ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKeyWithValue(ContainSubstring("foobar"), 2)) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyWithValueMatcher{Key: ContainSubstring("ar"), Value: 2}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - otherActual := map[string]int{"a": 1, "b": 2, "c": 3} - success, err = (&HaveKeyWithValueMatcher{Key: "a", Value: ContainSubstring("1")}).Match(otherActual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_len_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_len_matcher_test.go deleted file mode 100644 index 1e6aa69d9d1..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_len_matcher_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveLen", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(HaveLen(0)) - Ω("AA").Should(HaveLen(2)) - - Ω([0]int{}).Should(HaveLen(0)) - Ω([2]int{1, 2}).Should(HaveLen(2)) - - Ω([]int{}).Should(HaveLen(0)) - Ω([]int{1, 2, 3}).Should(HaveLen(3)) - - Ω(map[string]int{}).Should(HaveLen(0)) - Ω(map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}).Should(HaveLen(4)) - - c := make(chan bool, 3) - Ω(c).Should(HaveLen(0)) - c <- true - c <- true - Ω(c).Should(HaveLen(2)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).Should(HaveLen(0)) - - var nilMap map[int]string - Ω(nilMap).Should(HaveLen(0)) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&HaveLenMatcher{Count: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveLenMatcher{Count: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go deleted file mode 100644 index ef971aa6fd3..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers_test - -import ( - "errors" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveOccurred", func() { - It("should succeed if matching an error", func() { - Ω(errors.New("Foo")).Should(HaveOccurred()) - }) - - It("should not succeed with nil", func() { - Ω(nil).ShouldNot(HaveOccurred()) - }) - - It("should only support errors and nil", func() { - success, err := (&HaveOccurredMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveOccurredMatcher{}).Match("") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go deleted file mode 100644 index bec3f975827..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HavePrefixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string prefix", func() { - Ω("Ab").Should(HavePrefix("A")) - Ω("A").ShouldNot(HavePrefix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HavePrefix("C%dP", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HavePrefix("A")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HavePrefixMatcher{Prefix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go deleted file mode 100644 index 72e8975bae0..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveSuffixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string suffix", func() { - Ω("Ab").Should(HaveSuffix("b")) - Ω("A").ShouldNot(HaveSuffix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HaveSuffix("%dPO", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HaveSuffix("b")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HaveSuffixMatcher{Suffix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_error_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_error_matcher_test.go deleted file mode 100644 index 338b5129543..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_error_matcher_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package matchers_test - -import ( - "errors" - "fmt" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type CustomError struct { -} - -func (c CustomError) Error() string { - return "an error" -} - -var _ = Describe("MatchErrorMatcher", func() { - Context("When asserting against an error", func() { - It("should succeed when matching with an error", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError(errors.New("an error"))) - Ω(err).ShouldNot(MatchError(errors.New("another error"))) - - Ω(fmtErr).Should(MatchError(errors.New("an error"))) - Ω(customErr).Should(MatchError(CustomError{})) - }) - - It("should succeed when matching with a string", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError("an error")) - Ω(err).ShouldNot(MatchError("another error")) - - Ω(fmtErr).Should(MatchError("an error")) - Ω(customErr).Should(MatchError("an error")) - }) - - Context("when passed a matcher", func() { - It("should pass if the matcher passes against the error string", func() { - err := errors.New("error 123 abc") - - Ω(err).Should(MatchError(MatchRegexp(`\d{3}`))) - }) - - It("should fail if the matcher fails against the error string", func() { - err := errors.New("no digits") - Ω(err).ShouldNot(MatchError(MatchRegexp(`\d`))) - }) - }) - - It("should fail when passed anything else", func() { - actualErr := errors.New("an error") - _, err := (&MatchErrorMatcher{ - Expected: []byte("an error"), - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: 3, - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed nil", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match(nil) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a non-error", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match("an error") - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: "an error", - }).Match(3) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_json_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_json_matcher_test.go deleted file mode 100644 index c1924baac2d..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_json_matcher_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchJSONMatcher", func() { - Context("When passed stringifiables", func() { - It("should succeed if the JSON matches", func() { - Ω("{}").Should(MatchJSON("{}")) - Ω(`{"a":1}`).Should(MatchJSON(`{"a":1}`)) - Ω(`{ - "a":1 - }`).Should(MatchJSON(`{"a":1}`)) - Ω(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`)) - Ω(`{"a":1}`).ShouldNot(MatchJSON(`{"b":2, "a":1}`)) - }) - - It("should work with byte arrays", func() { - Ω([]byte("{}")).Should(MatchJSON([]byte("{}"))) - Ω("{}").Should(MatchJSON([]byte("{}"))) - Ω([]byte("{}")).Should(MatchJSON("{}")) - }) - }) - - Context("when either side is not valid JSON", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: `oops`}).Match(`{}`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when either side is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: 2}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: nil}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&MatchJSONMatcher{JSONToMatch: 2}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go deleted file mode 100644 index bb521cce347..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchRegexp", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω(" a2!bla").Should(MatchRegexp(`\d!`)) - Ω(" a2!bla").ShouldNot(MatchRegexp(`[A-Z]`)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(MatchRegexp(`[A-Z][a-z]+\d`)) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω(" a23!bla").Should(MatchRegexp(`\d%d!`, 3)) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: `\d`}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when the passed in regexp fails to compile", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: "("}).Match("Foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go deleted file mode 100644 index 4bc6d9d0c27..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package matchers_test - -import ( - "testing" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type myStringer struct { - a string -} - -func (s *myStringer) String() string { - return s.a -} - -type StringAlias string - -type myCustomType struct { - s string - n int - f float32 - arr []string -} - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Gomega") -} diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/panic_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/panic_matcher_test.go deleted file mode 100644 index 17f3935e64b..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/panic_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Panic", func() { - Context("when passed something that's not a function that takes zero arguments and returns nothing", func() { - It("should error", func() { - success, err := (&PanicMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func(foo string) {}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func() string { return "bar" }) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a function of the correct type", func() { - It("should call the function and pass if the function panics", func() { - Ω(func() { panic("ack!") }).Should(Panic()) - Ω(func() {}).ShouldNot(Panic()) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/receive_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/receive_matcher_test.go deleted file mode 100644 index 938c078e6f7..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/receive_matcher_test.go +++ /dev/null @@ -1,280 +0,0 @@ -package matchers_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type kungFuActor interface { - DrunkenMaster() bool -} - -type jackie struct { - name string -} - -func (j *jackie) DrunkenMaster() bool { - return true -} - -var _ = Describe("ReceiveMatcher", func() { - Context("with no argument", func() { - Context("for a buffered channel", func() { - It("should succeed", func() { - channel := make(chan bool, 1) - - Ω(channel).ShouldNot(Receive()) - - channel <- true - - Ω(channel).Should(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should succeed (eventually)", func() { - channel := make(chan bool) - - Ω(channel).ShouldNot(Receive()) - - go func() { - time.Sleep(10 * time.Millisecond) - channel <- true - }() - - Eventually(channel).Should(Receive()) - }) - }) - }) - - Context("with a pointer argument", func() { - Context("of the correct type", func() { - It("should write the value received on the channel to the pointer", func() { - channel := make(chan int, 1) - - var value int - - Ω(channel).ShouldNot(Receive(&value)) - Ω(value).Should(BeZero()) - - channel <- 17 - - Ω(channel).Should(Receive(&value)) - Ω(value).Should(Equal(17)) - }) - }) - - Context("to various types of objects", func() { - It("should work", func() { - //channels of strings - stringChan := make(chan string, 1) - stringChan <- "foo" - - var s string - Ω(stringChan).Should(Receive(&s)) - Ω(s).Should(Equal("foo")) - - //channels of slices - sliceChan := make(chan []bool, 1) - sliceChan <- []bool{true, true, false} - - var sl []bool - Ω(sliceChan).Should(Receive(&sl)) - Ω(sl).Should(Equal([]bool{true, true, false})) - - //channels of channels - chanChan := make(chan chan bool, 1) - c := make(chan bool) - chanChan <- c - - var receivedC chan bool - Ω(chanChan).Should(Receive(&receivedC)) - Ω(receivedC).Should(Equal(c)) - - //channels of interfaces - jackieChan := make(chan kungFuActor, 1) - aJackie := &jackie{name: "Jackie Chan"} - jackieChan <- aJackie - - var theJackie kungFuActor - Ω(jackieChan).Should(Receive(&theJackie)) - Ω(theJackie).Should(Equal(aJackie)) - }) - }) - - Context("of the wrong type", func() { - It("should error", func() { - channel := make(chan int) - var incorrectType bool - - success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - var notAPointer int - success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("with a matcher", func() { - It("should defer to the underlying matcher", func() { - intChannel := make(chan int, 1) - intChannel <- 3 - Ω(intChannel).Should(Receive(Equal(3))) - - intChannel <- 2 - Ω(intChannel).ShouldNot(Receive(Equal(3))) - - stringChannel := make(chan []string, 1) - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo")))) - - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago")))) - }) - - It("should defer to the underlying matcher for the message", func() { - matcher := Receive(Equal(3)) - channel := make(chan int, 1) - channel <- 2 - matcher.Match(channel) - Ω(matcher.FailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 2\s+to equal\s+: 3`)) - - channel <- 3 - matcher.Match(channel) - Ω(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 3\s+not to equal\s+: 3`)) - }) - - It("should work just fine with Eventually", func() { - stringChannel := make(chan string) - - go func() { - time.Sleep(5 * time.Millisecond) - stringChannel <- "A" - time.Sleep(5 * time.Millisecond) - stringChannel <- "B" - }() - - Eventually(stringChannel).Should(Receive(Equal("B"))) - }) - - Context("if the matcher errors", func() { - It("should error", func() { - channel := make(chan int, 1) - channel <- 3 - success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if nothing is received", func() { - It("should fail", func() { - channel := make(chan int, 1) - success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).ShouldNot(HaveOccurred()) - }) - }) - }) - - Context("When actual is a *closed* channel", func() { - Context("for a buffered channel", func() { - It("should work until it hits the end of the buffer", func() { - channel := make(chan bool, 1) - channel <- true - - close(channel) - - Ω(channel).Should(Receive()) - Ω(channel).ShouldNot(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should always fail", func() { - channel := make(chan bool) - close(channel) - - Ω(channel).ShouldNot(Receive()) - }) - }) - }) - - Context("When actual is a send-only channel", func() { - It("should error", func() { - channel := make(chan bool) - - var writerChannel chan<- bool - writerChannel = channel - - success, err := (&ReceiveMatcher{}).Match(writerChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when acutal is a non-channel", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&ReceiveMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(3) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Describe("when used with eventually and a custom matcher", func() { - It("should return the matcher's error when a failing value is received on the channel, instead of the must receive something failure", func() { - failures := InterceptGomegaFailures(func() { - c := make(chan string, 0) - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring("When passed a matcher, ReceiveMatcher's channel *must* receive something.")) - - failures = InterceptGomegaFailures(func() { - c := make(chan string, 1) - c <- "hi" - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring(": hello")) - }) - }) - - Describe("Bailing early", func() { - It("should bail early when passed a closed channel", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - - It("should bail early when passed a non-channel", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(3).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - }) -}) diff --git a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/succeed_matcher_test.go b/Godeps/_workspace/src/github.com/onsi/gomega/matchers/succeed_matcher_test.go deleted file mode 100644 index 3562e7049de..00000000000 --- a/Godeps/_workspace/src/github.com/onsi/gomega/matchers/succeed_matcher_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package matchers_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -func Erroring() error { - return errors.New("bam") -} - -func NotErroring() error { - return nil -} - -type AnyType struct{} - -func Invalid() *AnyType { - return nil -} - -var _ = Describe("Succeed", func() { - It("should succeed if the function succeeds", func() { - Ω(NotErroring()).Should(Succeed()) - }) - - It("should succeed (in the negated) if the function errored", func() { - Ω(Erroring()).ShouldNot(Succeed()) - }) - - It("should not if passed a non-error", func() { - success, err := (&SucceedMatcher{}).Match(Invalid()) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go deleted file mode 100644 index b5eae092472..00000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/json" - "reflect" - "testing" -) - -var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - -func TestJSON(t *testing.T) { - type S struct { - ID1 UUID - ID2 UUID - } - s1 := S{ID1: testUUID} - data, err := json.Marshal(&s1) - if err != nil { - t.Fatal(err) - } - var s2 S - if err := json.Unmarshal(data, &s2); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(&s1, &s2) { - t.Errorf("got %#v, want %#v", s2, s1) - } -} diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go deleted file mode 100644 index 3b3d1430d51..00000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "flag" - "runtime" - "testing" - "time" -) - -// This test is only run when --regressions is passed on the go test line. -var regressions = flag.Bool("regressions", false, "run uuid regression tests") - -// TestClockSeqRace tests for a particular race condition of returning two -// identical Version1 UUIDs. The duration of 1 minute was chosen as the race -// condition, before being fixed, nearly always occured in under 30 seconds. -func TestClockSeqRace(t *testing.T) { - if !*regressions { - t.Skip("skipping regression tests") - } - duration := time.Minute - - done := make(chan struct{}) - defer close(done) - - ch := make(chan UUID, 10000) - ncpu := runtime.NumCPU() - switch ncpu { - case 0, 1: - // We can't run the test effectively. - t.Skip("skipping race test, only one CPU detected") - return - default: - runtime.GOMAXPROCS(ncpu) - } - for i := 0; i < ncpu; i++ { - go func() { - for { - select { - case <-done: - return - case ch <- NewUUID(): - } - } - }() - } - - uuids := make(map[string]bool) - cnt := 0 - start := time.Now() - for u := range ch { - s := u.String() - if uuids[s] { - t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) - return - } - uuids[s] = true - if time.Since(start) > duration { - return - } - cnt++ - } -} diff --git a/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go b/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go deleted file mode 100644 index 417ebeb26aa..00000000000 --- a/Godeps/_workspace/src/github.com/pborman/uuid/uuid_test.go +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" - "time" -) - -type test struct { - in string - version Version - variant Variant - isuuid bool -} - -var tests = []test{ - {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true}, - {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true}, - {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true}, - {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true}, - {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true}, - {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true}, - {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true}, - {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true}, - {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true}, - {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true}, - {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true}, - {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true}, - {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true}, - {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true}, - - {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true}, - {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true}, - - {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false}, - {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false}, -} - -var constants = []struct { - c interface{} - name string -}{ - {Person, "Person"}, - {Group, "Group"}, - {Org, "Org"}, - {Invalid, "Invalid"}, - {RFC4122, "RFC4122"}, - {Reserved, "Reserved"}, - {Microsoft, "Microsoft"}, - {Future, "Future"}, - {Domain(17), "Domain17"}, - {Variant(42), "BadVariant42"}, -} - -func testTest(t *testing.T, in string, tt test) { - uuid := Parse(in) - if ok := (uuid != nil); ok != tt.isuuid { - t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid) - } - if uuid == nil { - return - } - - if v := uuid.Variant(); v != tt.variant { - t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant) - } - if v, _ := uuid.Version(); v != tt.version { - t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version) - } -} - -func TestUUID(t *testing.T) { - for _, tt := range tests { - testTest(t, tt.in, tt) - testTest(t, strings.ToUpper(tt.in), tt) - } -} - -func TestConstants(t *testing.T) { - for x, tt := range constants { - v, ok := tt.c.(fmt.Stringer) - if !ok { - t.Errorf("%x: %v: not a stringer", x, v) - } else if s := v.String(); s != tt.name { - v, _ := tt.c.(int) - t.Errorf("%x: Constant %T:%d gives %q, expected %q\n", x, tt.c, v, s, tt.name) - } - } -} - -func TestRandomUUID(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - uuid := NewRandom() - s := uuid.String() - if m[s] { - t.Errorf("NewRandom returned duplicated UUID %s\n", s) - } - m[s] = true - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s\n", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d\n", uuid.Variant()) - } - } -} - -func TestNew(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - s := New() - if m[s] { - t.Errorf("New returned duplicated UUID %s\n", s) - } - m[s] = true - uuid := Parse(s) - if uuid == nil { - t.Errorf("New returned %q which does not decode\n", s) - continue - } - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s\n", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d\n", uuid.Variant()) - } - } -} - -func clockSeq(t *testing.T, uuid UUID) int { - seq, ok := uuid.ClockSequence() - if !ok { - t.Fatalf("%s: invalid clock sequence\n", uuid) - } - return seq -} - -func TestClockSeq(t *testing.T) { - // Fake time.Now for this test to return a monotonically advancing time; restore it at end. - defer func(orig func() time.Time) { timeNow = orig }(timeNow) - monTime := time.Now() - timeNow = func() time.Time { - monTime = monTime.Add(1 * time.Second) - return monTime - } - - SetClockSequence(-1) - uuid1 := NewUUID() - uuid2 := NewUUID() - - if clockSeq(t, uuid1) != clockSeq(t, uuid2) { - t.Errorf("clock sequence %d != %d\n", clockSeq(t, uuid1), clockSeq(t, uuid2)) - } - - SetClockSequence(-1) - uuid2 = NewUUID() - - // Just on the very off chance we generated the same sequence - // two times we try again. - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - SetClockSequence(-1) - uuid2 = NewUUID() - } - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - t.Errorf("Duplicate clock sequence %d\n", clockSeq(t, uuid1)) - } - - SetClockSequence(0x1234) - uuid1 = NewUUID() - if seq := clockSeq(t, uuid1); seq != 0x1234 { - t.Errorf("%s: expected seq 0x1234 got 0x%04x\n", uuid1, seq) - } -} - -func TestCoding(t *testing.T) { - text := "7d444840-9dc0-11d1-b245-5ffdce74fad2" - urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2" - data := UUID{ - 0x7d, 0x44, 0x48, 0x40, - 0x9d, 0xc0, - 0x11, 0xd1, - 0xb2, 0x45, - 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, - } - if v := data.String(); v != text { - t.Errorf("%x: encoded to %s, expected %s\n", data, v, text) - } - if v := data.URN(); v != urn { - t.Errorf("%x: urn is %s, expected %s\n", data, v, urn) - } - - uuid := Parse(text) - if !Equal(uuid, data) { - t.Errorf("%s: decoded to %s, expected %s\n", text, uuid, data) - } -} - -func TestVersion1(t *testing.T) { - uuid1 := NewUUID() - uuid2 := NewUUID() - - if Equal(uuid1, uuid2) { - t.Errorf("%s:duplicate uuid\n", uuid1) - } - if v, _ := uuid1.Version(); v != 1 { - t.Errorf("%s: version %s expected 1\n", uuid1, v) - } - if v, _ := uuid2.Version(); v != 1 { - t.Errorf("%s: version %s expected 1\n", uuid2, v) - } - n1 := uuid1.NodeID() - n2 := uuid2.NodeID() - if !bytes.Equal(n1, n2) { - t.Errorf("Different nodes %x != %x\n", n1, n2) - } - t1, ok := uuid1.Time() - if !ok { - t.Errorf("%s: invalid time\n", uuid1) - } - t2, ok := uuid2.Time() - if !ok { - t.Errorf("%s: invalid time\n", uuid2) - } - q1, ok := uuid1.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence\n", uuid1) - } - q2, ok := uuid2.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence", uuid2) - } - - switch { - case t1 == t2 && q1 == q2: - t.Errorf("time stopped\n") - case t1 > t2 && q1 == q2: - t.Errorf("time reversed\n") - case t1 < t2 && q1 != q2: - t.Errorf("clock sequence chaned unexpectedly\n") - } -} - -func TestNodeAndTime(t *testing.T) { - // Time is February 5, 1998 12:30:23.136364800 AM GMT - - uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2") - node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2} - - ts, ok := uuid.Time() - if ok { - c := time.Unix(ts.UnixTime()) - want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC) - if !c.Equal(want) { - t.Errorf("Got time %v, want %v", c, want) - } - } else { - t.Errorf("%s: bad time\n", uuid) - } - if !bytes.Equal(node, uuid.NodeID()) { - t.Errorf("Expected node %v got %v\n", node, uuid.NodeID()) - } -} - -func TestMD5(t *testing.T) { - uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String() - want := "6fa459ea-ee8a-3ca4-894e-db77e160355e" - if uuid != want { - t.Errorf("MD5: got %q expected %q\n", uuid, want) - } -} - -func TestSHA1(t *testing.T) { - uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String() - want := "886313e1-3b8a-5372-9b90-0c9aee199e5d" - if uuid != want { - t.Errorf("SHA1: got %q expected %q\n", uuid, want) - } -} - -func TestNodeID(t *testing.T) { - nid := []byte{1, 2, 3, 4, 5, 6} - SetNodeInterface("") - s := NodeInterface() - if s == "" || s == "user" { - t.Errorf("NodeInterface %q after SetInteface\n", s) - } - node1 := NodeID() - if node1 == nil { - t.Errorf("NodeID nil after SetNodeInterface\n", s) - } - SetNodeID(nid) - s = NodeInterface() - if s != "user" { - t.Errorf("Expected NodeInterface %q got %q\n", "user", s) - } - node2 := NodeID() - if node2 == nil { - t.Errorf("NodeID nil after SetNodeID\n", s) - } - if bytes.Equal(node1, node2) { - t.Errorf("NodeID not changed after SetNodeID\n", s) - } else if !bytes.Equal(nid, node2) { - t.Errorf("NodeID is %x, expected %x\n", node2, nid) - } -} - -func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) { - if uuid == nil { - t.Errorf("%s failed\n", name) - return - } - if v, _ := uuid.Version(); v != 2 { - t.Errorf("%s: %s: expected version 2, got %s\n", name, uuid, v) - return - } - if v, ok := uuid.Domain(); !ok || v != domain { - if !ok { - t.Errorf("%s: %d: Domain failed\n", name, uuid) - } else { - t.Errorf("%s: %s: expected domain %d, got %d\n", name, uuid, domain, v) - } - } - if v, ok := uuid.Id(); !ok || v != id { - if !ok { - t.Errorf("%s: %d: Id failed\n", name, uuid) - } else { - t.Errorf("%s: %s: expected id %d, got %d\n", name, uuid, id, v) - } - } -} - -func TestDCE(t *testing.T) { - testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678) - testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid())) - testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid())) -} - -type badRand struct{} - -func (r badRand) Read(buf []byte) (int, error) { - for i, _ := range buf { - buf[i] = byte(i) - } - return len(buf), nil -} - -func TestBadRand(t *testing.T) { - SetRand(badRand{}) - uuid1 := New() - uuid2 := New() - if uuid1 != uuid2 { - t.Errorf("execpted duplicates, got %q and %q\n", uuid1, uuid2) - } - SetRand(nil) - uuid1 = New() - uuid2 = New() - if uuid1 == uuid2 { - t.Errorf("unexecpted duplicates, got %q\n", uuid1) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go deleted file mode 100644 index 6ae7333fcc9..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/benchmark_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "testing" -) - -func BenchmarkCounterWithLabelValues(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } -} - -func BenchmarkCounterWithMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() - } -} - -func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} - for i := 0; i < b.N; i++ { - m.With(labels).Inc() - } -} - -func BenchmarkCounterNoLabels(b *testing.B) { - m := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Inc() - } -} - -func BenchmarkGaugeWithLabelValues(b *testing.B) { - m := NewGaugeVec( - GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) - } -} - -func BenchmarkGaugeNoLabels(b *testing.B) { - m := NewGauge(GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Set(3.1415) - } -} - -func BenchmarkSummaryWithLabelValues(b *testing.B) { - m := NewSummaryVec( - SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkSummaryNoLabels(b *testing.B) { - m := NewSummary(SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkHistogramWithLabelValues(b *testing.B) { - m := NewHistogramVec( - HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkHistogramNoLabels(b *testing.B) { - m := NewHistogram(HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go deleted file mode 100644 index 67391a23aa8..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/counter_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestCounterAdd(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }).(*counter) - counter.Inc() - if expected, got := 1., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - counter.Add(42) - if expected, got := 43., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - - if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { - t.Errorf("Expected error %q, got %q.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `label: label: counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func decreaseCounter(c *counter) (err error) { - defer func() { - if e := recover(); e != nil { - err = e.(error) - } - }() - c.Add(-1) - return nil -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go deleted file mode 100644 index 6f3e215d47b..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "sync" - - "github.com/prometheus/client_golang/prometheus" -) - -// ClusterManager is an example for a system that might have been built without -// Prometheus in mind. It models a central manager of jobs running in a -// cluster. To turn it into something that collects Prometheus metrics, we -// simply add the two methods required for the Collector interface. -// -// An additional challenge is that multiple instances of the ClusterManager are -// run within the same binary, each in charge of a different zone. We need to -// make use of ConstLabels to be able to register each ClusterManager instance -// with Prometheus. -type ClusterManager struct { - Zone string - OOMCount *prometheus.CounterVec - RAMUsage *prometheus.GaugeVec - mtx sync.Mutex // Protects OOMCount and RAMUsage. - // ... many more fields -} - -// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a -// real cluster manager would have to do. Since it may actually be really -// expensive, it must only be called once per collection. This implementation, -// obviously, only returns some made-up data. -func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( - oomCountByHost map[string]int, ramUsageByHost map[string]float64, -) { - // Just example fake data. - oomCountByHost = map[string]int{ - "foo.example.org": 42, - "bar.example.org": 2001, - } - ramUsageByHost = map[string]float64{ - "foo.example.org": 6.023e23, - "bar.example.org": 3.14, - } - return -} - -// Describe faces the interesting challenge that the two metric vectors that are -// used in this example are already Collectors themselves. However, thanks to -// the use of channels, it is really easy to "chain" Collectors. Here we simply -// call the Describe methods of the two metric vectors. -func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { - c.OOMCount.Describe(ch) - c.RAMUsage.Describe(ch) -} - -// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it -// sets the retrieved values in the two metric vectors and then sends all their -// metrics to the channel (again using a chaining technique as in the Describe -// method). Since Collect could be called multiple times concurrently, that part -// is protected by a mutex. -func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { - oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() - c.mtx.Lock() - defer c.mtx.Unlock() - for host, oomCount := range oomCountByHost { - c.OOMCount.WithLabelValues(host).Set(float64(oomCount)) - } - for host, ramUsage := range ramUsageByHost { - c.RAMUsage.WithLabelValues(host).Set(ramUsage) - } - c.OOMCount.Collect(ch) - c.RAMUsage.Collect(ch) - // All metrics in OOMCount and RAMUsage are sent to the channel now. We - // can safely reset the two metric vectors now, so that we can start - // fresh in the next Collect cycle. (Imagine a host disappears from the - // cluster. If we did not reset here, its Metric would stay in the - // metric vectors forever.) - c.OOMCount.Reset() - c.RAMUsage.Reset() -} - -// NewClusterManager creates the two metric vectors OOMCount and RAMUsage. Note -// that the zone is set as a ConstLabel. (It's different in each instance of the -// ClusterManager, but constant over the lifetime of an instance.) The reported -// values are partitioned by host, which is therefore a variable label. -func NewClusterManager(zone string) *ClusterManager { - return &ClusterManager{ - Zone: zone, - OOMCount: prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "clustermanager", - Name: "oom_count", - Help: "number of OOM crashes", - ConstLabels: prometheus.Labels{"zone": zone}, - }, - []string{"host"}, - ), - RAMUsage: prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Subsystem: "clustermanager", - Name: "ram_usage_bytes", - Help: "RAM usage as reported to the cluster manager", - ConstLabels: prometheus.Labels{"zone": zone}, - }, - []string{"host"}, - ), - } -} - -func ExampleCollector_clustermanager() { - workerDB := NewClusterManager("db") - workerCA := NewClusterManager("ca") - prometheus.MustRegister(workerDB) - prometheus.MustRegister(workerCA) - - // Since we are dealing with custom Collector implementations, it might - // be a good idea to enable the collect checks in the registry. - prometheus.EnableCollectChecks(true) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go deleted file mode 100644 index a84d072504e..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_memstats_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "runtime" - - "github.com/prometheus/client_golang/prometheus" -) - -var ( - allocDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "alloc_bytes"), - "bytes allocated and still in use", - nil, nil, - ) - totalAllocDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "total_alloc_bytes"), - "bytes allocated (even if freed)", - nil, nil, - ) - numGCDesc = prometheus.NewDesc( - prometheus.BuildFQName("", "memstats", "num_gc_total"), - "number of GCs run", - nil, nil, - ) -) - -// MemStatsCollector is an example for a custom Collector that solves the -// problem of feeding into multiple metrics at the same time. The -// runtime.ReadMemStats should happen only once, and then the results need to be -// fed into a number of separate Metrics. In this example, only a few of the -// values reported by ReadMemStats are used. For each, there is a Desc provided -// as a var, so the MemStatsCollector itself needs nothing else in the -// struct. Only the methods need to be implemented. -type MemStatsCollector struct{} - -// Describe just sends the three Desc objects for the Metrics we intend to -// collect. -func (_ MemStatsCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- allocDesc - ch <- totalAllocDesc - ch <- numGCDesc -} - -// Collect does the trick by calling ReadMemStats once and then constructing -// three different Metrics on the fly. -func (_ MemStatsCollector) Collect(ch chan<- prometheus.Metric) { - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - ch <- prometheus.MustNewConstMetric( - allocDesc, - prometheus.GaugeValue, - float64(ms.Alloc), - ) - ch <- prometheus.MustNewConstMetric( - totalAllocDesc, - prometheus.GaugeValue, - float64(ms.TotalAlloc), - ) - ch <- prometheus.MustNewConstMetric( - numGCDesc, - prometheus.CounterValue, - float64(ms.NumGC), - ) - // To avoid new allocations on each collection, you could also keep - // metric objects around and return the same objects each time, just - // with new values set. -} - -func ExampleCollector_memstats() { - prometheus.MustRegister(&MemStatsCollector{}) - // Since we are dealing with custom Collector implementations, it might - // be a good idea to enable the collect checks in the registry. - prometheus.EnableCollectChecks(true) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go deleted file mode 100644 index 608deeb0279..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "runtime" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric { - result := &CallbackMetric{desc: desc, callback: callback} - result.Init(result) // Initialize the SelfCollector. - return result -} - -// TODO: Come up with a better example. - -// CallbackMetric is an example for a user-defined Metric that exports the -// result of a function call as a metric of type "untyped" without any -// labels. It uses SelfCollector to turn the Metric into a Collector so that it -// can be registered with Prometheus. -// -// Note that this example is pretty much academic as the prometheus package -// already provides an UntypedFunc type. -type CallbackMetric struct { - prometheus.SelfCollector - - desc *prometheus.Desc - callback func() float64 -} - -func (cm *CallbackMetric) Desc() *prometheus.Desc { - return cm.desc -} - -func (cm *CallbackMetric) Write(m *dto.Metric) error { - m.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())} - return nil -} - -func ExampleSelfCollector() { - m := NewCallbackMetric( - prometheus.NewDesc( - "runtime_goroutines_count", - "Total number of goroutines that currently exist.", - nil, nil, // No labels, these must be nil. - ), - func() float64 { - return float64(runtime.NumGoroutine()) - }, - ) - prometheus.MustRegister(m) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go deleted file mode 100644 index 0344e465b0c..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/examples_test.go +++ /dev/null @@ -1,649 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "flag" - "fmt" - "math" - "net/http" - "os" - "runtime" - "sort" - "time" - - dto "github.com/prometheus/client_model/go" - - "github.com/golang/protobuf/proto" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleGauge() { - opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed.", - }) - prometheus.MustRegister(opsQueued) - - // 10 operations queued by the goroutine managing incoming requests. - opsQueued.Add(10) - // A worker goroutine has picked up a waiting operation. - opsQueued.Dec() - // And once more... - opsQueued.Dec() -} - -func ExampleGaugeVec() { - binaryVersion := flag.String("binary_version", "debug", "Version of the binary: debug, canary, production.") - flag.Parse() - - opsQueued := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", - ConstLabels: prometheus.Labels{"binary_version": *binaryVersion}, - }, - []string{ - // Which user has requested the operation? - "user", - // Of what type is the operation? - "type", - }, - ) - prometheus.MustRegister(opsQueued) - - // Increase a value using compact (but order-sensitive!) WithLabelValues(). - opsQueued.WithLabelValues("bob", "put").Add(4) - // Increase a value with a map using WithLabels. More verbose, but order - // doesn't matter anymore. - opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() -} - -func ExampleGaugeFunc() { - if err := prometheus.Register(prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Subsystem: "runtime", - Name: "goroutines_count", - Help: "Number of goroutines that currently exist.", - }, - func() float64 { return float64(runtime.NumGoroutine()) }, - )); err == nil { - fmt.Println("GaugeFunc 'goroutines_count' registered.") - } - // Note that the count of goroutines is a gauge (and not a counter) as - // it can go up and down. - - // Output: - // GaugeFunc 'goroutines_count' registered. -} - -func ExampleCounter() { - pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", // Note: No help string... - }) - err := prometheus.Register(pushCounter) // ... so this will return an error. - if err != nil { - fmt.Println("Push counter couldn't be registered, no counting will happen:", err) - return - } - - // Try it once more, this time with a help string. - pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", - Help: "Number of pushes to external repository.", - }) - err = prometheus.Register(pushCounter) - if err != nil { - fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) - return - } - - pushComplete := make(chan struct{}) - // TODO: Start a goroutine that performs repository pushes and reports - // each completion via the channel. - for _ = range pushComplete { - pushCounter.Inc() - } - // Output: - // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string -} - -func ExampleCounterVec() { - binaryVersion := flag.String("environment", "test", "Execution environment: test, staging, production.") - flag.Parse() - - httpReqs := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", - ConstLabels: prometheus.Labels{"env": *binaryVersion}, - }, - []string{"code", "method"}, - ) - prometheus.MustRegister(httpReqs) - - httpReqs.WithLabelValues("404", "POST").Add(42) - - // If you have to access the same set of labels very frequently, it - // might be good to retrieve the metric only once and keep a handle to - // it. But beware of deletion of that metric, see below! - m := httpReqs.WithLabelValues("200", "GET") - for i := 0; i < 1000000; i++ { - m.Inc() - } - // Delete a metric from the vector. If you have previously kept a handle - // to that metric (as above), future updates via that handle will go - // unseen (even if you re-create a metric with the same label set - // later). - httpReqs.DeleteLabelValues("200", "GET") - // Same thing with the more verbose Labels syntax. - httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) -} - -func ExampleInstrumentHandler() { - // Handle the "/doc" endpoint with the standard http.FileServer handler. - // By wrapping the handler with InstrumentHandler, request count, - // request and response sizes, and request latency are automatically - // exported to Prometheus, partitioned by HTTP status code and method - // and by the handler name (here "fileserver"). - http.Handle("/doc", prometheus.InstrumentHandler( - "fileserver", http.FileServer(http.Dir("/usr/share/doc")), - )) - // The Prometheus handler still has to be registered to handle the - // "/metrics" endpoint. The handler returned by prometheus.Handler() is - // already instrumented - with "prometheus" as the handler name. In this - // example, we want the handler name to be "metrics", so we instrument - // the uninstrumented Prometheus handler ourselves. - http.Handle("/metrics", prometheus.InstrumentHandler( - "metrics", prometheus.UninstrumentedHandler(), - )) -} - -func ExampleLabelPairSorter() { - labelPairs := []*dto.LabelPair{ - &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")}, - &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")}, - } - - sort.Sort(prometheus.LabelPairSorter(labelPairs)) - - fmt.Println(labelPairs) - // Output: - // [name:"method" value:"get" name:"status" value:"404" ] -} - -func ExampleRegister() { - // Imagine you have a worker pool and want to count the tasks completed. - taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }) - // This will register fine. - if err := prometheus.Register(taskCounter); err != nil { - fmt.Println(err) - } else { - fmt.Println("taskCounter registered.") - } - // Don't forget to tell the HTTP server about the Prometheus handler. - // (In a real program, you still need to start the HTTP server...) - http.Handle("/metrics", prometheus.Handler()) - - // Now you can start workers and give every one of them a pointer to - // taskCounter and let it increment it whenever it completes a task. - taskCounter.Inc() // This has to happen somewhere in the worker code. - - // But wait, you want to see how individual workers perform. So you need - // a vector of counters, with one element for each worker. - taskCounterVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - - // Registering will fail because we already have a metric of that name. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - - // To fix, first unregister the old taskCounter. - if prometheus.Unregister(taskCounter) { - fmt.Println("taskCounter unregistered.") - } - - // Try registering taskCounterVec again. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Bummer! Still doesn't work. - - // Prometheus will not allow you to ever export metrics with - // inconsistent help strings or label names. After unregistering, the - // unregistered metrics will cease to show up in the /metrics HTTP - // response, but the registry still remembers that those metrics had - // been exported before. For this example, we will now choose a - // different name. (In a real program, you would obviously not export - // the obsolete metric in the first place.) - taskCounterVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_by_id", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Finally it worked! - - // The workers have to tell taskCounterVec their id to increment the - // right element in the metric vector. - taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. - - // Each worker could also keep a reference to their own counter element - // around. Pick the counter at initialization time of the worker. - myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. - myCounter.Inc() // Somewhere in the code of that worker. - - // Note that something like WithLabelValues("42", "spurious arg") would - // panic (because you have provided too many label values). If you want - // to get an error instead, use GetMetricWithLabelValues(...) instead. - notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") - if err != nil { - fmt.Println("Worker initialization failed:", err) - } - if notMyCounter == nil { - fmt.Println("notMyCounter is nil.") - } - - // A different (and somewhat tricky) approach is to use - // ConstLabels. ConstLabels are pairs of label names and label values - // that never change. You might ask what those labels are good for (and - // rightfully so - if they never change, they could as well be part of - // the metric name). There are essentially two use-cases: The first is - // if labels are constant throughout the lifetime of a binary execution, - // but they vary over time or between different instances of a running - // binary. The second is what we have here: Each worker creates and - // registers an own Counter instance where the only difference is in the - // value of the ConstLabels. Those Counters can all be registered - // because the different ConstLabel values guarantee that each worker - // will increment a different Counter metric. - counterOpts := prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks", - Help: "Total number of tasks completed.", - ConstLabels: prometheus.Labels{"worker_id": "42"}, - } - taskCounterForWorker42 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker42); err != nil { - fmt.Println("taskCounterVForWorker42 not registered:", err) - } else { - fmt.Println("taskCounterForWorker42 registered.") - } - // Obviously, in real code, taskCounterForWorker42 would be a member - // variable of a worker struct, and the "42" would be retrieved with a - // GetId() method or something. The Counter would be created and - // registered in the initialization code of the worker. - - // For the creation of the next Counter, we can recycle - // counterOpts. Just change the ConstLabels. - counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} - taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker2001); err != nil { - fmt.Println("taskCounterVForWorker2001 not registered:", err) - } else { - fmt.Println("taskCounterForWorker2001 registered.") - } - - taskCounterForWorker2001.Inc() - taskCounterForWorker42.Inc() - taskCounterForWorker2001.Inc() - - // Yet another approach would be to turn the workers themselves into - // Collectors and register them. See the Collector example for details. - - // Output: - // taskCounter registered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounter unregistered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounterVec registered. - // Worker initialization failed: inconsistent label cardinality - // notMyCounter is nil. - // taskCounterForWorker42 registered. - // taskCounterForWorker2001 registered. -} - -func ExampleSummary() { - temps := prometheus.NewSummary(prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > -} - -func ExampleSummaryVec() { - temps := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }, - []string{"species"}, - ) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) - } - - // Create a Summary without any observations. - temps.WithLabelValues("leiopelma-hochstetteri") - - // Just for demonstration, let's check the state of the summary vector - // by (ab)using its Collect method and the Write method of its elements - // (which is usually only used by Prometheus internally - code like the - // following will never appear in your own code). - metricChan := make(chan prometheus.Metric) - go func() { - defer close(metricChan) - temps.Collect(metricChan) - }() - - metricStrings := []string{} - for metric := range metricChan { - dtoMetric := &dto.Metric{} - metric.Write(dtoMetric) - metricStrings = append(metricStrings, proto.MarshalTextString(dtoMetric)) - } - sort.Strings(metricStrings) // For reproducible print order. - fmt.Println(metricStrings) - - // Output: - // [label: < - // name: "species" - // value: "leiopelma-hochstetteri" - // > - // summary: < - // sample_count: 0 - // sample_sum: 0 - // quantile: < - // quantile: 0.5 - // value: nan - // > - // quantile: < - // quantile: 0.9 - // value: nan - // > - // quantile: < - // quantile: 0.99 - // value: nan - // > - // > - // label: < - // name: "species" - // value: "lithobates-catesbeianus" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 31956.100000000017 - // quantile: < - // quantile: 0.5 - // value: 32.4 - // > - // quantile: < - // quantile: 0.9 - // value: 41.4 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // label: < - // name: "species" - // value: "litoria-caerulea" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // ] -} - -func ExampleConstSummary() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A summary of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant summary from values we got from a 3rd party telemetry system. - s := prometheus.MustNewConstSummary( - desc, - 4711, 403.34, - map[float64]float64{0.5: 42.3, 0.9: 323.3}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - s.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // summary: < - // sample_count: 4711 - // sample_sum: 403.34 - // quantile: < - // quantile: 0.5 - // value: 42.3 - // > - // quantile: < - // quantile: 0.9 - // value: 323.3 - // > - // > -} - -func ExampleHistogram() { - temps := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // histogram: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // bucket: < - // cumulative_count: 192 - // upper_bound: 20 - // > - // bucket: < - // cumulative_count: 366 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 501 - // upper_bound: 30 - // > - // bucket: < - // cumulative_count: 638 - // upper_bound: 35 - // > - // bucket: < - // cumulative_count: 816 - // upper_bound: 40 - // > - // > -} - -func ExampleConstHistogram() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A histogram of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant histogram from values we got from a 3rd party telemetry system. - h := prometheus.MustNewConstHistogram( - desc, - 4711, 403.34, - map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - h.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // histogram: < - // sample_count: 4711 - // sample_sum: 403.34 - // bucket: < - // cumulative_count: 121 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 2403 - // upper_bound: 50 - // > - // bucket: < - // cumulative_count: 3221 - // upper_bound: 100 - // > - // bucket: < - // cumulative_count: 4233 - // upper_bound: 200 - // > - // > -} - -func ExamplePushCollectors() { - hostname, _ := os.Hostname() - completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "db_backup_last_completion_time", - Help: "The timestamp of the last succesful completion of a DB backup.", - }) - completionTime.Set(float64(time.Now().Unix())) - if err := prometheus.PushCollectors( - "db_backup", hostname, - "http://pushgateway:9091", - completionTime, - ); err != nil { - fmt.Println("Could not push completion time to Pushgateway:", err) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go deleted file mode 100644 index 5d3128faed6..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/expvar_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus_test - -import ( - "expvar" - "fmt" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleExpvarCollector() { - expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ - "memstats": prometheus.NewDesc( - "expvar_memstats", - "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", - []string{"type"}, nil, - ), - "lone-int": prometheus.NewDesc( - "expvar_lone_int", - "Just an expvar int as an example.", - nil, nil, - ), - "http-request-map": prometheus.NewDesc( - "expvar_http_request_total", - "How many http requests processed, partitioned by status code and http method.", - []string{"code", "method"}, nil, - ), - }) - prometheus.MustRegister(expvarCollector) - - // The Prometheus part is done here. But to show that this example is - // doing anything, we have to manually export something via expvar. In - // real-life use-cases, some library would already have exported via - // expvar what we want to re-export as Prometheus metrics. - expvar.NewInt("lone-int").Set(42) - expvarMap := expvar.NewMap("http-request-map") - var ( - expvarMap1, expvarMap2 expvar.Map - expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int - ) - expvarMap1.Init() - expvarMap2.Init() - expvarInt11.Set(3) - expvarInt12.Set(13) - expvarInt21.Set(11) - expvarInt22.Set(212) - expvarMap1.Set("POST", &expvarInt11) - expvarMap1.Set("GET", &expvarInt12) - expvarMap2.Set("POST", &expvarInt21) - expvarMap2.Set("GET", &expvarInt22) - expvarMap.Set("404", &expvarMap1) - expvarMap.Set("200", &expvarMap2) - // Results in the following expvar map: - // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} - - // Let's see what the scrape would yield, but exclude the memstats metrics. - metricStrings := []string{} - metric := dto.Metric{} - metricChan := make(chan prometheus.Metric) - go func() { - expvarCollector.Collect(metricChan) - close(metricChan) - }() - for m := range metricChan { - if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { - metric.Reset() - m.Write(&metric) - metricStrings = append(metricStrings, metric.String()) - } - } - sort.Strings(metricStrings) - for _, s := range metricStrings { - fmt.Println(strings.TrimRight(s, " ")) - } - // Output: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // untyped: -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go deleted file mode 100644 index 48cab463671..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/gauge_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func listenGaugeStream(vals, result chan float64, done chan struct{}) { - var sum float64 -outer: - for { - select { - case <-done: - close(vals) - for v := range vals { - sum += v - } - break outer - case v := <-vals: - sum += v - } - } - result <- sum - close(result) -} - -func TestGaugeConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStream := make(chan float64, mutations*concLevel) - result := make(chan float64) - done := make(chan struct{}) - - go listenGaugeStream(sStream, result, done) - go func() { - end.Wait() - close(done) - }() - - gge := NewGauge(GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sStream <- v - gge.Add(v) - } - end.Done() - }(vals) - } - start.Done() - - if expected, got := <-result, math.Float64frombits(gge.(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeVecConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - vecLength := int(n%5 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStreams := make([]chan float64, vecLength) - results := make([]chan float64, vecLength) - done := make(chan struct{}) - - for i := 0; i < vecLength; i++ { - sStreams[i] = make(chan float64, mutations*concLevel) - results[i] = make(chan float64) - go listenGaugeStream(sStreams[i], results[i], done) - } - - go func() { - end.Wait() - close(done) - }() - - gge := NewGaugeVec( - GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }, - []string{"label"}, - ) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - pick := make([]int, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - pick[j] = rand.Intn(vecLength) - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sStreams[pick[i]] <- v - gge.WithLabelValues(string('A' + pick[i])).Add(v) - } - end.Done() - }(vals) - } - start.Done() - - for i := range sStreams { - if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeFunc(t *testing.T) { - gf := NewGaugeFunc( - GaugeOpts{ - Name: "test_name", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }, - func() float64 { return 3.1415 }, - ) - - if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } - - m := &dto.Metric{} - gf.Write(m) - - if expected, got := `label: label: gauge: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go deleted file mode 100644 index 9a8858cbd2b..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/go_collector_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package prometheus - -import ( - "runtime" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestGoCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - old = -1 - ) - defer close(closec) - - go func() { - c.Collect(ch) - go func(c <-chan struct{}) { - <-c - }(closec) - <-waitc - c.Collect(ch) - }() - - for { - select { - case metric := <-ch: - switch m := metric.(type) { - // Attention, this also catches Counter... - case Gauge: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetGauge() == nil { - continue - } - - if old == -1 { - old = int(pb.GetGauge().GetValue()) - close(waitc) - continue - } - - if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { - // TODO: This is flaky in highly concurrent situations. - t.Errorf("want 1 new goroutine, got %d", diff) - } - - // GoCollector performs two sends per call. - // On line 27 we need to receive the second send - // to shut down cleanly. - <-ch - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} - -func TestGCCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - oldGC uint64 - oldPause float64 - ) - defer close(closec) - - go func() { - c.Collect(ch) - // force GC - runtime.GC() - <-waitc - c.Collect(ch) - }() - - first := true - for { - select { - case metric := <-ch: - switch m := metric.(type) { - case *constSummary, *value: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetSummary() == nil { - continue - } - - if len(pb.GetSummary().Quantile) != 5 { - t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) - } - for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { - if *pb.GetSummary().Quantile[idx].Quantile != want { - t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) - } - } - if first { - first = false - oldGC = *pb.GetSummary().SampleCount - oldPause = *pb.GetSummary().SampleSum - close(waitc) - continue - } - if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { - t.Errorf("want 1 new garbage collection run, got %d", diff) - } - if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { - t.Errorf("want moar pause, got %f", diff) - } - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go deleted file mode 100644 index 11cf66b4fe2..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/histogram_test.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "reflect" - "sort" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkHistogramObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramObserve1(b *testing.B) { - benchmarkHistogramObserve(1, b) -} - -func BenchmarkHistogramObserve2(b *testing.B) { - benchmarkHistogramObserve(2, b) -} - -func BenchmarkHistogramObserve4(b *testing.B) { - benchmarkHistogramObserve(4, b) -} - -func BenchmarkHistogramObserve8(b *testing.B) { - benchmarkHistogramObserve(8, b) -} - -func benchmarkHistogramWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramWrite1(b *testing.B) { - benchmarkHistogramWrite(1, b) -} - -func BenchmarkHistogramWrite2(b *testing.B) { - benchmarkHistogramWrite(2, b) -} - -func BenchmarkHistogramWrite4(b *testing.B) { - benchmarkHistogramWrite(4, b) -} - -func BenchmarkHistogramWrite8(b *testing.B) { - benchmarkHistogramWrite(8, b) -} - -// Intentionally adding +Inf here to test if that case is handled correctly. -// Also, getCumulativeCounts depends on it. -var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} - -func TestHistogramConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: testBuckets, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Histogram.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - for i, wantBound := range testBuckets { - if i == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestHistogramVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - his := NewHistogramVec( - HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - his.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := his.WithLabelValues(string('A' + i)) - s.Write(m) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars[i]) - - for j, wantBound := range testBuckets { - if j == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func getCumulativeCounts(vars []float64) []uint64 { - counts := make([]uint64, len(testBuckets)) - for _, v := range vars { - for i := len(testBuckets) - 1; i >= 0; i-- { - if v > testBuckets[i] { - break - } - counts[i]++ - } - } - return counts -} - -func TestBuckets(t *testing.T) { - got := LinearBuckets(-15, 5, 6) - want := []float64{-15, -10, -5, 0, 5, 10} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } - - got = ExponentialBuckets(100, 1.2, 3) - want = []float64{100, 120, 144} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go deleted file mode 100644 index ffe0418cf87..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/http_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -type respBody string - -func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - w.Write([]byte(b)) -} - -func TestInstrumentHandler(t *testing.T) { - defer func(n nower) { - now = n.(nower) - }(now) - - instant := time.Now() - end := instant.Add(30 * time.Second) - now = nowSeries(instant, end) - respBody := respBody("Howdy there!") - - hndlr := InstrumentHandler("test-handler", respBody) - - opts := SummaryOpts{ - Subsystem: "http", - ConstLabels: Labels{"handler": "test-handler"}, - } - - reqCnt := MustRegisterOrGet(NewCounterVec( - CounterOpts{ - Namespace: opts.Namespace, - Subsystem: opts.Subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: opts.ConstLabels, - }, - instLabels, - )).(*CounterVec) - - opts.Name = "request_duration_microseconds" - opts.Help = "The HTTP request latencies in microseconds." - reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary) - - opts.Name = "request_size_bytes" - opts.Help = "The HTTP request sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - opts.Name = "response_size_bytes" - opts.Help = "The HTTP response sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - reqCnt.Reset() - - resp := httptest.NewRecorder() - req := &http.Request{ - Method: "GET", - } - - hndlr.ServeHTTP(resp, req) - - if resp.Code != http.StatusTeapot { - t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) - } - if string(resp.Body.Bytes()) != "Howdy there!" { - t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) - } - - out := &dto.Metric{} - reqDur.Write(out) - if want, got := "test-handler", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqDur, got %q", want, got) - } - if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { - t.Errorf("want sample count %d in reqDur, got %d", want, got) - } - - out.Reset() - if want, got := 1, len(reqCnt.children); want != got { - t.Errorf("want %d children in reqCnt, got %d", want, got) - } - cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") - if err != nil { - t.Fatal(err) - } - cnt.Write(out) - if want, got := "418", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "test-handler", out.Label[1].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "get", out.Label[2].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if out.Counter == nil { - t.Fatal("expected non-nil counter in reqCnt") - } - if want, got := 1., out.Counter.GetValue(); want != got { - t.Errorf("want reqCnt of %f, got %f", want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go deleted file mode 100644 index 7145f5e53c3..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/metric_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import "testing" - -func TestBuildFQName(t *testing.T) { - scenarios := []struct{ namespace, subsystem, name, result string }{ - {"a", "b", "c", "a_b_c"}, - {"", "b", "c", "b_c"}, - {"a", "", "c", "a_c"}, - {"", "", "c", "c"}, - {"a", "b", "", ""}, - {"a", "", "", ""}, - {"", "b", "", ""}, - {" ", "", "", ""}, - } - - for i, s := range scenarios { - if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { - t.Errorf("%d. want %s, got %s", i, want, got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go deleted file mode 100644 index 829715acd8f..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/process_collector_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package prometheus - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - "regexp" - "testing" - - "github.com/prometheus/procfs" -) - -func TestProcessCollector(t *testing.T) { - if _, err := procfs.Self(); err != nil { - t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) - } - - registry := newRegistry() - registry.Register(NewProcessCollector(os.Getpid(), "")) - registry.Register(NewProcessCollectorPIDFn( - func() (int, error) { return os.Getpid(), nil }, "foobar")) - - s := httptest.NewServer(InstrumentHandler("prometheus", registry)) - defer s.Close() - r, err := http.Get(s.URL) - if err != nil { - t.Fatal(err) - } - defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - - for _, re := range []*regexp.Regexp{ - regexp.MustCompile("process_cpu_seconds_total [0-9]"), - regexp.MustCompile("process_max_fds [0-9]{2,}"), - regexp.MustCompile("process_open_fds [1-9]"), - regexp.MustCompile("process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("process_resident_memory_bytes [1-9]"), - regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"), - regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"), - regexp.MustCompile("foobar_process_max_fds [0-9]{2,}"), - regexp.MustCompile("foobar_process_open_fds [1-9]"), - regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"), - } { - if !re.Match(body) { - t.Errorf("want body to match %s\n%s", re, body) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go deleted file mode 100644 index f30c90c06be..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/registry_test.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Copyright (c) 2013, The Prometheus 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 prometheus - -import ( - "bytes" - "encoding/binary" - "net/http" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -type fakeResponseWriter struct { - header http.Header - body bytes.Buffer -} - -func (r *fakeResponseWriter) Header() http.Header { - return r.header -} - -func (r *fakeResponseWriter) Write(d []byte) (l int, err error) { - return r.body.Write(d) -} - -func (r *fakeResponseWriter) WriteHeader(c int) { -} - -func testHandler(t testing.TB) { - - metricVec := NewCounterVec( - CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - - metricVec.WithLabelValues("val1").Inc() - metricVec.WithLabelValues("val2").Inc() - - varintBuf := make([]byte, binary.MaxVarintLen32) - - externalMetricFamily := &dto.MetricFamily{ - Name: proto.String("externalname"), - Help: proto.String("externaldocstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("externalconstname"), - Value: proto.String("externalconstvalue"), - }, - { - Name: proto.String("externallabelname"), - Value: proto.String("externalval1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - marshaledExternalMetricFamily, err := proto.Marshal(externalMetricFamily) - if err != nil { - t.Fatal(err) - } - var externalBuf bytes.Buffer - l := binary.PutUvarint(varintBuf, uint64(len(marshaledExternalMetricFamily))) - _, err = externalBuf.Write(varintBuf[:l]) - if err != nil { - t.Fatal(err) - } - _, err = externalBuf.Write(marshaledExternalMetricFamily) - if err != nil { - t.Fatal(err) - } - externalMetricFamilyAsBytes := externalBuf.Bytes() - externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring -# TYPE externalname counter -externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 -`) - externalMetricFamilyAsProtoText := []byte(`name: "externalname" -help: "externaldocstring" -type: COUNTER -metric: < - label: < - name: "externalconstname" - value: "externalconstvalue" - > - label: < - name: "externallabelname" - value: "externalval1" - > - counter: < - value: 1 - > -> - -`) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) - - expectedMetricFamily := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - marshaledExpectedMetricFamily, err := proto.Marshal(expectedMetricFamily) - if err != nil { - t.Fatal(err) - } - var buf bytes.Buffer - l = binary.PutUvarint(varintBuf, uint64(len(marshaledExpectedMetricFamily))) - _, err = buf.Write(varintBuf[:l]) - if err != nil { - t.Fatal(err) - } - _, err = buf.Write(marshaledExpectedMetricFamily) - if err != nil { - t.Fatal(err) - } - expectedMetricFamilyAsBytes := buf.Bytes() - expectedMetricFamilyAsText := []byte(`# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -`) - expectedMetricFamilyAsProtoText := []byte(`name: "name" -help: "docstring" -type: COUNTER -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val1" - > - counter: < - value: 1 - > -> -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val2" - > - counter: < - value: 1 - > -> - -`) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithSameName := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("inconsistent help string does not matter here"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) - - type output struct { - headers map[string]string - body []byte - } - - var scenarios = []struct { - headers map[string]string - out output - collector Collector - externalMF []*dto.MetricFamily - }{ - { // 0 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 1 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/quark;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 2 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 3 - headers: map[string]string{ - "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: []byte{}, - }, - }, - { // 4 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 5 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: expectedMetricFamilyAsBytes, - }, - collector: metricVec, - }, - { // 6 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: externalMetricFamilyAsText, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 7 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: externalMetricFamilyAsBytes, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 8 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 9 - headers: map[string]string{ - "Accept": "text/plain", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 10 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 11 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsText, - expectedMetricFamilyAsText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 12 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 13 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoText, - expectedMetricFamilyAsProtoText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 14 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 15 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyMergedWithExternalAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithSameName, - }, - }, - } - for i, scenario := range scenarios { - registry := newRegistry() - registry.collectChecksEnabled = true - - if scenario.collector != nil { - registry.Register(scenario.collector) - } - if scenario.externalMF != nil { - registry.metricFamilyInjectionHook = func() []*dto.MetricFamily { - return scenario.externalMF - } - } - writer := &fakeResponseWriter{ - header: http.Header{}, - } - handler := InstrumentHandler("prometheus", registry) - request, _ := http.NewRequest("GET", "/", nil) - for key, value := range scenario.headers { - request.Header.Add(key, value) - } - handler(writer, request) - - for key, value := range scenario.out.headers { - if writer.Header().Get(key) != value { - t.Errorf( - "%d. expected %q for header %q, got %q", - i, value, key, writer.Header().Get(key), - ) - } - } - - if !bytes.Equal(scenario.out.body, writer.body.Bytes()) { - t.Errorf( - "%d. expected %q for body, got %q", - i, scenario.out.body, writer.body.Bytes(), - ) - } - } -} - -func TestHandler(t *testing.T) { - testHandler(t) -} - -func BenchmarkHandler(b *testing.B) { - for i := 0; i < b.N; i++ { - testHandler(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go deleted file mode 100644 index 0790cdfe727..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/summary_test.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "math/rand" - "sort" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkSummaryObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryObserve1(b *testing.B) { - benchmarkSummaryObserve(1, b) -} - -func BenchmarkSummaryObserve2(b *testing.B) { - benchmarkSummaryObserve(2, b) -} - -func BenchmarkSummaryObserve4(b *testing.B) { - benchmarkSummaryObserve(4, b) -} - -func BenchmarkSummaryObserve8(b *testing.B) { - benchmarkSummaryObserve(8, b) -} - -func benchmarkSummaryWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryWrite1(b *testing.B) { - benchmarkSummaryWrite(1, b) -} - -func BenchmarkSummaryWrite2(b *testing.B) { - benchmarkSummaryWrite(2, b) -} - -func BenchmarkSummaryWrite4(b *testing.B) { - benchmarkSummaryWrite(4, b) -} - -func BenchmarkSummaryWrite8(b *testing.B) { - benchmarkSummaryWrite(8, b) -} - -func TestSummaryConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Summary.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - for i, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[i].Quantile - gotV := *m.Summary.Quantile[i].Value - min, max := getBounds(allVars, wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f, want %f", gotQ, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummaryVec( - SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sum.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := sum.WithLabelValues(string('A' + i)) - s.Write(m) - if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) - } - if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) - } - for j, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[j].Quantile - gotV := *m.Summary.Quantile[j].Value - min, max := getBounds(allVars[i], wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryDecay(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - // More because it depends on timing than because it is particularly long... - } - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - MaxAge: 100 * time.Millisecond, - Objectives: map[float64]float64{0.1: 0.001}, - AgeBuckets: 10, - }) - - m := &dto.Metric{} - i := 0 - tick := time.NewTicker(time.Millisecond) - for _ = range tick.C { - i++ - sum.Observe(float64(i)) - if i%10 == 0 { - sum.Write(m) - if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { - t.Errorf("%d. got %f, want %f", i, got, want) - } - m.Reset() - } - if i >= 1000 { - break - } - } - tick.Stop() - // Wait for MaxAge without observations and make sure quantiles are NaN. - time.Sleep(100 * time.Millisecond) - sum.Write(m) - if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { - t.Errorf("got %f, want NaN after expiration", got) - } -} - -func getBounds(vars []float64, q, ε float64) (min, max float64) { - // TODO: This currently tolerates an error of up to 2*ε. The error must - // be at most ε, but for some reason, it's sometimes slightly - // higher. That's a bug. - n := float64(len(vars)) - lower := int((q - 2*ε) * n) - upper := int(math.Ceil((q + 2*ε) * n)) - min = vars[0] - if lower > 1 { - min = vars[lower-1] - } - max = vars[len(vars)-1] - if upper < len(vars) { - max = vars[upper-1] - } - return -} diff --git a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go b/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go deleted file mode 100644 index 0e9431e656f..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus/vec_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "hash/fnv" - "testing" -) - -func TestDelete(t *testing.T) { - desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) - vec := MetricVec{ - children: map[uint64]Metric{}, - desc: desc, - hash: fnv.New64a(), - newMetric: func(lvs ...string) Metric { - return newValue(desc, UntypedValue, 0, lvs...) - }, - } - - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestDeleteLabelValues(t *testing.T) { - desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) - vec := MetricVec{ - children: map[uint64]Metric{}, - desc: desc, - hash: fnv.New64a(), - newMetric: func(lvs ...string) Metric { - return newValue(desc, UntypedValue, 0, lvs...) - }, - } - - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go deleted file mode 100644 index 92b16a028aa..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/bench_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "testing" - - "github.com/matttproud/golang_protobuf_extensions/pbutil" - - dto "github.com/prometheus/client_model/go" -) - -var parser TextParser - -// Benchmarks to show how much penalty text format parsing actually inflicts. -// -// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. -// -// BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op -// BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op -// BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op -// BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op -// BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op -// -// CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. -// Without compression, it needs ~7x longer, but with compression (the more relevant scenario), -// the difference becomes less relevant, only ~4x. -// -// The test data contains 248 samples. -// -// BenchmarkProcessor002ParseOnly in the extraction package is not quite -// comparable to the benchmarks here, but it gives an idea: JSON parsing is even -// slower than text parsing and needs a comparable amount of allocs. - -// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric -// family DTOs. -func BenchmarkParseText(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape -// into metric family DTOs. -func BenchmarkParseTextGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - if _, err := parser.TextToMetricFamilies(in); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into -// metric family DTOs. Note that this does not build a map of metric families -// (as the text version does), because it is not required for Prometheus -// ingestion either. (However, it is required for the text-format parsing, as -// the metric family might be sprinkled all over the text, while the -// protobuf-format guarantees bundling at one place.) -func BenchmarkParseProto(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped -// protobuf format. -func BenchmarkParseProtoGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed -// metric family DTOs into a map. This is not happening during Prometheus -// ingestion. It is just here to measure the overhead of that map creation and -// separate it from the overhead of the text format parsing. -func BenchmarkParseProtoMap(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - families := map[string]*dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family := &dto.MetricFamily{} - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - families[family.GetName()] = family - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go deleted file mode 100644 index 307fcd21fed..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/decode_test.go +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "errors" - "io" - "net/http" - "reflect" - "sort" - "strings" - "testing" - - "github.com/prometheus/common/model" -) - -func TestTextDecoder(t *testing.T) { - var ( - ts = model.Now() - in = ` -# Only a quite simple scenario with two metric families. -# More complicated tests of the parser itself can be found in the text package. -# TYPE mf2 counter -mf2 3 -mf1{label="value1"} -3.14 123456 -mf1{label="value2"} 42 -mf2 4 -` - out = model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value1", - }, - Value: -3.14, - Timestamp: 123456, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value2", - }, - Value: 42, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 3, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 4, - Timestamp: ts, - }, - } - ) - - dec := &SampleDecoder{ - Dec: &textDecoder{r: strings.NewReader(in)}, - Opts: &DecodeOptions{ - Timestamp: ts, - }, - } - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(out) - if !reflect.DeepEqual(all, out) { - t.Fatalf("output does not match") - } -} - -func TestProtoDecoder(t *testing.T) { - - var testTime = model.Now() - - scenarios := []struct { - in string - expected model.Vector - }{ - { - in: "", - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - }, - Value: 84, - Timestamp: testTime, - }, - }, - }, - { - in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.99", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.999", - }, - Value: -84, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - "quantile": "0.5", - }, - Value: 10, - Timestamp: testTime, - }, - }, - }, - { - in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "100", - }, - Value: 123, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "120", - }, - Value: 412, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "144", - }, - Value: 592, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "172.8", - }, - Value: 1524, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "+Inf", - }, - Value: 2693, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_sum", - }, - Value: 1756047.3, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_count", - }, - Value: 2693, - Timestamp: testTime, - }, - }, - }, - { - // The metric type is unset in this protobuf, which needs to be handled - // correctly by the decoder. - in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - }, - Value: 1, - Timestamp: testTime, - }, - }, - }, - } - - for i, scenario := range scenarios { - dec := &SampleDecoder{ - Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, - Opts: &DecodeOptions{ - Timestamp: testTime, - }, - } - - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(scenario.expected) - if !reflect.DeepEqual(all, scenario.expected) { - t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) - } - } -} - -func testDiscriminatorHTTPHeader(t testing.TB) { - var scenarios = []struct { - input map[string]string - output Format - err error - }{ - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, - output: FmtProtoDelim, - err: nil, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, - output: "", - err: errors.New("unrecognized protocol message illegal"), - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, - output: "", - err: errors.New("unsupported encoding illegal"), - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, - output: FmtText, - err: nil, - }, - { - input: map[string]string{"Content-Type": `text/plain`}, - output: FmtText, - err: nil, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, - output: "", - err: errors.New("unrecognized protocol version 0.0.3"), - }, - } - - for i, scenario := range scenarios { - var header http.Header - - if len(scenario.input) > 0 { - header = http.Header{} - } - - for key, value := range scenario.input { - header.Add(key, value) - } - - actual, err := ResponseFormat(header) - - if scenario.err != err { - if scenario.err != nil && err != nil { - if scenario.err.Error() != err.Error() { - t.Errorf("%d. expected %s, got %s", i, scenario.err, err) - } - } else if scenario.err != nil || err != nil { - t.Errorf("%d. expected %s, got %s", i, scenario.err, err) - } - } - - if !reflect.DeepEqual(scenario.output, actual) { - t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) - } - } -} - -func TestDiscriminatorHTTPHeader(t *testing.T) { - testDiscriminatorHTTPHeader(t) -} - -func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - testDiscriminatorHTTPHeader(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go deleted file mode 100644 index c98ea29e176..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/json_decode_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2015 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "os" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func TestJSON2Decode(t *testing.T) { - f, err := os.Open("testdata/json2") - if err != nil { - t.Fatal(err) - } - defer f.Close() - - dec := newJSON2Decoder(f) - - var v1 dto.MetricFamily - if err := dec.Decode(&v1); err != nil { - t.Fatal(err) - } - - exp1 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC calls."), - Name: proto.String("rpc_calls_total"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("zed"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(25), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("job"), - Value: proto.String("batch_job"), - }, { - Name: proto.String("service"), - Value: proto.String("bar"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(24), - }, - }, - }, - } - - if !reflect.DeepEqual(v1, exp1) { - t.Fatalf("Expected %v, got %v", exp1, v1) - } - - var v2 dto.MetricFamily - if err := dec.Decode(&v2); err != nil { - t.Fatal(err) - } - - exp2 := dto.MetricFamily{ - Type: dto.MetricType_UNTYPED.Enum(), - Help: proto.String("RPC latency."), - Name: proto.String("rpc_latency_microseconds"), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.010000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(15), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("percentile"), - Value: proto.String("0.990000"), - }, { - Name: proto.String("service"), - Value: proto.String("foo"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(17), - }, - }, - }, - } - - if !reflect.DeepEqual(v2, exp2) { - t.Fatalf("Expected %v, got %v", exp2, v2) - } - -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 deleted file mode 100644 index b914c938659..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/json2 +++ /dev/null @@ -1,46 +0,0 @@ -[ - { - "baseLabels": { - "__name__": "rpc_calls_total", - "job": "batch_job" - }, - "docstring": "RPC calls.", - "metric": { - "type": "counter", - "value": [ - { - "labels": { - "service": "zed" - }, - "value": 25 - }, - { - "labels": { - "service": "bar" - }, - "value": 24 - } - ] - } - }, - { - "baseLabels": { - "__name__": "rpc_latency_microseconds" - }, - "docstring": "RPC latency.", - "metric": { - "type": "histogram", - "value": [ - { - "labels": { - "service": "foo" - }, - "value": { - "0.010000": 15, - "0.990000": 17 - } - } - ] - } - } -] diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf deleted file mode 100644 index d5aae509150..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf +++ /dev/null @@ -1,516 +0,0 @@ -fc08 0a22 6874 7470 5f72 6571 7565 7374 -5f64 7572 6174 696f 6e5f 6d69 6372 6f73 -6563 6f6e 6473 122b 5468 6520 4854 5450 -2072 6571 7565 7374 206c 6174 656e 6369 -6573 2069 6e20 6d69 6372 6f73 6563 6f6e -6473 2e18 0222 570a 0c0a 0768 616e 646c -6572 1201 2f22 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 225d -0a12 0a07 6861 6e64 6c65 7212 072f 616c -6572 7473 2247 0800 1100 0000 0000 0000 -001a 1209 0000 0000 0000 e03f 1100 0000 -0000 0000 001a 1209 cdcc cccc cccc ec3f -1100 0000 0000 0000 001a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0000 0022 620a -170a 0768 616e 646c 6572 120c 2f61 7069 -2f6d 6574 7269 6373 2247 0800 1100 0000 -0000 0000 001a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0000 -0022 600a 150a 0768 616e 646c 6572 120a -2f61 7069 2f71 7565 7279 2247 0800 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 0000 001a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -0000 0022 660a 1b0a 0768 616e 646c 6572 -1210 2f61 7069 2f71 7565 7279 5f72 616e -6765 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 620a 170a -0768 616e 646c 6572 120c 2f61 7069 2f74 -6172 6765 7473 2247 0800 1100 0000 0000 -0000 001a 1209 0000 0000 0000 e03f 1100 -0000 0000 0000 001a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 0000 001a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 0000 0022 -600a 150a 0768 616e 646c 6572 120a 2f63 -6f6e 736f 6c65 732f 2247 0800 1100 0000 -0000 0000 001a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0000 -0022 5c0a 110a 0768 616e 646c 6572 1206 -2f67 7261 7068 2247 0800 1100 0000 0000 -0000 001a 1209 0000 0000 0000 e03f 1100 -0000 0000 0000 001a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 0000 001a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 0000 0022 -5b0a 100a 0768 616e 646c 6572 1205 2f68 -6561 7022 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 225e 0a13 -0a07 6861 6e64 6c65 7212 082f 7374 6174 -6963 2f22 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 2260 0a15 -0a07 6861 6e64 6c65 7212 0a70 726f 6d65 -7468 6575 7322 4708 3b11 5b8f c2f5 083f -f440 1a12 0900 0000 0000 00e0 3f11 e17a -14ae c7af 9340 1a12 09cd cccc cccc ccec -3f11 2fdd 2406 81f0 9640 1a12 09ae 47e1 -7a14 aeef 3f11 3d0a d7a3 b095 a740 e608 -0a17 6874 7470 5f72 6571 7565 7374 5f73 -697a 655f 6279 7465 7312 2054 6865 2048 -5454 5020 7265 7175 6573 7420 7369 7a65 -7320 696e 2062 7974 6573 2e18 0222 570a -0c0a 0768 616e 646c 6572 1201 2f22 4708 -0011 0000 0000 0000 0000 1a12 0900 0000 -0000 00e0 3f11 0000 0000 0000 0000 1a12 -09cd cccc cccc ccec 3f11 0000 0000 0000 -0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 -0000 0000 0000 225d 0a12 0a07 6861 6e64 -6c65 7212 072f 616c 6572 7473 2247 0800 -1100 0000 0000 0000 001a 1209 0000 0000 -0000 e03f 1100 0000 0000 0000 001a 1209 -cdcc cccc cccc ec3f 1100 0000 0000 0000 -001a 1209 ae47 e17a 14ae ef3f 1100 0000 -0000 0000 0022 620a 170a 0768 616e 646c -6572 120c 2f61 7069 2f6d 6574 7269 6373 -2247 0800 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 0022 600a 150a 0768 -616e 646c 6572 120a 2f61 7069 2f71 7565 -7279 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 660a 1b0a -0768 616e 646c 6572 1210 2f61 7069 2f71 -7565 7279 5f72 616e 6765 2247 0800 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 0000 001a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -0000 0022 620a 170a 0768 616e 646c 6572 -120c 2f61 7069 2f74 6172 6765 7473 2247 -0800 1100 0000 0000 0000 001a 1209 0000 -0000 0000 e03f 1100 0000 0000 0000 001a -1209 cdcc cccc cccc ec3f 1100 0000 0000 -0000 001a 1209 ae47 e17a 14ae ef3f 1100 -0000 0000 0000 0022 600a 150a 0768 616e -646c 6572 120a 2f63 6f6e 736f 6c65 732f -2247 0800 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 0022 5c0a 110a 0768 -616e 646c 6572 1206 2f67 7261 7068 2247 -0800 1100 0000 0000 0000 001a 1209 0000 -0000 0000 e03f 1100 0000 0000 0000 001a -1209 cdcc cccc cccc ec3f 1100 0000 0000 -0000 001a 1209 ae47 e17a 14ae ef3f 1100 -0000 0000 0000 0022 5b0a 100a 0768 616e -646c 6572 1205 2f68 6561 7022 4708 0011 -0000 0000 0000 0000 1a12 0900 0000 0000 -00e0 3f11 0000 0000 0000 0000 1a12 09cd -cccc cccc ccec 3f11 0000 0000 0000 0000 -1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 -0000 0000 225e 0a13 0a07 6861 6e64 6c65 -7212 082f 7374 6174 6963 2f22 4708 0011 -0000 0000 0000 0000 1a12 0900 0000 0000 -00e0 3f11 0000 0000 0000 0000 1a12 09cd -cccc cccc ccec 3f11 0000 0000 0000 0000 -1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 -0000 0000 2260 0a15 0a07 6861 6e64 6c65 -7212 0a70 726f 6d65 7468 6575 7322 4708 -3b11 0000 0000 40c4 d040 1a12 0900 0000 -0000 00e0 3f11 0000 0000 0030 7240 1a12 -09cd cccc cccc ccec 3f11 0000 0000 0030 -7240 1a12 09ae 47e1 7a14 aeef 3f11 0000 -0000 0030 7240 7c0a 1368 7474 705f 7265 -7175 6573 7473 5f74 6f74 616c 1223 546f -7461 6c20 6e75 6d62 6572 206f 6620 4854 -5450 2072 6571 7565 7374 7320 6d61 6465 -2e18 0022 3e0a 0b0a 0463 6f64 6512 0332 -3030 0a15 0a07 6861 6e64 6c65 7212 0a70 -726f 6d65 7468 6575 730a 0d0a 066d 6574 -686f 6412 0367 6574 1a09 0900 0000 0000 -804d 40e8 080a 1868 7474 705f 7265 7370 -6f6e 7365 5f73 697a 655f 6279 7465 7312 -2154 6865 2048 5454 5020 7265 7370 6f6e -7365 2073 697a 6573 2069 6e20 6279 7465 -732e 1802 2257 0a0c 0a07 6861 6e64 6c65 -7212 012f 2247 0800 1100 0000 0000 0000 -001a 1209 0000 0000 0000 e03f 1100 0000 -0000 0000 001a 1209 cdcc cccc cccc ec3f -1100 0000 0000 0000 001a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0000 0022 5d0a -120a 0768 616e 646c 6572 1207 2f61 6c65 -7274 7322 4708 0011 0000 0000 0000 0000 -1a12 0900 0000 0000 00e0 3f11 0000 0000 -0000 0000 1a12 09cd cccc cccc ccec 3f11 -0000 0000 0000 0000 1a12 09ae 47e1 7a14 -aeef 3f11 0000 0000 0000 0000 2262 0a17 -0a07 6861 6e64 6c65 7212 0c2f 6170 692f -6d65 7472 6963 7322 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -2260 0a15 0a07 6861 6e64 6c65 7212 0a2f -6170 692f 7175 6572 7922 4708 0011 0000 -0000 0000 0000 1a12 0900 0000 0000 00e0 -3f11 0000 0000 0000 0000 1a12 09cd cccc -cccc ccec 3f11 0000 0000 0000 0000 1a12 -09ae 47e1 7a14 aeef 3f11 0000 0000 0000 -0000 2266 0a1b 0a07 6861 6e64 6c65 7212 -102f 6170 692f 7175 6572 795f 7261 6e67 -6522 4708 0011 0000 0000 0000 0000 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0000 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 0000 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 0000 2262 0a17 0a07 -6861 6e64 6c65 7212 0c2f 6170 692f 7461 -7267 6574 7322 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 2260 -0a15 0a07 6861 6e64 6c65 7212 0a2f 636f -6e73 6f6c 6573 2f22 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -225c 0a11 0a07 6861 6e64 6c65 7212 062f -6772 6170 6822 4708 0011 0000 0000 0000 -0000 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0000 225b -0a10 0a07 6861 6e64 6c65 7212 052f 6865 -6170 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 5e0a 130a -0768 616e 646c 6572 1208 2f73 7461 7469 -632f 2247 0800 1100 0000 0000 0000 001a -1209 0000 0000 0000 e03f 1100 0000 0000 -0000 001a 1209 cdcc cccc cccc ec3f 1100 -0000 0000 0000 001a 1209 ae47 e17a 14ae -ef3f 1100 0000 0000 0000 0022 600a 150a -0768 616e 646c 6572 120a 7072 6f6d 6574 -6865 7573 2247 083b 1100 0000 00e0 b4fc -401a 1209 0000 0000 0000 e03f 1100 0000 -0000 349f 401a 1209 cdcc cccc cccc ec3f -1100 0000 0000 08a0 401a 1209 ae47 e17a -14ae ef3f 1100 0000 0000 0aa0 405c 0a19 -7072 6f63 6573 735f 6370 755f 7365 636f -6e64 735f 746f 7461 6c12 3054 6f74 616c -2075 7365 7220 616e 6420 7379 7374 656d -2043 5055 2074 696d 6520 7370 656e 7420 -696e 2073 6563 6f6e 6473 2e18 0022 0b1a -0909 a470 3d0a d7a3 d03f 4f0a 1270 726f -6365 7373 5f67 6f72 6f75 7469 6e65 7312 -2a4e 756d 6265 7220 6f66 2067 6f72 6f75 -7469 6e65 7320 7468 6174 2063 7572 7265 -6e74 6c79 2065 7869 7374 2e18 0122 0b12 -0909 0000 0000 0000 5140 4a0a 0f70 726f -6365 7373 5f6d 6178 5f66 6473 1228 4d61 -7869 6d75 6d20 6e75 6d62 6572 206f 6620 -6f70 656e 2066 696c 6520 6465 7363 7269 -7074 6f72 732e 1801 220b 1209 0900 0000 -0000 00c0 4043 0a10 7072 6f63 6573 735f -6f70 656e 5f66 6473 1220 4e75 6d62 6572 -206f 6620 6f70 656e 2066 696c 6520 6465 -7363 7269 7074 6f72 732e 1801 220b 1209 -0900 0000 0000 003d 404e 0a1d 7072 6f63 -6573 735f 7265 7369 6465 6e74 5f6d 656d -6f72 795f 6279 7465 7312 1e52 6573 6964 -656e 7420 6d65 6d6f 7279 2073 697a 6520 -696e 2062 7974 6573 2e18 0122 0b12 0909 -0000 0000 004b 8841 630a 1a70 726f 6365 -7373 5f73 7461 7274 5f74 696d 655f 7365 -636f 6e64 7312 3653 7461 7274 2074 696d -6520 6f66 2074 6865 2070 726f 6365 7373 -2073 696e 6365 2075 6e69 7820 6570 6f63 -6820 696e 2073 6563 6f6e 6473 2e18 0122 -0b12 0909 3d0a 172d e831 d541 4c0a 1c70 -726f 6365 7373 5f76 6972 7475 616c 5f6d -656d 6f72 795f 6279 7465 7312 1d56 6972 -7475 616c 206d 656d 6f72 7920 7369 7a65 -2069 6e20 6279 7465 732e 1801 220b 1209 -0900 0000 0020 12c0 415f 0a27 7072 6f6d -6574 6865 7573 5f64 6e73 5f73 645f 6c6f -6f6b 7570 5f66 6169 6c75 7265 735f 746f -7461 6c12 2554 6865 206e 756d 6265 7220 -6f66 2044 4e53 2d53 4420 6c6f 6f6b 7570 -2066 6169 6c75 7265 732e 1800 220b 1a09 -0900 0000 0000 0000 004f 0a1f 7072 6f6d -6574 6865 7573 5f64 6e73 5f73 645f 6c6f -6f6b 7570 735f 746f 7461 6c12 1d54 6865 -206e 756d 6265 7220 6f66 2044 4e53 2d53 -4420 6c6f 6f6b 7570 732e 1800 220b 1a09 -0900 0000 0000 0008 40cf 010a 2a70 726f -6d65 7468 6575 735f 6576 616c 7561 746f -725f 6475 7261 7469 6f6e 5f6d 696c 6c69 -7365 636f 6e64 7312 2c54 6865 2064 7572 -6174 696f 6e20 666f 7220 616c 6c20 6576 -616c 7561 7469 6f6e 7320 746f 2065 7865 -6375 7465 2e18 0222 7122 6f08 0b11 0000 -0000 0000 2240 1a12 097b 14ae 47e1 7a84 -3f11 0000 0000 0000 0000 1a12 099a 9999 -9999 99a9 3f11 0000 0000 0000 0000 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0000 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 f03f 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 f03f a301 0a39 7072 -6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 -746f 7261 6765 5f63 6865 636b 706f 696e -745f 6475 7261 7469 6f6e 5f6d 696c 6c69 -7365 636f 6e64 7312 5754 6865 2064 7572 -6174 696f 6e20 2869 6e20 6d69 6c6c 6973 -6563 6f6e 6473 2920 6974 2074 6f6f 6b20 -746f 2063 6865 636b 706f 696e 7420 696e -2d6d 656d 6f72 7920 6d65 7472 6963 7320 -616e 6420 6865 6164 2063 6875 6e6b 732e -1801 220b 1209 0900 0000 0000 0000 00f2 -010a 2870 726f 6d65 7468 6575 735f 6c6f -6361 6c5f 7374 6f72 6167 655f 6368 756e -6b5f 6f70 735f 746f 7461 6c12 3354 6865 -2074 6f74 616c 206e 756d 6265 7220 6f66 -2063 6875 6e6b 206f 7065 7261 7469 6f6e -7320 6279 2074 6865 6972 2074 7970 652e -1800 221b 0a0e 0a04 7479 7065 1206 6372 -6561 7465 1a09 0900 0000 0000 b880 4022 -1c0a 0f0a 0474 7970 6512 0770 6572 7369 -7374 1a09 0900 0000 0000 c05b 4022 180a -0b0a 0474 7970 6512 0370 696e 1a09 0900 -0000 0000 807b 4022 1e0a 110a 0474 7970 -6512 0974 7261 6e73 636f 6465 1a09 0900 -0000 0000 a06b 4022 1a0a 0d0a 0474 7970 -6512 0575 6e70 696e 1a09 0900 0000 0000 -807b 40c4 010a 3c70 726f 6d65 7468 6575 -735f 6c6f 6361 6c5f 7374 6f72 6167 655f -696e 6465 7869 6e67 5f62 6174 6368 5f6c -6174 656e 6379 5f6d 696c 6c69 7365 636f -6e64 7312 3751 7561 6e74 696c 6573 2066 -6f72 2062 6174 6368 2069 6e64 6578 696e -6720 6c61 7465 6e63 6965 7320 696e 206d -696c 6c69 7365 636f 6e64 732e 1802 2249 -2247 0801 1100 0000 0000 0000 001a 1209 -0000 0000 0000 e03f 1100 0000 0000 0000 -001a 1209 cdcc cccc cccc ec3f 1100 0000 -0000 0000 001a 1209 ae47 e17a 14ae ef3f -1100 0000 0000 0000 00bf 010a 2d70 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 696e 6465 7869 6e67 5f62 -6174 6368 5f73 697a 6573 1241 5175 616e -7469 6c65 7320 666f 7220 696e 6465 7869 -6e67 2062 6174 6368 2073 697a 6573 2028 -6e75 6d62 6572 206f 6620 6d65 7472 6963 -7320 7065 7220 6261 7463 6829 2e18 0222 -4922 4708 0111 0000 0000 0000 0040 1a12 -0900 0000 0000 00e0 3f11 0000 0000 0000 -0040 1a12 09cd cccc cccc ccec 3f11 0000 -0000 0000 0040 1a12 09ae 47e1 7a14 aeef -3f11 0000 0000 0000 0040 660a 3070 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 696e 6465 7869 6e67 5f71 -7565 7565 5f63 6170 6163 6974 7912 2354 -6865 2063 6170 6163 6974 7920 6f66 2074 -6865 2069 6e64 6578 696e 6720 7175 6575 -652e 1801 220b 1209 0900 0000 0000 00d0 -406d 0a2e 7072 6f6d 6574 6865 7573 5f6c -6f63 616c 5f73 746f 7261 6765 5f69 6e64 -6578 696e 675f 7175 6575 655f 6c65 6e67 -7468 122c 5468 6520 6e75 6d62 6572 206f -6620 6d65 7472 6963 7320 7761 6974 696e -6720 746f 2062 6520 696e 6465 7865 642e -1801 220b 1209 0900 0000 0000 0000 0067 -0a2f 7072 6f6d 6574 6865 7573 5f6c 6f63 -616c 5f73 746f 7261 6765 5f69 6e67 6573 -7465 645f 7361 6d70 6c65 735f 746f 7461 -6c12 2554 6865 2074 6f74 616c 206e 756d -6265 7220 6f66 2073 616d 706c 6573 2069 -6e67 6573 7465 642e 1800 220b 1a09 0900 -0000 0080 27cd 40c3 010a 3770 726f 6d65 -7468 6575 735f 6c6f 6361 6c5f 7374 6f72 -6167 655f 696e 7661 6c69 645f 7072 656c -6f61 645f 7265 7175 6573 7473 5f74 6f74 -616c 1279 5468 6520 746f 7461 6c20 6e75 -6d62 6572 206f 6620 7072 656c 6f61 6420 -7265 7175 6573 7473 2072 6566 6572 7269 -6e67 2074 6f20 6120 6e6f 6e2d 6578 6973 -7465 6e74 2073 6572 6965 732e 2054 6869 -7320 6973 2061 6e20 696e 6469 6361 7469 -6f6e 206f 6620 6f75 7464 6174 6564 206c -6162 656c 2069 6e64 6578 6573 2e18 0022 -0b1a 0909 0000 0000 0000 0000 6f0a 2a70 -726f 6d65 7468 6575 735f 6c6f 6361 6c5f -7374 6f72 6167 655f 6d65 6d6f 7279 5f63 -6875 6e6b 6465 7363 7312 3254 6865 2063 -7572 7265 6e74 206e 756d 6265 7220 6f66 -2063 6875 6e6b 2064 6573 6372 6970 746f -7273 2069 6e20 6d65 6d6f 7279 2e18 0122 -0b12 0909 0000 0000 0020 8f40 9c01 0a26 -7072 6f6d 6574 6865 7573 5f6c 6f63 616c -5f73 746f 7261 6765 5f6d 656d 6f72 795f -6368 756e 6b73 1263 5468 6520 6375 7272 -656e 7420 6e75 6d62 6572 206f 6620 6368 -756e 6b73 2069 6e20 6d65 6d6f 7279 2c20 -6578 636c 7564 696e 6720 636c 6f6e 6564 -2063 6875 6e6b 7320 2869 2e65 2e20 6368 -756e 6b73 2077 6974 686f 7574 2061 2064 -6573 6372 6970 746f 7229 2e18 0122 0b12 -0909 0000 0000 00e8 8d40 600a 2670 726f -6d65 7468 6575 735f 6c6f 6361 6c5f 7374 -6f72 6167 655f 6d65 6d6f 7279 5f73 6572 -6965 7312 2754 6865 2063 7572 7265 6e74 -206e 756d 6265 7220 6f66 2073 6572 6965 -7320 696e 206d 656d 6f72 792e 1801 220b -1209 0900 0000 0000 807a 40b7 010a 3570 -726f 6d65 7468 6575 735f 6c6f 6361 6c5f -7374 6f72 6167 655f 7065 7273 6973 745f -6c61 7465 6e63 795f 6d69 6372 6f73 6563 -6f6e 6473 1231 4120 7375 6d6d 6172 7920 -6f66 206c 6174 656e 6369 6573 2066 6f72 -2070 6572 7369 7374 696e 6720 6561 6368 -2063 6875 6e6b 2e18 0222 4922 4708 6f11 -1c2f dd24 e68c cc40 1a12 0900 0000 0000 -00e0 3f11 8d97 6e12 8360 3e40 1a12 09cd -cccc cccc ccec 3f11 0ad7 a370 3d62 6b40 -1a12 09ae 47e1 7a14 aeef 3f11 7b14 ae47 -e1b6 7240 6a0a 2f70 726f 6d65 7468 6575 -735f 6c6f 6361 6c5f 7374 6f72 6167 655f -7065 7273 6973 745f 7175 6575 655f 6361 -7061 6369 7479 1228 5468 6520 746f 7461 -6c20 6361 7061 6369 7479 206f 6620 7468 -6520 7065 7273 6973 7420 7175 6575 652e -1801 220b 1209 0900 0000 0000 0090 407a -0a2d 7072 6f6d 6574 6865 7573 5f6c 6f63 -616c 5f73 746f 7261 6765 5f70 6572 7369 -7374 5f71 7565 7565 5f6c 656e 6774 6812 -3a54 6865 2063 7572 7265 6e74 206e 756d -6265 7220 6f66 2063 6875 6e6b 7320 7761 -6974 696e 6720 696e 2074 6865 2070 6572 -7369 7374 2071 7565 7565 2e18 0122 0b12 -0909 0000 0000 0000 0000 ac01 0a29 7072 -6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 -746f 7261 6765 5f73 6572 6965 735f 6f70 -735f 746f 7461 6c12 3454 6865 2074 6f74 -616c 206e 756d 6265 7220 6f66 2073 6572 -6965 7320 6f70 6572 6174 696f 6e73 2062 -7920 7468 6569 7220 7479 7065 2e18 0022 -1b0a 0e0a 0474 7970 6512 0663 7265 6174 -651a 0909 0000 0000 0000 0040 222a 0a1d -0a04 7479 7065 1215 6d61 696e 7465 6e61 -6e63 655f 696e 5f6d 656d 6f72 791a 0909 -0000 0000 0000 1440 d601 0a2d 7072 6f6d -6574 6865 7573 5f6e 6f74 6966 6963 6174 -696f 6e73 5f6c 6174 656e 6379 5f6d 696c -6c69 7365 636f 6e64 7312 584c 6174 656e -6379 2071 7561 6e74 696c 6573 2066 6f72 -2073 656e 6469 6e67 2061 6c65 7274 206e -6f74 6966 6963 6174 696f 6e73 2028 6e6f -7420 696e 636c 7564 696e 6720 6472 6f70 -7065 6420 6e6f 7469 6669 6361 7469 6f6e -7329 2e18 0222 4922 4708 0011 0000 0000 -0000 0000 1a12 0900 0000 0000 00e0 3f11 -0000 0000 0000 0000 1a12 09cd cccc cccc -ccec 3f11 0000 0000 0000 0000 1a12 09ae -47e1 7a14 aeef 3f11 0000 0000 0000 0000 -680a 2770 726f 6d65 7468 6575 735f 6e6f -7469 6669 6361 7469 6f6e 735f 7175 6575 -655f 6361 7061 6369 7479 122e 5468 6520 -6361 7061 6369 7479 206f 6620 7468 6520 -616c 6572 7420 6e6f 7469 6669 6361 7469 -6f6e 7320 7175 6575 652e 1801 220b 1209 -0900 0000 0000 0059 4067 0a25 7072 6f6d -6574 6865 7573 5f6e 6f74 6966 6963 6174 -696f 6e73 5f71 7565 7565 5f6c 656e 6774 -6812 2f54 6865 206e 756d 6265 7220 6f66 -2061 6c65 7274 206e 6f74 6966 6963 6174 -696f 6e73 2069 6e20 7468 6520 7175 6575 -652e 1801 220b 1209 0900 0000 0000 0000 -009e 020a 3070 726f 6d65 7468 6575 735f -7275 6c65 5f65 7661 6c75 6174 696f 6e5f -6475 7261 7469 6f6e 5f6d 696c 6c69 7365 -636f 6e64 7312 2354 6865 2064 7572 6174 -696f 6e20 666f 7220 6120 7275 6c65 2074 -6f20 6578 6563 7574 652e 1802 2260 0a15 -0a09 7275 6c65 5f74 7970 6512 0861 6c65 -7274 696e 6722 4708 3711 0000 0000 0000 -2840 1a12 0900 0000 0000 00e0 3f11 0000 -0000 0000 0000 1a12 09cd cccc cccc ccec -3f11 0000 0000 0000 0000 1a12 09ae 47e1 -7a14 aeef 3f11 0000 0000 0000 0840 2261 -0a16 0a09 7275 6c65 5f74 7970 6512 0972 -6563 6f72 6469 6e67 2247 0837 1100 0000 -0000 002e 401a 1209 0000 0000 0000 e03f -1100 0000 0000 0000 001a 1209 cdcc cccc -cccc ec3f 1100 0000 0000 0000 001a 1209 -ae47 e17a 14ae ef3f 1100 0000 0000 0008 -4069 0a29 7072 6f6d 6574 6865 7573 5f72 -756c 655f 6576 616c 7561 7469 6f6e 5f66 -6169 6c75 7265 735f 746f 7461 6c12 2d54 -6865 2074 6f74 616c 206e 756d 6265 7220 -6f66 2072 756c 6520 6576 616c 7561 7469 -6f6e 2066 6169 6c75 7265 732e 1800 220b -1a09 0900 0000 0000 0000 0060 0a21 7072 -6f6d 6574 6865 7573 5f73 616d 706c 6573 -5f71 7565 7565 5f63 6170 6163 6974 7912 -2c43 6170 6163 6974 7920 6f66 2074 6865 -2071 7565 7565 2066 6f72 2075 6e77 7269 -7474 656e 2073 616d 706c 6573 2e18 0122 -0b12 0909 0000 0000 0000 b040 da01 0a1f -7072 6f6d 6574 6865 7573 5f73 616d 706c -6573 5f71 7565 7565 5f6c 656e 6774 6812 -a701 4375 7272 656e 7420 6e75 6d62 6572 -206f 6620 6974 656d 7320 696e 2074 6865 -2071 7565 7565 2066 6f72 2075 6e77 7269 -7474 656e 2073 616d 706c 6573 2e20 4561 -6368 2069 7465 6d20 636f 6d70 7269 7365 -7320 616c 6c20 7361 6d70 6c65 7320 6578 -706f 7365 6420 6279 206f 6e65 2074 6172 -6765 7420 6173 206f 6e65 206d 6574 7269 -6320 6661 6d69 6c79 2028 692e 652e 206d -6574 7269 6373 206f 6620 7468 6520 7361 -6d65 206e 616d 6529 2e18 0122 0b12 0909 -0000 0000 0000 0000 d902 0a29 7072 6f6d -6574 6865 7573 5f74 6172 6765 745f 696e -7465 7276 616c 5f6c 656e 6774 685f 7365 -636f 6e64 7312 2141 6374 7561 6c20 696e -7465 7276 616c 7320 6265 7477 6565 6e20 -7363 7261 7065 732e 1802 2282 010a 0f0a -0869 6e74 6572 7661 6c12 0331 3573 226f -0804 1100 0000 0000 804d 401a 1209 7b14 -ae47 e17a 843f 1100 0000 0000 002c 401a -1209 9a99 9999 9999 a93f 1100 0000 0000 -002c 401a 1209 0000 0000 0000 e03f 1100 -0000 0000 002e 401a 1209 cdcc cccc cccc -ec3f 1100 0000 0000 002e 401a 1209 ae47 -e17a 14ae ef3f 1100 0000 0000 002e 4022 -8101 0a0e 0a08 696e 7465 7276 616c 1202 -3173 226f 083a 1100 0000 0000 003c 401a -1209 7b14 ae47 e17a 843f 1100 0000 0000 -0000 001a 1209 9a99 9999 9999 a93f 1100 -0000 0000 0000 001a 1209 0000 0000 0000 -e03f 1100 0000 0000 0000 001a 1209 cdcc -cccc cccc ec3f 1100 0000 0000 00f0 3f1a -1209 ae47 e17a 14ae ef3f 1100 0000 0000 -00f0 3f \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz deleted file mode 100644 index 62fccb61650..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/protobuf.gz +++ /dev/null @@ -1,129 +0,0 @@ -1f8b 0808 efa0 c754 0003 7072 6f74 6f62 -7566 00ed 594d 8c1c c515 9eb1 8d3d 5b86 -6037 265e 8c4d ca03 c4bb ceee cc9a 9f58 -01cc f6ca 4424 041b 8837 21c8 24ed daee -9a99 cef6 1f55 d578 c7e4 b004 0e39 8088 -8448 048a 124b 4442 9110 e110 25b9 c54a -9072 01c5 9724 4a24 2472 413e 448a 8592 -1b87 bcea aeda eeea 99d9 3530 49a4 68e7 -b0bb 5355 fdde abf7 bef7 bdf7 7a3f 6ca0 -664f 88c4 61f4 8994 72e1 7829 23c2 8f23 -27f4 5d16 73ea c691 c7ad cf2d f628 fed2 -e2e2 c358 9dc3 0111 3472 7dca b11f e1f2 -d9d6 e496 e6a3 e86a b4a3 4722 2fa0 ccaa -b79b f737 6abb 6bea b3cf 9ac8 ff78 6fbe -bcf6 cedb f2f3 7763 ed8d fbff 766e cf1b -ff28 d69a df44 5621 7847 9bc0 2fc1 c727 -7e09 ed2d c45f dd26 89df 0ea9 60be 3b46 -1d67 d0f5 850e 94e9 008f b2fe f834 74d0 -8d85 865d 8506 8791 a84b ffa3 de12 8475 -e938 2352 f116 208c c701 e563 84d4 e368 -77a1 617b bbcb 48d2 1b9f f4d3 6857 21fd -aa76 8f92 647c c2bf 85ae 2b84 37da 5c40 -e6ba 6374 8de9 fc84 c590 0c3d 9aca f0de -bdfb f40b bffd 5763 fe9f 7659 8314 f0fb -9fbf 6897 35b4 dfbd 65fb d397 7f60 9735 -1c43 7f7e f5cd 975e b3df 6fa0 bd06 fb70 -ff1c 7596 fa82 720b 0f50 8edc cce8 263b -b0c9 339b 3cb3 c933 5afa ff2f cfc8 13f6 -5b17 ed01 0d73 cc1e d090 af99 1a60 ed3b -e8ba 32cd 7047 c482 04d6 cd8b f217 8ed2 -7089 321c 770c bae1 3824 1e6d 4dd6 9af7 -a29d 689b 1b7b d4da 7adb dcdc 085b d135 -68bb fc33 f6ac ad00 cd7d 13b9 b5ab 27ec -4b0d 34a9 b4f3 0470 45cb 2c77 b0c4 72f9 -ee26 cd7d 02ec 6cd2 dc26 cd7d 6ce1 ff73 -9a7b ef17 1f0e d2dc 1d3f 19a4 b9c6 f941 -9a43 e7ed c7d1 0d20 d5a5 9c3b 6e92 3a6a -2053 6437 9793 5dca 81ea c006 ccfb 5cd0 -101f 7ff8 6b58 f821 d04e 4223 2169 676d -8eab 3577 028d fd34 91dd dac5 f987 90a5 -8577 6316 a7c2 8f80 bf0e 9f5c 23cf 6215 -8b1e 11d8 4d19 0391 411f d315 9f8b d664 -bdb9 d352 b458 7bc4 7e00 5dab e585 64c5 -e9c0 9439 7582 acf8 611a 9618 3906 ab70 -c70f 28f6 2877 999f 8898 7153 d405 fb38 -daa5 45c9 f399 2c7c f2a3 c838 669f 4407 -b40c 6062 df03 cb9d 9086 31e4 79ce d437 -7d55 2de3 7c39 e3e9 124d 97c4 7de5 7b0b -2eda a7c5 018e 9870 a48f 7544 accf 9f92 -6bb9 dfc1 4040 0156 a741 6ae4 529c 46fe -0aa6 49ec f68c 88e4 3a8e a1bd b397 8efc -71e1 41b4 5feb 78d2 6722 2581 69f1 81af -e7ab 1b1a 8cad 0b0b 0e3a 5420 d2f1 22b0 -db73 8238 5e4e 13a7 43fc 2005 af28 24dd -2a6b 5611 a2fb 4e9e 9a3d 751f cecf 627d -56c3 47a3 ff21 f499 51f2 b5dc 03eb c8ad -c86b d87f a8a3 c325 81f4 4912 a404 025b -7e81 1104 bef6 f88c 94ad b770 2786 1c08 -02ac 9e82 25c0 6c0c 38a5 6e2a a82c b94f -34e3 c64e 95ba 4d99 6c4f ed91 e9f6 ac91 -e2af bc2c 3f3f 9bff 88f4 7079 7e90 1e2e -cfbf 5a47 5f28 5d28 885d 8827 871b 912e -75dc 1e75 9793 d88f c488 fb3d 6adc 6f2a -7b27 536c 4f63 1fd0 068e 94b7 2c64 0118 -6615 3654 5dce 9801 58d5 8353 69b4 5cc9 -925a ed83 3a9a 5ac7 4878 0432 50c7 f376 -6993 a8b4 58d9 2199 924c f97d a92f f1ef -332c fa49 d66e dd88 3e85 b6c9 2fd6 7697 -5122 a88e faaf 57ed e67e 74ad dadc 0122 -38f0 8ade bd70 da6e 4eca 4e2d dbdd 9af8 -d15a 0ff6 94dd bc09 ca52 be33 21a0 6e73 -d9ce e9fd f3cb 7673 1ff4 6ff9 fe55 6964 -3efb 561d dd33 f2ce 7ee4 01bb 455d 6789 -08b7 e7e4 6fc5 fa66 6c8e 3e92 9248 00ff -f00c 78d9 49ac 1fac be48 2b9e 9330 fc32 -d486 fa58 aacf 6fea 68f6 4a6f 9175 a0d6 -8269 f69a c1b9 fd79 973a 5504 5623 08c2 -921f 991e b8c0 6071 cbd7 aa17 182c 6eb0 -d641 731b db0f 8d59 0a40 2409 717d d187 -061f 10a8 bf69 a65d bb48 76d8 44f8 453b -44ad 2b55 13d0 a82b 7a39 b50c fae1 2cf1 -85d4 0219 b7a4 9452 af9a 4f5d d45e 475b -17c6 10ea 399c 8449 60b2 6f35 abd4 11ac -9f29 b3e5 eaa1 77ec dfd5 d1d1 7514 010d -fa9e 9330 1ac4 c4ab 4e49 fd61 0ad5 d962 -5862 b443 1953 1726 388a a3d9 acec cb82 -092d 07e0 bb85 177b 3e98 2849 46fa c377 -73b2 9215 3a15 1ea4 8107 c9b0 4403 e5ac -8112 121b 8c6f de41 15be 8c5d 6495 e7d6 -6d59 ecf3 1e64 807f 4a8d 4096 76d9 d346 -70f0 0bf6 8fea e8b3 57a4 905b ee3a ca4a -1a66 a0c4 b841 ea49 37b9 411c 51cd b3c0 -d82d dad2 5fce fa30 47a6 02dc 58d8 396d -5877 e979 fbcc c6c6 e57e b70e 0d37 2edf -1d71 fdd5 73f6 afea e8ce 911a 14f9 9608 -aff4 df82 230b 98a7 6148 5896 7305 c149 -1a51 0f4a 0f50 023c 925d 5933 45bc 7b7f -fbdd 5bde 7fee 6d83 299e ff61 643d 73e6 -5e83 29a0 254d 8e2d 2d1b 4c91 95e8 5f32 -fbdb eb24 95b6 bb42 1453 05c6 ab74 a19e -18c6 16df b7cf ad43 aaa6 2a45 1677 ad0b -14cd 1910 930d 54d7 6aaf d7d1 f448 dd79 -6c4b b5f8 8ea1 ac91 23e0 6315 6360 e4e6 -6174 406d 5e1f 12e8 2768 44a0 7905 3e51 -005c 3bbb c7fe 9359 7ea2 58f8 1d45 007c -78d5 fcc6 83f9 2adc be5c 8638 8db2 f4c9 -de55 6043 0e54 a358 f634 3ac3 3c16 2709 -a498 7168 ad2a 8d67 a8eb 196d b379 ad0a -c65a c38a d1b0 6b0c 09f7 6376 17dd ba81 -2285 b0b6 598e 8629 50f0 1a0a ab1f 6f31 -ea2c 4b03 ea14 6df2 88ee f3e6 c1ee 1acb -272b 4db5 1c80 2732 8919 681a 996d 1029 -88c6 51e5 d1a9 613d c215 46a3 6137 09fa -7459 c304 0303 9967 aa68 7d22 15be 9175 -55f7 5426 a5d9 6159 9739 a678 66e4 c474 -061d 2c69 d24d 4005 5433 c72b 80ca f6b3 -10a4 d159 e60b c821 dd1d 98a1 7ed3 fe6b -dd98 c94c 0d0a 4daf d58f 0f90 952f 6868 -8268 843e fc45 c9f0 f238 76e3 3061 8017 -9ecd 5dba 5da1 2b09 140d 4fd2 0e14 439c -bfee c284 67df f246 0adc 0350 ebab 02a9 -9b2b 7559 9003 5887 1fd3 5518 ff65 8b11 -a75c b223 398a 81e7 d5ed d6e6 f183 0b6e -3628 eb7d 2042 2ace 5279 1597 9124 7f0b -fbdd 3acc 1e0d 7dc4 da7a e44e 0e43 e2b6 -1c19 ab27 860c 8933 f6e0 9038 3304 7dad -214d 706b 4813 dcb2 9b4f d781 900b 23b6 -1c91 36dc a5f6 eff9 af0c aaff 06f1 48e5 -4433 2000 00 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz deleted file mode 100644 index 3f8199dfb26..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/test.gz +++ /dev/null @@ -1,163 +0,0 @@ -1f8b 0808 2aa1 c754 0003 7465 7874 00b5 -5b5d 939b 3816 7def 5fa1 ea79 99a9 4d3c -601b db3c f4c3 5426 55f3 309b ca6e 7ab7 -6a9e 281a d436 150c 04c4 a4bd 5df3 dff7 -4a88 361f 025d 094f 1e92 34e8 1cae 8ea4 -ab7b 04fd 03f9 ede3 ef9f c989 b122 28e9 -b79a 562c 88eb 3264 499e 05e7 242a f38a -4679 1657 e4f1 44c9 6f8f 8f9f 896c 46d2 -90d1 2c4a 6845 928c 749b aeee 7e20 8f7f -7cfe 8861 adea f339 2c2f 77fa a6af a730 -8b53 5a3e dcff 7cff ee5b 1d66 2c49 e9c3 -bdb3 f2ee ff22 ce12 027f 3101 9621 80ee -7659 90a8 28af 3366 8eeb 2042 f887 558b -7553 d158 a8a7 a4b1 d450 7259 2a69 84ee -e28a e4e7 3365 6512 dd40 d429 2e1b 6527 -b96c e5ed 10da 6a6c 4c31 0043 cbf2 7213 -9915 4c96 22ab 9816 48dc d02d 10d8 8440 -050d ca30 3bd2 db89 ace2 5b22 b592 6fa9 -e092 74a9 ec46 3403 0216 9647 7a8b cc3c -c565 29ba 9a6b 81e0 2de1 02b1 cd28 3a60 -f8b9 ca53 5a2d 2f1c 2698 2c44 9e62 b294 -f84a 6729 b029 4107 7a2c c3e2 b458 5a05 -8b85 ac2a 164b 491b 2a4b 394d c01d d889 -86c5 6225 c724 1642 2a48 2c75 144c 9632 -1a60 3ba8 8ac1 ed68 f96a 57f2 5868 a9e6 -b194 b325 b354 d40c 7e05 1665 0e45 dc89 -d68a bdca dd38 fbd5 7aef dd84 90cb e21e -bcc3 6ab7 59df 8690 336e 9cc3 7eb5 396c -8df5 eeb0 425c 7bff 70d8 ad3c 47fe 712d -46a0 4fe8 fa60 96c7 16bc 4afe 4783 a70b -a30a dfcd ef09 cf2d eeab cd76 07af 74d8 -d7fb 26b6 1a81 524c 6a0c 6a16 a675 cd9d -a67a abac 0c07 e98f d158 ac0c 5827 3c29 -c694 819d 9144 0fb1 34ba 6604 6889 4c2c -edb4 4e73 2674 4e2c 1cce cab1 9ac0 4dd4 -427a d359 ad26 fca4 4629 2d6a 81f5 3427 -31d6 0c6b 32f5 ca4d 5942 8c7e 7aac a587 -3423 3051 0fed 1667 959b f477 1ad5 1038 -2b33 6802 c7aa 6560 fb26 b59a b16a 334a -a150 c6ae 0e0b c5ea 83f4 6f93 da4c f8ae -195d b408 537b 8644 6215 c119 b149 41d4 -0e6a 460f 1dc0 c267 e1c1 5851 d08e 6a52 -9749 1f34 230d 0283 334c 6bdf b527 f017 -1368 1866 0cd0 66bb 3d1c b07a 619c 4e15 -b09c 8529 7914 7f67 f5f9 8996 247f ee39 -9e8a 9cc3 982a 8d4e 0b17 4fa6 e59d e2de -6b94 c7d0 edb5 e3dc bf53 4ac3 ff93 c70f -f7b0 8728 e3ac 0ac8 9c74 c292 3537 359e -6ccc 3030 65a3 0638 5786 87f9 96b0 79dc -8c31 1bb7 9d73 6673 1169 ad99 2918 ad85 -de9c e914 195b 2dbd 2e08 8cb1 3fb3 62c0 -eb84 7368 5ab1 d456 0ba1 1812 6868 d22c -f046 9269 6d1a 46b0 91e3 c2c9 a587 5939 -356b 1673 e1f4 5e0d 2ddf d870 1988 8800 -1bdb 352b 0623 0911 860d 239f c279 e1a4 -c300 0d3d 9b05 1e2d 19ca b5e9 0453 1a30 -bd5c 3898 8171 33c4 a245 d25a 379d 4023 -27a6 1747 0fc1 bb37 3328 5a16 9d7f d3a9 -32f4 637a 51b4 0823 0b67 8c46 2b83 3071 -3a71 148e 4caf 0f06 84f4 71ce d65f 4021 -7c98 e31d 9650 341c bb2d 52b1 9e27 5b6f -f79d 7758 5ae1 a6fc 1c5c 8f68 05cd 8b3a -685f 7a75 5d5d 5d81 a703 1252 5d2a 46cf -e4c3 e7ff 1096 9cc1 3515 3463 dc35 0d3f -1c9d 666c 8dde 740b 1819 6f18 d931 2ff3 -9a25 1938 af4f 6f16 b373 919d 4246 a2ba -2c21 9ef4 42e8 4b52 b151 309d f6c7 b03e -d23b c58d bd33 7cf4 397c 099e e38a fc33 -7c49 cef5 b963 7173 e83d 7986 7124 31ad -a232 2958 5e8e 2568 f1fd 47b6 570f aebf -1e3e 91f3 8a9b 9f0c 1ff5 06ec 3feb edf2 -7a34 e230 6992 1834 0bce f49c 432d d498 -db7f cbab a4b9 2acc f1d8 1bcf 73f4 4350 -b7f1 569b c3de f1fc 35fd 87b3 1f86 068b -bc64 019f 66ed fc20 5ff8 a566 e681 2630 -91db c610 6116 5152 67c9 0ba1 451e 9de6 -e6a4 82b8 1fac a281 bbda aed7 9bdd c1df -1e36 3b88 7624 e49f 49c9 ea30 edf7 efbf -cd45 9c8c 4a86 7e60 ca26 de6a eb6e f707 -dfe5 2a1e 3a71 c9a5 1ec4 1974 290e d23c -ff5a 17c1 7398 a435 0c47 bbc0 41c4 eb8c -fef5 d397 f75f 7e25 4d53 d236 ed86 8a22 -edac 7154 7b47 1735 225a 7d94 d8e8 da76 -7b45 54f4 cf30 ad43 587c dd4f 05d2 34e9 -7e63 dfde 21cf 3964 cd34 2512 0497 2051 -e590 9c68 5433 aa8a 5747 df9e 3ae1 21af -ddbd c671 c596 698b f696 a017 81c5 2725 -d660 5334 df70 89bb 3641 8839 45d6 1bc5 -9449 f308 966c 05d8 f048 83e8 44a3 af45 -9e64 0c33 837e 14bf 9871 bdfb 1349 20ff -c12c e5f3 e84a 0549 e5bd cc31 f218 45ec -d650 46c6 d0aa cebe 2a17 8761 606f a9c8 -12af 5ae4 430a 0815 76ab ee6a 6783 6365 -d186 6f87 a55c 504f 17be 1124 2561 9742 -b9a6 e69f a148 06b3 8057 fe98 87fb a8a4 -21e3 8706 9e7f 30c5 42ec 1594 27e2 6ba4 -ad31 38c9 00e8 af1d 5320 2bc3 ace2 27e9 -00df ba9e 29bc ceae 4fd6 8d63 92c5 5080 -65c7 e029 64d1 2968 7ecd e8d2 9f0d ff92 -0bb4 1259 5234 242d 6ef8 8b49 5798 7e7c -31cf 5664 5163 92f9 dcb6 8cce bf31 dd72 -3e91 1117 5234 29d2 359d 3dcd 8b99 fe74 -799b 28cd bc69 9afc 784d 126d 1284 95d6 -34f9 c978 e234 9ca6 3345 a046 5363 bd00 -ef2f c55b 1088 d136 c518 0fef b79a d690 -6dc2 228c 1276 11c9 feed 0759 ddbf 8db3 -686b 3086 036e cdd6 3505 7377 fc7b 53c3 -0ea5 343b b2d3 a052 6d27 e4f7 3061 bc3f -b07b 3fc9 eed1 d8b8 5ff2 1166 bd92 204c -f63e 5270 f971 5085 e722 a573 9bb1 6c41 -5a08 a627 4a72 ed2e 3c81 db38 dbbd bee6 -4a32 a8de 9238 284a 9ae6 613c 7a73 ade8 -996c 7a7d 815d d267 5a96 72ec 4292 e5d9 -7b71 c8c0 5d72 454b d8ab 5640 9480 16bc -f6e2 439b 444d 0dc7 dd7b cd62 4889 316c -6c4f 3495 e38e dacc 6603 47a8 368b d7cf -0569 3445 49c0 0f1e 9af2 549e b38c aab2 -ced1 84d8 b805 58df cbf1 4334 337b 0c70 -1dcf 37ea cc6c 473a d1bf 03b7 16a5 75cc -073e 4af3 8cb6 0535 94e6 2bba 6a7f f89e -b013 0c32 4c8c ab06 883d a71f 9141 af79 -8f11 8598 8434 f373 a2c7 f2a6 f978 4920 -2e6a d978 bbd6 e753 591e 778a 88ce 6f9b -ffd2 6ec9 3cf4 6b99 c88b 0289 e323 4543 -a80a 8450 fade cc3e 4ebb ffcf a147 75c0 -c659 6df6 fb1b 9035 47c6 9b95 b7f1 6fc1 -26e8 76eb dd6a bbdb d8f1 3515 8303 c3bb -9af5 16b3 1cb2 82d8 e3a7 88a2 8490 9971 -5048 4800 b68e 98e0 d74c f509 14ac 54d3 -1e75 6a88 c914 d596 12b0 7017 f710 5750 -2831 fa24 d42c 7d8d ad97 f9c1 ded7 8f9e -a2dd 1c87 88a1 b39f 2980 27a0 e730 8147 -6661 16f1 ad57 a63e f1a6 4521 5296 b3e4 -59d6 0895 daa7 fede 5c24 df7a e6a7 a299 -d88e c467 46a4 4703 1e28 e787 41ed 8e15 -9779 51c0 96d5 6ba4 dc97 10d1 2872 a11e -356f 930d f123 1f6b 8ab7 2018 3b5f 04a6 -c964 aaa5 d107 232c 906a 9427 d7f8 2cfb -6875 cfb6 761d 6cf8 4ac3 a30a 5b66 2aa3 -e8a7 32d3 4c5b 55dc 659d d2e0 7a0c 8f3e -bc27 1ca8 39b3 c771 2b56 0f0a f82a 5a35 -f945 880a eb5a f5ae fff6 bca3 c572 2bde -d189 048a 58bc 0557 91ff 3538 aac7 b135 -6fc6 27f8 fa25 8c71 bf4b b854 c67f c340 -4d10 2f1f a929 62f1 8bb7 8b87 eaca 0eda -9a4b 3b1e ab1e a1eb 2116 bce2 ade7 b004 -114b fd0a 997d fba9 a157 d41e 1a84 2a69 -b547 1d83 ccfc 61b0 4388 db22 5dd5 d9f7 -3261 b01f b507 33aa d027 5847 1976 a2dd -d6f1 77da 5865 26fe 30aa 5d13 46cf fd8d -6022 70f2 915b 38de 1cc4 3c17 25cc 854a -bc4b 6d8f 9ce8 4b01 c621 e665 22b8 72d2 -7c8e 48c2 4afc d41c b7c1 08c2 34ba 48a7 -de1e c149 d580 07f6 2bf8 4b59 0e29 bba3 -9168 66fb 69a2 0b78 7558 c214 904d df3e -2ef8 2512 5f09 b4b7 a1f6 a5ec 3be5 6a44 -6558 a887 5143 a9d8 6ee6 11af edf5 877b -d71b 7ca2 245e 1bbb db1b 9179 3724 f346 -19c5 9ecb bf25 9729 9948 997d 42fe 7ad0 -84a1 c992 238e b55d 8f54 53c0 b90d d568 -1fb4 a6ba 1dd3 e813 017b 2643 aae1 c8f3 -41f3 168d 7bf3 71df feee ff2d f9e8 431a -5200 00 \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text deleted file mode 100644 index f3d8c378443..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/testdata/text +++ /dev/null @@ -1,322 +0,0 @@ -# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. -# TYPE http_request_duration_microseconds summary -http_request_duration_microseconds{handler="/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/"} 0 -http_request_duration_microseconds_count{handler="/"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/alerts",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/alerts"} 0 -http_request_duration_microseconds_count{handler="/alerts"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/metrics",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/metrics"} 0 -http_request_duration_microseconds_count{handler="/api/metrics"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query"} 0 -http_request_duration_microseconds_count{handler="/api/query"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/query_range",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/query_range"} 0 -http_request_duration_microseconds_count{handler="/api/query_range"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/api/targets",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/api/targets"} 0 -http_request_duration_microseconds_count{handler="/api/targets"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/consoles/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/consoles/"} 0 -http_request_duration_microseconds_count{handler="/consoles/"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/graph",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/graph"} 0 -http_request_duration_microseconds_count{handler="/graph"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/heap",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/heap"} 0 -http_request_duration_microseconds_count{handler="/heap"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.5"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.9"} 0 -http_request_duration_microseconds{handler="/static/",quantile="0.99"} 0 -http_request_duration_microseconds_sum{handler="/static/"} 0 -http_request_duration_microseconds_count{handler="/static/"} 0 -http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 1307.275 -http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 1858.632 -http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 3087.384 -http_request_duration_microseconds_sum{handler="prometheus"} 179886.5000000001 -http_request_duration_microseconds_count{handler="prometheus"} 119 -# HELP http_request_size_bytes The HTTP request sizes in bytes. -# TYPE http_request_size_bytes summary -http_request_size_bytes{handler="/",quantile="0.5"} 0 -http_request_size_bytes{handler="/",quantile="0.9"} 0 -http_request_size_bytes{handler="/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/"} 0 -http_request_size_bytes_count{handler="/"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_request_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/alerts"} 0 -http_request_size_bytes_count{handler="/alerts"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/metrics"} 0 -http_request_size_bytes_count{handler="/api/metrics"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query"} 0 -http_request_size_bytes_count{handler="/api/query"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/query_range"} 0 -http_request_size_bytes_count{handler="/api/query_range"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_request_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/api/targets"} 0 -http_request_size_bytes_count{handler="/api/targets"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_request_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/consoles/"} 0 -http_request_size_bytes_count{handler="/consoles/"} 0 -http_request_size_bytes{handler="/graph",quantile="0.5"} 0 -http_request_size_bytes{handler="/graph",quantile="0.9"} 0 -http_request_size_bytes{handler="/graph",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/graph"} 0 -http_request_size_bytes_count{handler="/graph"} 0 -http_request_size_bytes{handler="/heap",quantile="0.5"} 0 -http_request_size_bytes{handler="/heap",quantile="0.9"} 0 -http_request_size_bytes{handler="/heap",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/heap"} 0 -http_request_size_bytes_count{handler="/heap"} 0 -http_request_size_bytes{handler="/static/",quantile="0.5"} 0 -http_request_size_bytes{handler="/static/",quantile="0.9"} 0 -http_request_size_bytes{handler="/static/",quantile="0.99"} 0 -http_request_size_bytes_sum{handler="/static/"} 0 -http_request_size_bytes_count{handler="/static/"} 0 -http_request_size_bytes{handler="prometheus",quantile="0.5"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.9"} 291 -http_request_size_bytes{handler="prometheus",quantile="0.99"} 291 -http_request_size_bytes_sum{handler="prometheus"} 34488 -http_request_size_bytes_count{handler="prometheus"} 119 -# HELP http_requests_total Total number of HTTP requests made. -# TYPE http_requests_total counter -http_requests_total{code="200",handler="prometheus",method="get"} 119 -# HELP http_response_size_bytes The HTTP response sizes in bytes. -# TYPE http_response_size_bytes summary -http_response_size_bytes{handler="/",quantile="0.5"} 0 -http_response_size_bytes{handler="/",quantile="0.9"} 0 -http_response_size_bytes{handler="/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/"} 0 -http_response_size_bytes_count{handler="/"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.5"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.9"} 0 -http_response_size_bytes{handler="/alerts",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/alerts"} 0 -http_response_size_bytes_count{handler="/alerts"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/metrics",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/metrics"} 0 -http_response_size_bytes_count{handler="/api/metrics"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query"} 0 -http_response_size_bytes_count{handler="/api/query"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/query_range",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/query_range"} 0 -http_response_size_bytes_count{handler="/api/query_range"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.5"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.9"} 0 -http_response_size_bytes{handler="/api/targets",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/api/targets"} 0 -http_response_size_bytes_count{handler="/api/targets"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.5"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.9"} 0 -http_response_size_bytes{handler="/consoles/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/consoles/"} 0 -http_response_size_bytes_count{handler="/consoles/"} 0 -http_response_size_bytes{handler="/graph",quantile="0.5"} 0 -http_response_size_bytes{handler="/graph",quantile="0.9"} 0 -http_response_size_bytes{handler="/graph",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/graph"} 0 -http_response_size_bytes_count{handler="/graph"} 0 -http_response_size_bytes{handler="/heap",quantile="0.5"} 0 -http_response_size_bytes{handler="/heap",quantile="0.9"} 0 -http_response_size_bytes{handler="/heap",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/heap"} 0 -http_response_size_bytes_count{handler="/heap"} 0 -http_response_size_bytes{handler="/static/",quantile="0.5"} 0 -http_response_size_bytes{handler="/static/",quantile="0.9"} 0 -http_response_size_bytes{handler="/static/",quantile="0.99"} 0 -http_response_size_bytes_sum{handler="/static/"} 0 -http_response_size_bytes_count{handler="/static/"} 0 -http_response_size_bytes{handler="prometheus",quantile="0.5"} 2049 -http_response_size_bytes{handler="prometheus",quantile="0.9"} 2058 -http_response_size_bytes{handler="prometheus",quantile="0.99"} 2064 -http_response_size_bytes_sum{handler="prometheus"} 247001 -http_response_size_bytes_count{handler="prometheus"} 119 -# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. -# TYPE process_cpu_seconds_total counter -process_cpu_seconds_total 0.55 -# HELP go_goroutines Number of goroutines that currently exist. -# TYPE go_goroutines gauge -go_goroutines 70 -# HELP process_max_fds Maximum number of open file descriptors. -# TYPE process_max_fds gauge -process_max_fds 8192 -# HELP process_open_fds Number of open file descriptors. -# TYPE process_open_fds gauge -process_open_fds 29 -# HELP process_resident_memory_bytes Resident memory size in bytes. -# TYPE process_resident_memory_bytes gauge -process_resident_memory_bytes 5.3870592e+07 -# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. -# TYPE process_start_time_seconds gauge -process_start_time_seconds 1.42236894836e+09 -# HELP process_virtual_memory_bytes Virtual memory size in bytes. -# TYPE process_virtual_memory_bytes gauge -process_virtual_memory_bytes 5.41478912e+08 -# HELP prometheus_dns_sd_lookup_failures_total The number of DNS-SD lookup failures. -# TYPE prometheus_dns_sd_lookup_failures_total counter -prometheus_dns_sd_lookup_failures_total 0 -# HELP prometheus_dns_sd_lookups_total The number of DNS-SD lookups. -# TYPE prometheus_dns_sd_lookups_total counter -prometheus_dns_sd_lookups_total 7 -# HELP prometheus_evaluator_duration_milliseconds The duration for all evaluations to execute. -# TYPE prometheus_evaluator_duration_milliseconds summary -prometheus_evaluator_duration_milliseconds{quantile="0.01"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.05"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.5"} 0 -prometheus_evaluator_duration_milliseconds{quantile="0.9"} 1 -prometheus_evaluator_duration_milliseconds{quantile="0.99"} 1 -prometheus_evaluator_duration_milliseconds_sum 12 -prometheus_evaluator_duration_milliseconds_count 23 -# HELP prometheus_local_storage_checkpoint_duration_milliseconds The duration (in milliseconds) it took to checkpoint in-memory metrics and head chunks. -# TYPE prometheus_local_storage_checkpoint_duration_milliseconds gauge -prometheus_local_storage_checkpoint_duration_milliseconds 0 -# HELP prometheus_local_storage_chunk_ops_total The total number of chunk operations by their type. -# TYPE prometheus_local_storage_chunk_ops_total counter -prometheus_local_storage_chunk_ops_total{type="create"} 598 -prometheus_local_storage_chunk_ops_total{type="persist"} 174 -prometheus_local_storage_chunk_ops_total{type="pin"} 920 -prometheus_local_storage_chunk_ops_total{type="transcode"} 415 -prometheus_local_storage_chunk_ops_total{type="unpin"} 920 -# HELP prometheus_local_storage_indexing_batch_latency_milliseconds Quantiles for batch indexing latencies in milliseconds. -# TYPE prometheus_local_storage_indexing_batch_latency_milliseconds summary -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.5"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.9"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.99"} 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_sum 0 -prometheus_local_storage_indexing_batch_latency_milliseconds_count 1 -# HELP prometheus_local_storage_indexing_batch_sizes Quantiles for indexing batch sizes (number of metrics per batch). -# TYPE prometheus_local_storage_indexing_batch_sizes summary -prometheus_local_storage_indexing_batch_sizes{quantile="0.5"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.9"} 2 -prometheus_local_storage_indexing_batch_sizes{quantile="0.99"} 2 -prometheus_local_storage_indexing_batch_sizes_sum 2 -prometheus_local_storage_indexing_batch_sizes_count 1 -# HELP prometheus_local_storage_indexing_queue_capacity The capacity of the indexing queue. -# TYPE prometheus_local_storage_indexing_queue_capacity gauge -prometheus_local_storage_indexing_queue_capacity 16384 -# HELP prometheus_local_storage_indexing_queue_length The number of metrics waiting to be indexed. -# TYPE prometheus_local_storage_indexing_queue_length gauge -prometheus_local_storage_indexing_queue_length 0 -# HELP prometheus_local_storage_ingested_samples_total The total number of samples ingested. -# TYPE prometheus_local_storage_ingested_samples_total counter -prometheus_local_storage_ingested_samples_total 30473 -# HELP prometheus_local_storage_invalid_preload_requests_total The total number of preload requests referring to a non-existent series. This is an indication of outdated label indexes. -# TYPE prometheus_local_storage_invalid_preload_requests_total counter -prometheus_local_storage_invalid_preload_requests_total 0 -# HELP prometheus_local_storage_memory_chunkdescs The current number of chunk descriptors in memory. -# TYPE prometheus_local_storage_memory_chunkdescs gauge -prometheus_local_storage_memory_chunkdescs 1059 -# HELP prometheus_local_storage_memory_chunks The current number of chunks in memory, excluding cloned chunks (i.e. chunks without a descriptor). -# TYPE prometheus_local_storage_memory_chunks gauge -prometheus_local_storage_memory_chunks 1020 -# HELP prometheus_local_storage_memory_series The current number of series in memory. -# TYPE prometheus_local_storage_memory_series gauge -prometheus_local_storage_memory_series 424 -# HELP prometheus_local_storage_persist_latency_microseconds A summary of latencies for persisting each chunk. -# TYPE prometheus_local_storage_persist_latency_microseconds summary -prometheus_local_storage_persist_latency_microseconds{quantile="0.5"} 30.377 -prometheus_local_storage_persist_latency_microseconds{quantile="0.9"} 203.539 -prometheus_local_storage_persist_latency_microseconds{quantile="0.99"} 2626.463 -prometheus_local_storage_persist_latency_microseconds_sum 20424.415 -prometheus_local_storage_persist_latency_microseconds_count 174 -# HELP prometheus_local_storage_persist_queue_capacity The total capacity of the persist queue. -# TYPE prometheus_local_storage_persist_queue_capacity gauge -prometheus_local_storage_persist_queue_capacity 1024 -# HELP prometheus_local_storage_persist_queue_length The current number of chunks waiting in the persist queue. -# TYPE prometheus_local_storage_persist_queue_length gauge -prometheus_local_storage_persist_queue_length 0 -# HELP prometheus_local_storage_series_ops_total The total number of series operations by their type. -# TYPE prometheus_local_storage_series_ops_total counter -prometheus_local_storage_series_ops_total{type="create"} 2 -prometheus_local_storage_series_ops_total{type="maintenance_in_memory"} 11 -# HELP prometheus_notifications_latency_milliseconds Latency quantiles for sending alert notifications (not including dropped notifications). -# TYPE prometheus_notifications_latency_milliseconds summary -prometheus_notifications_latency_milliseconds{quantile="0.5"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.9"} 0 -prometheus_notifications_latency_milliseconds{quantile="0.99"} 0 -prometheus_notifications_latency_milliseconds_sum 0 -prometheus_notifications_latency_milliseconds_count 0 -# HELP prometheus_notifications_queue_capacity The capacity of the alert notifications queue. -# TYPE prometheus_notifications_queue_capacity gauge -prometheus_notifications_queue_capacity 100 -# HELP prometheus_notifications_queue_length The number of alert notifications in the queue. -# TYPE prometheus_notifications_queue_length gauge -prometheus_notifications_queue_length 0 -# HELP prometheus_rule_evaluation_duration_milliseconds The duration for a rule to execute. -# TYPE prometheus_rule_evaluation_duration_milliseconds summary -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.99"} 2 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="alerting"} 12 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="alerting"} 115 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.5"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.9"} 0 -prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.99"} 3 -prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="recording"} 15 -prometheus_rule_evaluation_duration_milliseconds_count{rule_type="recording"} 115 -# HELP prometheus_rule_evaluation_failures_total The total number of rule evaluation failures. -# TYPE prometheus_rule_evaluation_failures_total counter -prometheus_rule_evaluation_failures_total 0 -# HELP prometheus_samples_queue_capacity Capacity of the queue for unwritten samples. -# TYPE prometheus_samples_queue_capacity gauge -prometheus_samples_queue_capacity 4096 -# HELP prometheus_samples_queue_length Current number of items in the queue for unwritten samples. Each item comprises all samples exposed by one target as one metric family (i.e. metrics of the same name). -# TYPE prometheus_samples_queue_length gauge -prometheus_samples_queue_length 0 -# HELP prometheus_target_interval_length_seconds Actual intervals between scrapes. -# TYPE prometheus_target_interval_length_seconds summary -prometheus_target_interval_length_seconds{interval="15s",quantile="0.01"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.05"} 14 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.5"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.9"} 15 -prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15 -prometheus_target_interval_length_seconds_sum{interval="15s"} 175 -prometheus_target_interval_length_seconds_count{interval="15s"} 12 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.01"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.05"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.5"} 0 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.9"} 1 -prometheus_target_interval_length_seconds{interval="1s",quantile="0.99"} 1 -prometheus_target_interval_length_seconds_sum{interval="1s"} 55 -prometheus_target_interval_length_seconds_count{interval="1s"} 117 diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go deleted file mode 100644 index e4cc5d803bb..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_create_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "bytes" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" -) - -func testCreate(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - out string - }{ - // 0: Counter, NaN as value, timestamp given. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - out: `# HELP name two-line\n doc str\\ing -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name{labelname="val2",basename="basevalue"} 0.23 1234567890 -`, - }, - // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. - { - in: &dto.MetricFamily{ - Name: proto.String("gauge_name"), - Help: proto.String("gauge\ndoc\nstr\"ing"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("val with\nnew line"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("val with \\backslash and \"quotes\""), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("Björn"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("佖佥"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14E42), - }, - }, - }, - }, - out: `# HELP gauge_name gauge\ndoc\nstr"ing -# TYPE gauge_name gauge -gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf -gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 -`, - }, - // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. - { - in: &dto.MetricFamily{ - Name: proto.String("untyped_name"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(-1.23e-45), - }, - }, - }, - }, - out: `# TYPE untyped_name untyped -untyped_name -Inf -untyped_name{name_1="value 1"} -1.23e-45 -`, - }, - // 3: Summary. - { - in: &dto.MetricFamily{ - Name: proto.String("summary_name"), - Help: proto.String("summary docstring"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(-3.4567), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(-1.23), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(.2342354), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(0), - }, - }, - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("value 2"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(4711), - SampleSum: proto.Float64(2010.1971), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(1), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(2), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - out: `# HELP summary_name summary docstring -# TYPE summary_name summary -summary_name{quantile="0.5"} -1.23 -summary_name{quantile="0.9"} 0.2342354 -summary_name{quantile="0.99"} 0 -summary_name_sum -3.4567 -summary_name_count 42 -summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 -summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 -summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 -summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 -summary_name_count{name_1="value 1",name_2="value 2"} 4711 -`, - }, - // 4: Histogram - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 5: Histogram with missing +Inf bucket. - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 6: No metric type, should result in default type Counter. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - out: `# HELP name doc string -# TYPE name counter -name -Inf -`, - }, - } - - for i, scenario := range scenarios { - out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) - n, err := MetricFamilyToText(out, scenario.in) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), n; expected != got { - t.Errorf( - "%d. expected %d bytes written, got %d", - i, expected, got, - ) - } - if expected, got := scenario.out, out.String(); expected != got { - t.Errorf( - "%d. expected out=%q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreate(t *testing.T) { - testCreate(t) -} - -func BenchmarkCreate(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreate(b) - } -} - -func testCreateError(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - err string - }{ - // 0: No metric. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{}, - }, - err: "MetricFamily has no metrics", - }, - // 1: No metric name. - { - in: &dto.MetricFamily{ - Help: proto.String("doc string"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "MetricFamily has no name", - }, - // 2: Wrong type. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "expected counter in metric", - }, - } - - for i, scenario := range scenarios { - var out bytes.Buffer - _, err := MetricFamilyToText(&out, scenario.in) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreateError(t *testing.T) { - testCreateError(t) -} - -func BenchmarkCreateError(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreateError(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go b/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go deleted file mode 100644 index 589c87a9d5f..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/expfmt/text_parse_test.go +++ /dev/null @@ -1,586 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package expfmt - -import ( - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func testTextParse(t testing.TB) { - var scenarios = []struct { - in string - out []*dto.MetricFamily - }{ - // 0: Empty lines as input. - { - in: ` - -`, - out: []*dto.MetricFamily{}, - }, - // 1: Minimal case. - { - in: ` -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("minimal_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(1.234), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-3e3), - }, - TimestampMs: proto.Int64(103948), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("no_labels"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - // 2: Counters & gauges, docstrings, various whitespace, escape sequences. - { - in: ` -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("base\"v\\al\nue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("name2"), - Help: proto.String("doc str\"ing 2"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue2"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - TimestampMs: proto.Int64(54321), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - }, - }, - // 3: The evil summary, mixed with other types and funny comments. - { - in: ` -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("fake_sum"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(2001), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("decoy"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-1), - }, - TimestampMs: proto.Int64(-2), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("my_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(4711), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(110), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(140), - }, - }, - }, - TimestampMs: proto.Int64(2), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(5), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(-12.34), - Value: proto.Float64(math.NaN()), - }, - }, - }, - TimestampMs: proto.Int64(5), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val2"), - }, - }, - Summary: &dto.Summary{ - SampleSum: proto.Float64(8), - }, - TimestampMs: proto.Int64(15), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val3"), - }, - }, - Summary: &dto.Summary{ - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.2), - Value: proto.Float64(4711), - }, - }, - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(20), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.3), - Value: proto.Float64(-1.2), - }, - }, - }, - }, - }, - }, - }, - }, - // 4: The histogram. - { - in: ` -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - out: []*dto.MetricFamily{ - { - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - }, - }, - } - - for i, scenario := range scenarios { - out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), len(out); expected != got { - t.Errorf( - "%d. expected %d MetricFamilies, got %d", - i, expected, got, - ) - } - for _, expected := range scenario.out { - got, ok := out[expected.GetName()] - if !ok { - t.Errorf( - "%d. expected MetricFamily %q, found none", - i, expected.GetName(), - ) - continue - } - if expected.String() != got.String() { - t.Errorf( - "%d. expected MetricFamily %s, got %s", - i, expected, got, - ) - } - } - } -} - -func TestTextParse(t *testing.T) { - testTextParse(t) -} - -func BenchmarkTextParse(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParse(b) - } -} - -func testTextParseError(t testing.TB) { - var scenarios = []struct { - in string - err string - }{ - // 0: No new-line at end of input. - { - in: `bla 3.14`, - err: "EOF", - }, - // 1: Invalid escape sequence in label value. - { - in: `metric{label="\t"} 3.14`, - err: "text format parsing error in line 1: invalid escape sequence", - }, - // 2: Newline in label value. - { - in: ` -metric{label="new -line"} 3.14 -`, - err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, - }, - // 3: - { - in: `metric{@="bla"} 3.14`, - err: "text format parsing error in line 1: invalid label name for metric", - }, - // 4: - { - in: `metric{__name__="bla"} 3.14`, - err: `text format parsing error in line 1: label name "__name__" is reserved`, - }, - // 5: - { - in: `metric{label+="bla"} 3.14`, - err: "text format parsing error in line 1: expected '=' after label name", - }, - // 6: - { - in: `metric{label=bla} 3.14`, - err: "text format parsing error in line 1: expected '\"' at start of label value", - }, - // 7: - { - in: ` -# TYPE metric summary -metric{quantile="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'quantile' label", - }, - // 8: - { - in: `metric{label="bla"+} 3.14`, - err: "text format parsing error in line 1: unexpected end of label value", - }, - // 9: - { - in: `metric{label="bla"} 3.14 2.72 -`, - err: "text format parsing error in line 1: expected integer as timestamp", - }, - // 10: - { - in: `metric{label="bla"} 3.14 2 3 -`, - err: "text format parsing error in line 1: spurious string after timestamp", - }, - // 11: - { - in: `metric{label="bla"} blubb -`, - err: "text format parsing error in line 1: expected float as value", - }, - // 12: - { - in: ` -# HELP metric one -# HELP metric two -`, - err: "text format parsing error in line 3: second HELP line for metric name", - }, - // 13: - { - in: ` -# TYPE metric counter -# TYPE metric untyped -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -metric 4.12 -# TYPE metric counter -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -# TYPE metric bla -`, - err: "text format parsing error in line 2: unknown metric type", - }, - // 15: - { - in: ` -# TYPE met-ric -`, - err: "text format parsing error in line 2: invalid metric name in comment", - }, - // 16: - { - in: `@invalidmetric{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 17: - { - in: `{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 18: - { - in: ` -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'le' label", - }, - } - - for i, scenario := range scenarios { - _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestTextParseError(t *testing.T) { - testTextParseError(t) -} - -func BenchmarkParseError(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParseError(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go deleted file mode 100644 index ab17025c76a..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/labels_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "sort" - "testing" -) - -func testLabelNames(t testing.TB) { - var scenarios = []struct { - in LabelNames - out LabelNames - }{ - { - in: LabelNames{"ZZZ", "zzz"}, - out: LabelNames{"ZZZ", "zzz"}, - }, - { - in: LabelNames{"aaa", "AAA"}, - out: LabelNames{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelNames(t *testing.T) { - testLabelNames(t) -} - -func BenchmarkLabelNames(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelNames(b) - } -} - -func testLabelValues(t testing.TB) { - var scenarios = []struct { - in LabelValues - out LabelValues - }{ - { - in: LabelValues{"ZZZ", "zzz"}, - out: LabelValues{"ZZZ", "zzz"}, - }, - { - in: LabelValues{"aaa", "AAA"}, - out: LabelValues{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelValues(t *testing.T) { - testLabelValues(t) -} - -func BenchmarkLabelValues(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelValues(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go deleted file mode 100644 index 5c7cfceafe9..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/metric_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import "testing" - -func testMetric(t testing.TB) { - var scenarios = []struct { - input LabelSet - fingerprint Fingerprint - fastFingerprint Fingerprint - }{ - { - input: LabelSet{}, - fingerprint: 14695981039346656037, - fastFingerprint: 14695981039346656037, - }, - { - input: LabelSet{ - "first_name": "electro", - "occupation": "robot", - "manufacturer": "westinghouse", - }, - fingerprint: 5911716720268894962, - fastFingerprint: 11310079640881077873, - }, - { - input: LabelSet{ - "x": "y", - }, - fingerprint: 8241431561484471700, - fastFingerprint: 13948396922932177635, - }, - { - input: LabelSet{ - "a": "bb", - "b": "c", - }, - fingerprint: 3016285359649981711, - fastFingerprint: 3198632812309449502, - }, - { - input: LabelSet{ - "a": "b", - "bb": "c", - }, - fingerprint: 7122421792099404749, - fastFingerprint: 5774953389407657638, - }, - } - - for i, scenario := range scenarios { - input := Metric(scenario.input) - - if scenario.fingerprint != input.Fingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) - } - if scenario.fastFingerprint != input.FastFingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) - } - } -} - -func TestMetric(t *testing.T) { - testMetric(t) -} - -func BenchmarkMetric(b *testing.B) { - for i := 0; i < b.N; i++ { - testMetric(b) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go deleted file mode 100644 index d9c665f8c79..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/signature_test.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "runtime" - "sync" - "testing" -) - -func TestLabelsToSignature(t *testing.T) { - var scenarios = []struct { - in map[string]string - out uint64 - }{ - { - in: map[string]string{}, - out: 14695981039346656037, - }, - { - in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := LabelsToSignature(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFastFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 12952432476264840823, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFastFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureForLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels LabelNames - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 14695981039346656037, - }, - } - - for i, scenario := range scenarios { - actual := SignatureForLabels(scenario.in, scenario.labels...) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureWithoutLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels map[LabelName]struct{} - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: map[LabelName]struct{}{"foo": struct{}{}}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := SignatureWithoutLabels(scenario.in, scenario.labels) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { - for i := 0; i < b.N; i++ { - if a := LabelsToSignature(l); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, l, a) - } - } -} - -func BenchmarkLabelToSignatureScalar(b *testing.B) { - benchmarkLabelToSignature(b, nil, 14695981039346656037) -} - -func BenchmarkLabelToSignatureSingle(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkLabelToSignatureDouble(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkLabelToSignatureTriple(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFingerprintScalar(b *testing.B) { - benchmarkMetricToFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFingerprintSingle(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkMetricToFingerprintDouble(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkMetricToFingerprintTriple(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { - benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) -} - -func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) -} - -func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) -} - -func BenchmarkEmptyLabelSignature(b *testing.B) { - input := []map[string]string{nil, {}} - - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - - alloc := ms.Alloc - - for _, labels := range input { - LabelsToSignature(labels) - } - - runtime.ReadMemStats(&ms) - - if got := ms.Alloc; alloc != got { - b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") - } -} - -func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - for i := 0; i < concLevel; i++ { - go func() { - start.Wait() - for j := b.N / concLevel; j >= 0; j-- { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } - end.Done() - }() - } - b.ResetTimer() - start.Done() - end.Wait() -} - -func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) -} - -func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) -} - -func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) -} - -func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go deleted file mode 100644 index 9013a62775b..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/time_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "testing" - "time" -) - -func TestComparators(t *testing.T) { - t1a := TimeFromUnix(0) - t1b := TimeFromUnix(0) - t2 := TimeFromUnix(2*second - 1) - - if !t1a.Equal(t1b) { - t.Fatalf("Expected %s to be equal to %s", t1a, t1b) - } - if t1a.Equal(t2) { - t.Fatalf("Expected %s to not be equal to %s", t1a, t2) - } - - if !t1a.Before(t2) { - t.Fatalf("Expected %s to be before %s", t1a, t2) - } - if t1a.Before(t1b) { - t.Fatalf("Expected %s to not be before %s", t1a, t1b) - } - - if !t2.After(t1a) { - t.Fatalf("Expected %s to be after %s", t2, t1a) - } - if t1b.After(t1a) { - t.Fatalf("Expected %s to not be after %s", t1b, t1a) - } -} - -func TestTimeConversions(t *testing.T) { - unixSecs := int64(1136239445) - unixNsecs := int64(123456789) - unixNano := unixSecs*1e9 + unixNsecs - - t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) - t2 := time.Unix(unixSecs, unixNsecs) - - ts := TimeFromUnixNano(unixNano) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - // Test available precision. - ts = TimeFromUnixNano(t2.UnixNano()) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - if ts.UnixNano() != unixNano-unixNano%nanosPerTick { - t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) - } -} - -func TestDuration(t *testing.T) { - duration := time.Second + time.Minute + time.Hour - goTime := time.Unix(1136239445, 0) - - ts := TimeFromUnix(goTime.Unix()) - if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { - t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) - } - - earlier := ts.Add(-duration) - delta := ts.Sub(earlier) - if delta != duration { - t.Fatalf("Expected %s to be equal to %s", delta, duration) - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go b/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go deleted file mode 100644 index 2e9c7eb09d1..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/common/model/value_test.go +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2013 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package model - -import ( - "encoding/json" - "math" - "reflect" - "sort" - "testing" -) - -func TestSamplePairJSON(t *testing.T) { - input := []struct { - plain string - value SamplePair - }{ - { - plain: `[1234.567,"123.1"]`, - value: SamplePair{ - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sp SamplePair - err = json.Unmarshal(b, &sp) - if err != nil { - t.Error(err) - continue - } - - if sp != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sp) - } - } -} - -func TestSampleJSON(t *testing.T) { - input := []struct { - plain string - value Sample - }{ - { - plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, - value: Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Sample - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(sv, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorJSON(t *testing.T) { - input := []struct { - plain string - value Vector - }{ - { - plain: `[]`, - value: Vector{}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, - value: Vector{&Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, - value: Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - &Sample{ - Metric: Metric{ - "foo": "bar", - }, - Value: SampleValue(math.Inf(1)), - Timestamp: 1234, - }, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var vec Vector - err = json.Unmarshal(b, &vec) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(vec, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, vec) - } - } -} - -func TestScalarJSON(t *testing.T) { - input := []struct { - plain string - value Scalar - }{ - { - plain: `[123.456,"456"]`, - value: Scalar{ - Timestamp: 123456, - Value: 456, - }, - }, - { - plain: `[123123.456,"+Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(1)), - }, - }, - { - plain: `[123123.456,"-Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(-1)), - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Scalar - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestStringJSON(t *testing.T) { - input := []struct { - plain string - value String - }{ - { - plain: `[123.456,"test"]`, - value: String{ - Timestamp: 123456, - Value: "test", - }, - }, - { - plain: `[123123.456,"台北"]`, - value: String{ - Timestamp: 123123456, - Value: "台北", - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv String - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorSort(t *testing.T) { - input := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - } - - expected := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - } - - sort.Sort(input) - - for i, actual := range input { - actualFp := actual.Metric.Fingerprint() - expectedFp := expected[i].Metric.Fingerprint() - - if actualFp != expectedFp { - t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) - } - - if actual.Timestamp != expected[i].Timestamp { - t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go deleted file mode 100644 index 91f1c6c9763..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/fs_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package procfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("procfs.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go deleted file mode 100644 index ca7a254da75..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_limits_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package procfs - -import "testing" - -func TestNewLimits(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - l, err := p.NewLimits() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "cpu time", want: -1, got: l.CPUTime}, - {name: "open files", want: 2048, got: l.OpenFiles}, - {name: "msgqueue size", want: 819200, got: l.MsqqueueSize}, - {name: "nice priority", want: 0, got: l.NicePriority}, - {name: "address space", want: -1, got: l.AddressSpace}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go deleted file mode 100644 index e4d5cacfa4b..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_stat_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package procfs - -import "testing" - -func TestProcStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - p, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "pid", want: 26231, got: s.PID}, - {name: "user time", want: 1677, got: int(s.UTime)}, - {name: "system time", want: 44, got: int(s.STime)}, - {name: "start time", want: 82375, got: int(s.Starttime)}, - {name: "virtual memory size", want: 56274944, got: s.VSize}, - {name: "resident set size", want: 1981, got: s.RSS}, - } { - if test.want != test.got { - t.Errorf("want %s %d, got %d", test.name, test.want, test.got) - } - } -} - -func TestProcStatComm(t *testing.T) { - s1, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - if want, got := "vim", s1.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } - - s2, err := testProcStat(584) - if err != nil { - t.Fatal(err) - } - if want, got := "(a b ) ( c d) ", s2.Comm; want != got { - t.Errorf("want comm %s, got %s", want, got) - } -} - -func TestProcStatVirtualMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 56274944, s.VirtualMemory(); want != got { - t.Errorf("want virtual memory %d, got %d", want, got) - } -} - -func TestProcStatResidentMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 1981*4096, s.ResidentMemory(); want != got { - t.Errorf("want resident memory %d, got %d", want, got) - } -} - -func TestProcStatStartTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - time, err := s.StartTime() - if err != nil { - t.Fatal(err) - } - if want, got := 1418184099.75, time; want != got { - t.Errorf("want start time %f, got %f", want, got) - } -} - -func TestProcStatCPUTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, got := 17.21, s.CPUTime(); want != got { - t.Errorf("want cpu time %f, got %f", want, got) - } -} - -func testProcStat(pid int) (ProcStat, error) { - p, err := testProcess(pid) - if err != nil { - return ProcStat{}, err - } - - return p.NewStat() -} diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go deleted file mode 100644 index bd234a14cb3..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/proc_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package procfs - -import ( - "os" - "reflect" - "sort" - "testing" -) - -func TestSelf(t *testing.T) { - p1, err := NewProc(os.Getpid()) - if err != nil { - t.Fatal(err) - } - p2, err := Self() - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(p1, p2) { - t.Errorf("want process %v to equal %v", p1, p2) - } -} - -func TestAllProcs(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - procs, err := fs.AllProcs() - if err != nil { - t.Fatal(err) - } - sort.Sort(procs) - for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { - if want, got := p.PID, procs[i].PID; want != got { - t.Errorf("want processes %d, got %d", want, got) - } - } -} - -func TestCmdLine(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - c, err := p1.CmdLine() - if err != nil { - t.Fatal(err) - } - if want := []string{"vim", "test.go", "+10"}; !reflect.DeepEqual(want, c) { - t.Errorf("want cmdline %v, got %v", want, c) - } -} - -func TestFileDescriptors(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptors() - if err != nil { - t.Fatal(err) - } - sort.Sort(byUintptr(fds)) - if want := []uintptr{0, 1, 2, 3, 4}; !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, got %v", want, fds) - } - - p2, err := Self() - if err != nil { - t.Fatal(err) - } - - fdsBefore, err := p2.FileDescriptors() - if err != nil { - t.Fatal(err) - } - - s, err := os.Open("fixtures") - if err != nil { - t.Fatal(err) - } - defer s.Close() - - fdsAfter, err := p2.FileDescriptors() - if err != nil { - t.Fatal(err) - } - - if len(fdsBefore)+1 != len(fdsAfter) { - t.Errorf("want fds %v+1 to equal %v", fdsBefore, fdsAfter) - } -} - -func TestFileDescriptorsLen(t *testing.T) { - p1, err := testProcess(26231) - if err != nil { - t.Fatal(err) - } - l, err := p1.FileDescriptorsLen() - if err != nil { - t.Fatal(err) - } - if want, got := 5, l; want != got { - t.Errorf("want fds %d, got %d", want, got) - } -} - -func testProcess(pid int) (Proc, error) { - fs, err := NewFS("fixtures") - if err != nil { - return Proc{}, err - } - - return fs.NewProc(pid) -} - -type byUintptr []uintptr - -func (a byUintptr) Len() int { return len(a) } -func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } diff --git a/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go b/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go deleted file mode 100644 index 24b5d61f8e9..00000000000 --- a/Godeps/_workspace/src/github.com/prometheus/procfs/stat_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package procfs - -import "testing" - -func TestStat(t *testing.T) { - fs, err := NewFS("fixtures") - if err != nil { - t.Fatal(err) - } - - s, err := fs.NewStat() - if err != nil { - t.Fatal(err) - } - - if want, got := int64(1418183276), s.BootTime; want != got { - t.Errorf("want boot time %d, got %d", want, got) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/snapshots_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/snapshots_test.go deleted file mode 100644 index 7741aa98416..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/snapshots_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots" - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSnapshots(t *testing.T) { - - client, err := newClient(t) - th.AssertNoErr(t, err) - - v, err := volumes.Create(client, &volumes.CreateOpts{ - Name: "gophercloud-test-volume", - Size: 1, - }).Extract() - th.AssertNoErr(t, err) - - err = volumes.WaitForStatus(client, v.ID, "available", 120) - th.AssertNoErr(t, err) - - t.Logf("Created volume: %v\n", v) - - ss, err := snapshots.Create(client, &snapshots.CreateOpts{ - Name: "gophercloud-test-snapshot", - VolumeID: v.ID, - }).Extract() - th.AssertNoErr(t, err) - - err = snapshots.WaitForStatus(client, ss.ID, "available", 120) - th.AssertNoErr(t, err) - - t.Logf("Created snapshot: %+v\n", ss) - - err = snapshots.Delete(client, ss.ID).ExtractErr() - th.AssertNoErr(t, err) - - err = gophercloud.WaitFor(120, func() (bool, error) { - _, err := snapshots.Get(client, ss.ID).Extract() - if err != nil { - return true, nil - } - - return false, nil - }) - th.AssertNoErr(t, err) - - t.Log("Deleted snapshot\n") - - err = volumes.Delete(client, v.ID).ExtractErr() - th.AssertNoErr(t, err) - - err = gophercloud.WaitFor(120, func() (bool, error) { - _, err := volumes.Get(client, v.ID).Extract() - if err != nil { - return true, nil - } - - return false, nil - }) - th.AssertNoErr(t, err) - - t.Log("Deleted volume\n") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumes_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumes_test.go deleted file mode 100644 index 7760427f08c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumes_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// +build acceptance blockstorage - -package v1 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func newClient(t *testing.T) (*gophercloud.ServiceClient, error) { - ao, err := openstack.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - client, err := openstack.AuthenticatedClient(ao) - th.AssertNoErr(t, err) - - return openstack.NewBlockStorageV1(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -} - -func TestVolumes(t *testing.T) { - client, err := newClient(t) - th.AssertNoErr(t, err) - - cv, err := volumes.Create(client, &volumes.CreateOpts{ - Size: 1, - Name: "gophercloud-test-volume", - }).Extract() - th.AssertNoErr(t, err) - defer func() { - err = volumes.WaitForStatus(client, cv.ID, "available", 60) - th.AssertNoErr(t, err) - err = volumes.Delete(client, cv.ID).ExtractErr() - th.AssertNoErr(t, err) - }() - - _, err = volumes.Update(client, cv.ID, &volumes.UpdateOpts{ - Name: "gophercloud-updated-volume", - }).Extract() - th.AssertNoErr(t, err) - - v, err := volumes.Get(client, cv.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Got volume: %+v\n", v) - - if v.Name != "gophercloud-updated-volume" { - t.Errorf("Unable to update volume: Expected name: gophercloud-updated-volume\nActual name: %s", v.Name) - } - - err = volumes.List(client, &volumes.ListOpts{Name: "gophercloud-updated-volume"}).EachPage(func(page pagination.Page) (bool, error) { - vols, err := volumes.ExtractVolumes(page) - th.CheckEquals(t, 1, len(vols)) - return true, err - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumetypes_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumetypes_test.go deleted file mode 100644 index 000bc01d575..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/blockstorage/v1/volumetypes_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - "time" - - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestVolumeTypes(t *testing.T) { - client, err := newClient(t) - th.AssertNoErr(t, err) - - vt, err := volumetypes.Create(client, &volumetypes.CreateOpts{ - ExtraSpecs: map[string]interface{}{ - "capabilities": "gpu", - "priority": 3, - }, - Name: "gophercloud-test-volumeType", - }).Extract() - th.AssertNoErr(t, err) - defer func() { - time.Sleep(10000 * time.Millisecond) - err = volumetypes.Delete(client, vt.ID).ExtractErr() - if err != nil { - t.Error(err) - return - } - }() - t.Logf("Created volume type: %+v\n", vt) - - vt, err = volumetypes.Get(client, vt.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Got volume type: %+v\n", vt) - - err = volumetypes.List(client).EachPage(func(page pagination.Page) (bool, error) { - volTypes, err := volumetypes.ExtractVolumeTypes(page) - if len(volTypes) != 1 { - t.Errorf("Expected 1 volume type, got %d", len(volTypes)) - } - t.Logf("Listing volume types: %+v\n", volTypes) - return true, err - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/client_test.go deleted file mode 100644 index 6e88819d80e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/client_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build acceptance - -package openstack - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" -) - -func TestAuthenticatedClient(t *testing.T) { - // Obtain credentials from the environment. - ao, err := openstack.AuthOptionsFromEnv() - if err != nil { - t.Fatalf("Unable to acquire credentials: %v", err) - } - - client, err := openstack.AuthenticatedClient(ao) - if err != nil { - t.Fatalf("Unable to authenticate: %v", err) - } - - if client.TokenID == "" { - t.Errorf("No token ID assigned to the client") - } - - t.Logf("Client successfully acquired a token: %v", client.TokenID) - - // Find the storage service in the service catalog. - storage, err := openstack.NewObjectStorageV1(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) - if err != nil { - t.Errorf("Unable to locate a storage service: %v", err) - } else { - t.Logf("Located a storage service at endpoint: [%s]", storage.Endpoint) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/bootfromvolume_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/bootfromvolume_test.go deleted file mode 100644 index add0e5fc11e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/bootfromvolume_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBootFromVolume(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - name := tools.RandomString("Gophercloud-", 8) - t.Logf("Creating server [%s].", name) - - bd := []bootfromvolume.BlockDevice{ - bootfromvolume.BlockDevice{ - UUID: choices.ImageID, - SourceType: bootfromvolume.Image, - VolumeSize: 10, - }, - } - - serverCreateOpts := servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - } - server, err := bootfromvolume.Create(client, bootfromvolume.CreateOptsExt{ - serverCreateOpts, - bd, - }).Extract() - th.AssertNoErr(t, err) - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - t.Logf("Created server: %+v\n", server) - defer servers.Delete(client, server.ID) - t.Logf("Deleting server [%s]...", name) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/compute_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/compute_test.go deleted file mode 100644 index c1bbf7961f4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/compute_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// +build acceptance common - -package v2 - -import ( - "fmt" - "os" - "strings" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" -) - -func newClient() (*gophercloud.ServiceClient, error) { - ao, err := openstack.AuthOptionsFromEnv() - if err != nil { - return nil, err - } - - client, err := openstack.AuthenticatedClient(ao) - if err != nil { - return nil, err - } - - return openstack.NewComputeV2(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -} - -func waitForStatus(client *gophercloud.ServiceClient, server *servers.Server, status string) error { - return tools.WaitFor(func() (bool, error) { - latest, err := servers.Get(client, server.ID).Extract() - if err != nil { - return false, err - } - - if latest.Status == status { - // Success! - return true, nil - } - - return false, nil - }) -} - -// ComputeChoices contains image and flavor selections for use by the acceptance tests. -type ComputeChoices struct { - // ImageID contains the ID of a valid image. - ImageID string - - // FlavorID contains the ID of a valid flavor. - FlavorID string - - // FlavorIDResize contains the ID of a different flavor available on the same OpenStack installation, that is distinct - // from FlavorID. - FlavorIDResize string - - // NetworkName is the name of a network to launch the instance on. - NetworkName string -} - -// ComputeChoicesFromEnv populates a ComputeChoices struct from environment variables. -// If any required state is missing, an `error` will be returned that enumerates the missing properties. -func ComputeChoicesFromEnv() (*ComputeChoices, error) { - imageID := os.Getenv("OS_IMAGE_ID") - flavorID := os.Getenv("OS_FLAVOR_ID") - flavorIDResize := os.Getenv("OS_FLAVOR_ID_RESIZE") - networkName := os.Getenv("OS_NETWORK_NAME") - - missing := make([]string, 0, 3) - if imageID == "" { - missing = append(missing, "OS_IMAGE_ID") - } - if flavorID == "" { - missing = append(missing, "OS_FLAVOR_ID") - } - if flavorIDResize == "" { - missing = append(missing, "OS_FLAVOR_ID_RESIZE") - } - if networkName == "" { - networkName = "public" - } - - notDistinct := "" - if flavorID == flavorIDResize { - notDistinct = "OS_FLAVOR_ID and OS_FLAVOR_ID_RESIZE must be distinct." - } - - if len(missing) > 0 || notDistinct != "" { - text := "You're missing some important setup:\n" - if len(missing) > 0 { - text += " * These environment variables must be provided: " + strings.Join(missing, ", ") + "\n" - } - if notDistinct != "" { - text += " * " + notDistinct + "\n" - } - - return nil, fmt.Errorf(text) - } - - return &ComputeChoices{ImageID: imageID, FlavorID: flavorID, FlavorIDResize: flavorIDResize, NetworkName: networkName}, nil -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/extension_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/extension_test.go deleted file mode 100644 index 1356ffa8998..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/extension_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build acceptance compute extensionss - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListExtensions(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - err = extensions.List(client).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - exts, err := extensions.ExtractExtensions(page) - th.AssertNoErr(t, err) - - for i, ext := range exts { - t.Logf("[%02d] name=[%s]\n", i, ext.Name) - t.Logf(" alias=[%s]\n", ext.Alias) - t.Logf(" description=[%s]\n", ext.Description) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func TestGetExtension(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - ext, err := extensions.Get(client, "os-admin-actions").Extract() - th.AssertNoErr(t, err) - - t.Logf("Extension details:") - t.Logf(" name=[%s]\n", ext.Name) - t.Logf(" namespace=[%s]\n", ext.Namespace) - t.Logf(" alias=[%s]\n", ext.Alias) - t.Logf(" description=[%s]\n", ext.Description) - t.Logf(" updated=[%s]\n", ext.Updated) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/flavors_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/flavors_test.go deleted file mode 100644 index 9f51b12280b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/flavors_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// +build acceptance compute flavors - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/flavors" - "github.com/rackspace/gophercloud/pagination" -) - -func TestListFlavors(t *testing.T) { - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - t.Logf("ID\tRegion\tName\tStatus\tCreated") - - pager := flavors.ListDetail(client, nil) - count, pages := 0, 0 - pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("---") - pages++ - flavors, err := flavors.ExtractFlavors(page) - if err != nil { - return false, err - } - - for _, f := range flavors { - t.Logf("%s\t%s\t%d\t%d\t%d", f.ID, f.Name, f.RAM, f.Disk, f.VCPUs) - } - - return true, nil - }) - - t.Logf("--------\n%d flavors listed on %d pages.", count, pages) -} - -func TestGetFlavor(t *testing.T) { - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - flavor, err := flavors.Get(client, choices.FlavorID).Extract() - if err != nil { - t.Fatalf("Unable to get flavor information: %v", err) - } - - t.Logf("Flavor: %#v", flavor) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/floatingip_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/floatingip_test.go deleted file mode 100644 index ab7554b5a88..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/floatingip_test.go +++ /dev/null @@ -1,107 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func createFIPServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices) (*servers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - server, err := servers.Create(client, servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - AdminPass: pwd, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func createFloatingIP(t *testing.T, client *gophercloud.ServiceClient) (*floatingip.FloatingIP, error) { - pool := os.Getenv("OS_POOL_NAME") - fip, err := floatingip.Create(client, &floatingip.CreateOpts{ - Pool: pool, - }).Extract() - th.AssertNoErr(t, err) - t.Logf("Obtained Floating IP: %v", fip.IP) - - return fip, err -} - -func associateFloatingIP(t *testing.T, client *gophercloud.ServiceClient, serverId string, fip *floatingip.FloatingIP) { - err := floatingip.Associate(client, serverId, fip.IP).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Associated floating IP %v from instance %v", fip.IP, serverId) - defer func() { - err = floatingip.Disassociate(client, serverId, fip.IP).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Disassociated floating IP %v from instance %v", fip.IP, serverId) - }() - floatingIp, err := floatingip.Get(client, fip.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Floating IP %v is associated with Fixed IP %v", fip.IP, floatingIp.FixedIP) -} - -func TestFloatingIP(t *testing.T) { - pool := os.Getenv("OS_POOL_NAME") - if pool == "" { - t.Fatalf("OS_POOL_NAME must be set") - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - server, err := createFIPServer(t, client, choices) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(client, server.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - fip, err := createFloatingIP(t, client) - if err != nil { - t.Fatalf("Unable to create floating IP: %v", err) - } - defer func() { - err = floatingip.Delete(client, fip.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Floating IP deleted.") - }() - - associateFloatingIP(t, client, server.ID, fip) - -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/images_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/images_test.go deleted file mode 100644 index ceab22fa76d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/images_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build acceptance compute images - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/images" - "github.com/rackspace/gophercloud/pagination" -) - -func TestListImages(t *testing.T) { - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute: client: %v", err) - } - - t.Logf("ID\tRegion\tName\tStatus\tCreated") - - pager := images.ListDetail(client, nil) - count, pages := 0, 0 - pager.EachPage(func(page pagination.Page) (bool, error) { - pages++ - images, err := images.ExtractImages(page) - if err != nil { - return false, err - } - - for _, i := range images { - t.Logf("%s\t%s\t%s\t%s", i.ID, i.Name, i.Status, i.Created) - } - - return true, nil - }) - - t.Logf("--------\n%d images listed on %d pages.", count, pages) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/keypairs_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/keypairs_test.go deleted file mode 100644 index a4fe8db2d0d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/keypairs_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "crypto/rand" - "crypto/rsa" - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" - - "golang.org/x/crypto/ssh" -) - -const keyName = "gophercloud_test_key_pair" - -func TestCreateServerWithKeyPair(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - publicKey := privateKey.PublicKey - pub, err := ssh.NewPublicKey(&publicKey) - th.AssertNoErr(t, err) - pubBytes := ssh.MarshalAuthorizedKey(pub) - pk := string(pubBytes) - - kp, err := keypairs.Create(client, keypairs.CreateOpts{ - Name: keyName, - PublicKey: pk, - }).Extract() - th.AssertNoErr(t, err) - t.Logf("Created key pair: %s\n", kp) - - choices, err := ComputeChoicesFromEnv() - th.AssertNoErr(t, err) - - name := tools.RandomString("Gophercloud-", 8) - t.Logf("Creating server [%s] with key pair.", name) - - serverCreateOpts := servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - } - - server, err := servers.Create(client, keypairs.CreateOptsExt{ - serverCreateOpts, - keyName, - }).Extract() - th.AssertNoErr(t, err) - defer servers.Delete(client, server.ID) - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - server, err = servers.Get(client, server.ID).Extract() - t.Logf("Created server: %+v\n", server) - th.AssertNoErr(t, err) - th.AssertEquals(t, server.KeyName, keyName) - - t.Logf("Deleting key pair [%s]...", kp.Name) - err = keypairs.Delete(client, keyName).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Deleting server [%s]...", name) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/network_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/network_test.go deleted file mode 100644 index 7ebe7ec7bba..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/network_test.go +++ /dev/null @@ -1,78 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func getNetworkIDFromNetworkExtension(t *testing.T, client *gophercloud.ServiceClient, networkName string) (string, error) { - allPages, err := networks.List(client).AllPages() - if err != nil { - t.Fatalf("Unable to list networks: %v", err) - } - - networkList, err := networks.ExtractNetworks(allPages) - if err != nil { - t.Fatalf("Unable to list networks: %v", err) - } - - networkID := "" - for _, network := range networkList { - t.Logf("Network: %v", network) - if network.Label == networkName { - networkID = network.ID - } - } - - t.Logf("Found network ID for %s: %s\n", networkName, networkID) - - return networkID, nil -} - -func TestNetworks(t *testing.T) { - networkName := os.Getenv("OS_NETWORK_NAME") - if networkName == "" { - t.Fatalf("OS_NETWORK_NAME must be set") - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - networkID, err := getNetworkIDFromNetworkExtension(t, client, networkName) - if err != nil { - t.Fatalf("Unable to get network ID: %v", err) - } - - // createNetworkServer is defined in tenantnetworks_test.go - server, err := createNetworkServer(t, client, choices, networkID) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(client, server.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - allPages, err := networks.List(client).AllPages() - allNetworks, err := networks.ExtractNetworks(allPages) - th.AssertNoErr(t, err) - t.Logf("Retrieved all %d networks: %+v", len(allNetworks), allNetworks) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secdefrules_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secdefrules_test.go deleted file mode 100644 index 78b07986bd2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secdefrules_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// +build acceptance compute defsecrules - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - dsr "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/defsecrules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSecDefRules(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - id := createDefRule(t, client) - - listDefRules(t, client) - - getDefRule(t, client, id) - - deleteDefRule(t, client, id) -} - -func createDefRule(t *testing.T, client *gophercloud.ServiceClient) string { - opts := dsr.CreateOpts{ - FromPort: tools.RandomInt(80, 89), - ToPort: tools.RandomInt(90, 99), - IPProtocol: "TCP", - CIDR: "0.0.0.0/0", - } - - rule, err := dsr.Create(client, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Created default rule %s", rule.ID) - - return rule.ID -} - -func listDefRules(t *testing.T, client *gophercloud.ServiceClient) { - err := dsr.List(client).EachPage(func(page pagination.Page) (bool, error) { - drList, err := dsr.ExtractDefaultRules(page) - th.AssertNoErr(t, err) - - for _, dr := range drList { - t.Logf("Listing default rule %s: Name [%s] From Port [%s] To Port [%s] Protocol [%s]", - dr.ID, dr.FromPort, dr.ToPort, dr.IPProtocol) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getDefRule(t *testing.T, client *gophercloud.ServiceClient, id string) { - rule, err := dsr.Get(client, id).Extract() - th.AssertNoErr(t, err) - - t.Logf("Getting rule %s: %#v", id, rule) -} - -func deleteDefRule(t *testing.T, client *gophercloud.ServiceClient, id string) { - err := dsr.Delete(client, id).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Deleted rule %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secgroup_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secgroup_test.go deleted file mode 100644 index 4f507391093..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/secgroup_test.go +++ /dev/null @@ -1,177 +0,0 @@ -// +build acceptance compute secgroups - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSecGroups(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - serverID, needsDeletion := findServer(t, client) - - groupID := createSecGroup(t, client) - - listSecGroups(t, client) - - newName := tools.RandomString("secgroup_", 5) - updateSecGroup(t, client, groupID, newName) - - getSecGroup(t, client, groupID) - - addRemoveRules(t, client, groupID) - - addServerToSecGroup(t, client, serverID, newName) - - removeServerFromSecGroup(t, client, serverID, newName) - - if needsDeletion { - servers.Delete(client, serverID) - } - - deleteSecGroup(t, client, groupID) -} - -func createSecGroup(t *testing.T, client *gophercloud.ServiceClient) string { - opts := secgroups.CreateOpts{ - Name: tools.RandomString("secgroup_", 5), - Description: "something", - } - - group, err := secgroups.Create(client, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Created secgroup %s %s", group.ID, group.Name) - - return group.ID -} - -func listSecGroups(t *testing.T, client *gophercloud.ServiceClient) { - err := secgroups.List(client).EachPage(func(page pagination.Page) (bool, error) { - secGrpList, err := secgroups.ExtractSecurityGroups(page) - th.AssertNoErr(t, err) - - for _, sg := range secGrpList { - t.Logf("Listing secgroup %s: Name [%s] Desc [%s] TenantID [%s]", sg.ID, - sg.Name, sg.Description, sg.TenantID) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updateSecGroup(t *testing.T, client *gophercloud.ServiceClient, id, newName string) { - opts := secgroups.UpdateOpts{ - Name: newName, - Description: tools.RandomString("dec_", 10), - } - group, err := secgroups.Update(client, id, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Updated %s's name to %s", group.ID, group.Name) -} - -func getSecGroup(t *testing.T, client *gophercloud.ServiceClient, id string) { - group, err := secgroups.Get(client, id).Extract() - th.AssertNoErr(t, err) - - t.Logf("Getting %s: %#v", id, group) -} - -func addRemoveRules(t *testing.T, client *gophercloud.ServiceClient, id string) { - opts := secgroups.CreateRuleOpts{ - ParentGroupID: id, - FromPort: 22, - ToPort: 22, - IPProtocol: "TCP", - CIDR: "0.0.0.0/0", - } - - rule, err := secgroups.CreateRule(client, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Adding rule %s to group %s", rule.ID, id) - - err = secgroups.DeleteRule(client, rule.ID).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Deleted rule %s from group %s", rule.ID, id) -} - -func findServer(t *testing.T, client *gophercloud.ServiceClient) (string, bool) { - var serverID string - var needsDeletion bool - - err := servers.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - sList, err := servers.ExtractServers(page) - th.AssertNoErr(t, err) - - for _, s := range sList { - serverID = s.ID - needsDeletion = false - - t.Logf("Found an existing server: ID [%s]", serverID) - break - } - - return true, nil - }) - th.AssertNoErr(t, err) - - if serverID == "" { - t.Log("No server found, creating one") - - choices, err := ComputeChoicesFromEnv() - th.AssertNoErr(t, err) - - opts := &servers.CreateOpts{ - Name: tools.RandomString("secgroup_test_", 5), - ImageRef: choices.ImageID, - FlavorRef: choices.FlavorID, - } - - s, err := servers.Create(client, opts).Extract() - th.AssertNoErr(t, err) - serverID = s.ID - - t.Logf("Created server %s, waiting for it to build", s.ID) - err = servers.WaitForStatus(client, serverID, "ACTIVE", 300) - th.AssertNoErr(t, err) - - needsDeletion = true - } - - return serverID, needsDeletion -} - -func addServerToSecGroup(t *testing.T, client *gophercloud.ServiceClient, serverID, groupName string) { - err := secgroups.AddServerToGroup(client, serverID, groupName).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Adding group %s to server %s", groupName, serverID) -} - -func removeServerFromSecGroup(t *testing.T, client *gophercloud.ServiceClient, serverID, groupName string) { - err := secgroups.RemoveServerFromGroup(client, serverID, groupName).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Removing group %s from server %s", groupName, serverID) -} - -func deleteSecGroup(t *testing.T, client *gophercloud.ServiceClient, id string) { - err := secgroups.Delete(client, id).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Deleted group %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servergroup_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servergroup_test.go deleted file mode 100644 index 945854e3b27..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servergroup_test.go +++ /dev/null @@ -1,143 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "fmt" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func createServerGroup(t *testing.T, computeClient *gophercloud.ServiceClient) (*servergroups.ServerGroup, error) { - sg, err := servergroups.Create(computeClient, &servergroups.CreateOpts{ - Name: "test", - Policies: []string{"affinity"}, - }).Extract() - - if err != nil { - t.Fatalf("Unable to create server group: %v", err) - } - - t.Logf("Created server group: %v", sg.ID) - t.Logf("It has policies: %v", sg.Policies) - - return sg, nil -} - -func getServerGroup(t *testing.T, computeClient *gophercloud.ServiceClient, sgID string) error { - sg, err := servergroups.Get(computeClient, sgID).Extract() - if err != nil { - t.Fatalf("Unable to get server group: %v", err) - } - - t.Logf("Got server group: %v", sg.Name) - - return nil -} - -func createServerInGroup(t *testing.T, computeClient *gophercloud.ServiceClient, choices *ComputeChoices, serverGroup *servergroups.ServerGroup) (*servers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - serverCreateOpts := servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - AdminPass: pwd, - } - server, err := servers.Create(computeClient, schedulerhints.CreateOptsExt{ - serverCreateOpts, - schedulerhints.SchedulerHints{ - Group: serverGroup.ID, - }, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func verifySchedulerWorked(t *testing.T, firstServer, secondServer *servers.Server) error { - t.Logf("First server hostID: %v", firstServer.HostID) - t.Logf("Second server hostID: %v", secondServer.HostID) - if firstServer.HostID == secondServer.HostID { - return nil - } - - return fmt.Errorf("%s and %s were not scheduled on the same host.", firstServer.ID, secondServer.ID) -} - -func TestServerGroups(t *testing.T) { - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - computeClient, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - sg, err := createServerGroup(t, computeClient) - if err != nil { - t.Fatalf("Unable to create server group: %v", err) - } - defer func() { - servergroups.Delete(computeClient, sg.ID) - t.Logf("Server Group deleted.") - }() - - err = getServerGroup(t, computeClient, sg.ID) - if err != nil { - t.Fatalf("Unable to get server group: %v", err) - } - - firstServer, err := createServerInGroup(t, computeClient, choices, sg) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(computeClient, firstServer.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(computeClient, firstServer, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - firstServer, err = servers.Get(computeClient, firstServer.ID).Extract() - - secondServer, err := createServerInGroup(t, computeClient, choices, sg) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(computeClient, secondServer.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(computeClient, secondServer, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - secondServer, err = servers.Get(computeClient, secondServer.ID).Extract() - - if err = verifySchedulerWorked(t, firstServer, secondServer); err != nil { - t.Fatalf("Scheduling did not work: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servers_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servers_test.go deleted file mode 100644 index f6c7c052458..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/servers_test.go +++ /dev/null @@ -1,484 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListServers(t *testing.T) { - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - t.Logf("ID\tRegion\tName\tStatus\tIPv4\tIPv6") - - pager := servers.List(client, servers.ListOpts{}) - count, pages := 0, 0 - pager.EachPage(func(page pagination.Page) (bool, error) { - pages++ - t.Logf("---") - - servers, err := servers.ExtractServers(page) - if err != nil { - return false, err - } - - for _, s := range servers { - t.Logf("%s\t%s\t%s\t%s\t%s\t\n", s.ID, s.Name, s.Status, s.AccessIPv4, s.AccessIPv6) - count++ - } - - return true, nil - }) - - t.Logf("--------\n%d servers listed on %d pages.\n", count, pages) -} - -func networkingClient() (*gophercloud.ServiceClient, error) { - opts, err := openstack.AuthOptionsFromEnv() - if err != nil { - return nil, err - } - - provider, err := openstack.AuthenticatedClient(opts) - if err != nil { - return nil, err - } - - return openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -} - -func createServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices) (*servers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - var network networks.Network - - networkingClient, err := networkingClient() - if err != nil { - t.Fatalf("Unable to create a networking client: %v", err) - } - - pager := networks.List(networkingClient, networks.ListOpts{ - Name: choices.NetworkName, - Limit: 1, - }) - pager.EachPage(func(page pagination.Page) (bool, error) { - networks, err := networks.ExtractNetworks(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - if len(networks) == 0 { - t.Fatalf("No networks to attach to server") - return false, err - } - - network = networks[0] - - return false, nil - }) - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - server, err := servers.Create(client, servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - Networks: []servers.Network{ - servers.Network{UUID: network.ID}, - }, - AdminPass: pwd, - Personality: servers.Personality{ - &servers.File{ - Path: "/etc/test", - Contents: []byte("hello world"), - }, - }, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func TestCreateDestroyServer(t *testing.T) { - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(client, server.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - pager := servers.ListAddresses(client, server.ID) - pager.EachPage(func(page pagination.Page) (bool, error) { - networks, err := servers.ExtractAddresses(page) - if err != nil { - return false, err - } - - for n, a := range networks { - t.Logf("%s: %+v\n", n, a) - } - return true, nil - }) - - pager = servers.ListAddressesByNetwork(client, server.ID, choices.NetworkName) - pager.EachPage(func(page pagination.Page) (bool, error) { - addresses, err := servers.ExtractNetworkAddresses(page) - if err != nil { - return false, err - } - - for _, a := range addresses { - t.Logf("%+v\n", a) - } - return true, nil - }) -} - -func TestUpdateServer(t *testing.T) { - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - alternateName := tools.RandomString("ACPTTEST", 16) - for alternateName == server.Name { - alternateName = tools.RandomString("ACPTTEST", 16) - } - - t.Logf("Attempting to rename the server to %s.", alternateName) - - updated, err := servers.Update(client, server.ID, servers.UpdateOpts{Name: alternateName}).Extract() - if err != nil { - t.Fatalf("Unable to rename server: %v", err) - } - - if updated.ID != server.ID { - t.Errorf("Updated server ID [%s] didn't match original server ID [%s]!", updated.ID, server.ID) - } - - err = tools.WaitFor(func() (bool, error) { - latest, err := servers.Get(client, updated.ID).Extract() - if err != nil { - return false, err - } - - return latest.Name == alternateName, nil - }) -} - -func TestActionChangeAdminPassword(t *testing.T) { - t.Parallel() - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - randomPassword := tools.MakeNewPassword(server.AdminPass) - res := servers.ChangeAdminPassword(client, server.ID, randomPassword) - if res.Err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, server, "PASSWORD"); err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } -} - -func TestActionReboot(t *testing.T) { - t.Parallel() - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - res := servers.Reboot(client, server.ID, "aldhjflaskhjf") - if res.Err == nil { - t.Fatal("Expected the SDK to provide an ArgumentError here") - } - - t.Logf("Attempting reboot of server %s", server.ID) - res = servers.Reboot(client, server.ID, servers.OSReboot) - if res.Err != nil { - t.Fatalf("Unable to reboot server: %v", err) - } - - if err = waitForStatus(client, server, "REBOOT"); err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } -} - -func TestActionRebuild(t *testing.T) { - t.Parallel() - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - t.Logf("Attempting to rebuild server %s", server.ID) - - rebuildOpts := servers.RebuildOpts{ - Name: tools.RandomString("ACPTTEST", 16), - AdminPass: tools.MakeNewPassword(server.AdminPass), - ImageID: choices.ImageID, - } - - rebuilt, err := servers.Rebuild(client, server.ID, rebuildOpts).Extract() - if err != nil { - t.Fatal(err) - } - - if rebuilt.ID != server.ID { - t.Errorf("Expected rebuilt server ID of [%s]; got [%s]", server.ID, rebuilt.ID) - } - - if err = waitForStatus(client, rebuilt, "REBUILD"); err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, rebuilt, "ACTIVE"); err != nil { - t.Fatal(err) - } -} - -func resizeServer(t *testing.T, client *gophercloud.ServiceClient, server *servers.Server, choices *ComputeChoices) { - if err := waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - t.Logf("Attempting to resize server [%s]", server.ID) - - opts := &servers.ResizeOpts{ - FlavorRef: choices.FlavorIDResize, - } - if res := servers.Resize(client, server.ID, opts); res.Err != nil { - t.Fatal(res.Err) - } - - if err := waitForStatus(client, server, "VERIFY_RESIZE"); err != nil { - t.Fatal(err) - } -} - -func TestActionResizeConfirm(t *testing.T) { - t.Parallel() - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - resizeServer(t, client, server, choices) - - t.Logf("Attempting to confirm resize for server %s", server.ID) - - if res := servers.ConfirmResize(client, server.ID); res.Err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } -} - -func TestActionResizeRevert(t *testing.T) { - t.Parallel() - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - resizeServer(t, client, server, choices) - - t.Logf("Attempting to revert resize for server %s", server.ID) - - if res := servers.RevertResize(client, server.ID); res.Err != nil { - t.Fatal(err) - } - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } -} - -func TestServerMetadata(t *testing.T) { - t.Parallel() - - choices, err := ComputeChoicesFromEnv() - th.AssertNoErr(t, err) - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - server, err := createServer(t, client, choices) - if err != nil { - t.Fatal(err) - } - defer servers.Delete(client, server.ID) - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatal(err) - } - - metadata, err := servers.UpdateMetadata(client, server.ID, servers.MetadataOpts{ - "foo": "bar", - "this": "that", - }).Extract() - th.AssertNoErr(t, err) - t.Logf("UpdateMetadata result: %+v\n", metadata) - - err = servers.DeleteMetadatum(client, server.ID, "foo").ExtractErr() - th.AssertNoErr(t, err) - - metadata, err = servers.CreateMetadatum(client, server.ID, servers.MetadatumOpts{ - "foo": "baz", - }).Extract() - th.AssertNoErr(t, err) - t.Logf("CreateMetadatum result: %+v\n", metadata) - - metadata, err = servers.Metadatum(client, server.ID, "foo").Extract() - th.AssertNoErr(t, err) - t.Logf("Metadatum result: %+v\n", metadata) - th.AssertEquals(t, "baz", metadata["foo"]) - - metadata, err = servers.Metadata(client, server.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Metadata result: %+v\n", metadata) - - metadata, err = servers.ResetMetadata(client, server.ID, servers.MetadataOpts{}).Extract() - th.AssertNoErr(t, err) - t.Logf("ResetMetadata result: %+v\n", metadata) - th.AssertDeepEquals(t, map[string]string{}, metadata) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/tenantnetworks_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/tenantnetworks_test.go deleted file mode 100644 index a92e8bf5314..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/tenantnetworks_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func getNetworkID(t *testing.T, client *gophercloud.ServiceClient, networkName string) (string, error) { - allPages, err := tenantnetworks.List(client).AllPages() - if err != nil { - t.Fatalf("Unable to list networks: %v", err) - } - - networkList, err := tenantnetworks.ExtractNetworks(allPages) - if err != nil { - t.Fatalf("Unable to list networks: %v", err) - } - - networkID := "" - for _, network := range networkList { - t.Logf("Network: %v", network) - if network.Name == networkName { - networkID = network.ID - } - } - - t.Logf("Found network ID for %s: %s\n", networkName, networkID) - - return networkID, nil -} - -func createNetworkServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices, networkID string) (*servers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - networks := make([]servers.Network, 1) - networks[0] = servers.Network{ - UUID: networkID, - } - - server, err := servers.Create(client, servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - AdminPass: pwd, - Networks: networks, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func TestTenantNetworks(t *testing.T) { - networkName := os.Getenv("OS_NETWORK_NAME") - if networkName == "" { - t.Fatalf("OS_NETWORK_NAME must be set") - } - - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - client, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - networkID, err := getNetworkID(t, client, networkName) - if err != nil { - t.Fatalf("Unable to get network ID: %v", err) - } - - server, err := createNetworkServer(t, client, choices, networkID) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(client, server.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(client, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - allPages, err := tenantnetworks.List(client).AllPages() - allNetworks, err := tenantnetworks.ExtractNetworks(allPages) - th.AssertNoErr(t, err) - t.Logf("Retrieved all %d networks: %+v", len(allNetworks), allNetworks) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/volumeattach_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/volumeattach_test.go deleted file mode 100644 index 34634c9d2f8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/volumeattach_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack" - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func newBlockClient(t *testing.T) (*gophercloud.ServiceClient, error) { - ao, err := openstack.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - client, err := openstack.AuthenticatedClient(ao) - th.AssertNoErr(t, err) - - return openstack.NewBlockStorageV1(client, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) -} - -func createVAServer(t *testing.T, computeClient *gophercloud.ServiceClient, choices *ComputeChoices) (*servers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - server, err := servers.Create(computeClient, servers.CreateOpts{ - Name: name, - FlavorRef: choices.FlavorID, - ImageRef: choices.ImageID, - AdminPass: pwd, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func createVAVolume(t *testing.T, blockClient *gophercloud.ServiceClient) (*volumes.Volume, error) { - volume, err := volumes.Create(blockClient, &volumes.CreateOpts{ - Size: 1, - Name: "gophercloud-test-volume", - }).Extract() - th.AssertNoErr(t, err) - defer func() { - err = volumes.WaitForStatus(blockClient, volume.ID, "available", 60) - th.AssertNoErr(t, err) - }() - - return volume, err -} - -func createVolumeAttachment(t *testing.T, computeClient *gophercloud.ServiceClient, blockClient *gophercloud.ServiceClient, serverId string, volumeId string) { - va, err := volumeattach.Create(computeClient, serverId, &volumeattach.CreateOpts{ - VolumeID: volumeId, - }).Extract() - th.AssertNoErr(t, err) - defer func() { - err = volumes.WaitForStatus(blockClient, volumeId, "in-use", 60) - th.AssertNoErr(t, err) - err = volumeattach.Delete(computeClient, serverId, va.ID).ExtractErr() - th.AssertNoErr(t, err) - err = volumes.WaitForStatus(blockClient, volumeId, "available", 60) - th.AssertNoErr(t, err) - }() -} - -func TestAttachVolume(t *testing.T) { - choices, err := ComputeChoicesFromEnv() - if err != nil { - t.Fatal(err) - } - - computeClient, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - blockClient, err := newBlockClient(t) - if err != nil { - t.Fatalf("Unable to create a blockstorage client: %v", err) - } - - server, err := createVAServer(t, computeClient, choices) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(computeClient, server.ID) - t.Logf("Server deleted.") - }() - - if err = waitForStatus(computeClient, server, "ACTIVE"); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - volume, err := createVAVolume(t, blockClient) - if err != nil { - t.Fatalf("Unable to create volume: %v", err) - } - defer func() { - err = volumes.Delete(blockClient, volume.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Volume deleted.") - }() - - createVolumeAttachment(t, computeClient, blockClient, server.ID, volume.ID) - -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/extension_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/extension_test.go deleted file mode 100644 index d1fa1e3dcec..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/extension_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "testing" - - extensions2 "github.com/rackspace/gophercloud/openstack/identity/v2/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestEnumerateExtensions(t *testing.T) { - service := authenticatedClient(t) - - t.Logf("Extensions available on this identity endpoint:") - count := 0 - err := extensions2.List(service).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - extensions, err := extensions2.ExtractExtensions(page) - th.AssertNoErr(t, err) - - for i, ext := range extensions { - t.Logf("[%02d] name=[%s] namespace=[%s]", i, ext.Name, ext.Namespace) - t.Logf(" alias=[%s] updated=[%s]", ext.Alias, ext.Updated) - t.Logf(" description=[%s]", ext.Description) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) -} - -func TestGetExtension(t *testing.T) { - service := authenticatedClient(t) - - ext, err := extensions2.Get(service, "OS-KSCRUD").Extract() - th.AssertNoErr(t, err) - - th.CheckEquals(t, "OpenStack Keystone User CRUD", ext.Name) - th.CheckEquals(t, "http://docs.openstack.org/identity/api/ext/OS-KSCRUD/v1.0", ext.Namespace) - th.CheckEquals(t, "OS-KSCRUD", ext.Alias) - th.CheckEquals(t, "OpenStack extensions to Keystone v2.0 API enabling User Operations.", ext.Description) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/identity_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/identity_test.go deleted file mode 100644 index 96bf1fdadea..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/identity_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - th "github.com/rackspace/gophercloud/testhelper" -) - -func v2AuthOptions(t *testing.T) gophercloud.AuthOptions { - // Obtain credentials from the environment. - ao, err := openstack.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - // Trim out unused fields. Prefer authentication by API key to password. - ao.UserID, ao.DomainID, ao.DomainName = "", "", "" - if ao.APIKey != "" { - ao.Password = "" - } - - return ao -} - -func createClient(t *testing.T, auth bool) *gophercloud.ServiceClient { - ao := v2AuthOptions(t) - - provider, err := openstack.NewClient(ao.IdentityEndpoint) - th.AssertNoErr(t, err) - - if auth { - err = openstack.AuthenticateV2(provider, ao) - th.AssertNoErr(t, err) - } - - return openstack.NewIdentityV2(provider) -} - -func unauthenticatedClient(t *testing.T) *gophercloud.ServiceClient { - return createClient(t, false) -} - -func authenticatedClient(t *testing.T) *gophercloud.ServiceClient { - return createClient(t, true) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/role_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/role_test.go deleted file mode 100644 index ba243fe02bf..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/role_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// +build acceptance identity roles - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestRoles(t *testing.T) { - client := authenticatedClient(t) - - tenantID := findTenant(t, client) - userID := createUser(t, client, tenantID) - roleID := listRoles(t, client) - - addUserRole(t, client, tenantID, userID, roleID) - - deleteUserRole(t, client, tenantID, userID, roleID) - - deleteUser(t, client, userID) -} - -func listRoles(t *testing.T, client *gophercloud.ServiceClient) string { - var roleID string - - err := roles.List(client).EachPage(func(page pagination.Page) (bool, error) { - roleList, err := roles.ExtractRoles(page) - th.AssertNoErr(t, err) - - for _, role := range roleList { - t.Logf("Listing role: ID [%s] Name [%s]", role.ID, role.Name) - roleID = role.ID - } - - return true, nil - }) - - th.AssertNoErr(t, err) - - return roleID -} - -func addUserRole(t *testing.T, client *gophercloud.ServiceClient, tenantID, userID, roleID string) { - err := roles.AddUserRole(client, tenantID, userID, roleID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Added role %s to user %s", roleID, userID) -} - -func deleteUserRole(t *testing.T, client *gophercloud.ServiceClient, tenantID, userID, roleID string) { - err := roles.DeleteUserRole(client, tenantID, userID, roleID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Removed role %s from user %s", roleID, userID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/tenant_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/tenant_test.go deleted file mode 100644 index 578fc483b8e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/tenant_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "testing" - - tenants2 "github.com/rackspace/gophercloud/openstack/identity/v2/tenants" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestEnumerateTenants(t *testing.T) { - service := authenticatedClient(t) - - t.Logf("Tenants to which your current token grants access:") - count := 0 - err := tenants2.List(service, nil).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - tenants, err := tenants2.ExtractTenants(page) - th.AssertNoErr(t, err) - for i, tenant := range tenants { - t.Logf("[%02d] name=[%s] id=[%s] description=[%s] enabled=[%v]", - i, tenant.Name, tenant.ID, tenant.Description, tenant.Enabled) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/token_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/token_test.go deleted file mode 100644 index d9031408558..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/token_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "testing" - - tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAuthenticate(t *testing.T) { - ao := v2AuthOptions(t) - service := unauthenticatedClient(t) - - // Authenticated! - result := tokens2.Create(service, tokens2.WrapOptions(ao)) - - // Extract and print the token. - token, err := result.ExtractToken() - th.AssertNoErr(t, err) - - t.Logf("Acquired token: [%s]", token.ID) - t.Logf("The token will expire at: [%s]", token.ExpiresAt.String()) - t.Logf("The token is valid for tenant: [%#v]", token.Tenant) - - // Extract and print the service catalog. - catalog, err := result.ExtractServiceCatalog() - th.AssertNoErr(t, err) - - t.Logf("Acquired service catalog listing [%d] services", len(catalog.Entries)) - for i, entry := range catalog.Entries { - t.Logf("[%02d]: name=[%s], type=[%s]", i, entry.Name, entry.Type) - for _, endpoint := range entry.Endpoints { - t.Logf(" - region=[%s] publicURL=[%s]", endpoint.Region, endpoint.PublicURL) - } - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/user_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/user_test.go deleted file mode 100644 index fe73d198987..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v2/user_test.go +++ /dev/null @@ -1,127 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "strconv" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/identity/v2/tenants" - "github.com/rackspace/gophercloud/openstack/identity/v2/users" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestUsers(t *testing.T) { - client := authenticatedClient(t) - - tenantID := findTenant(t, client) - - userID := createUser(t, client, tenantID) - - listUsers(t, client) - - getUser(t, client, userID) - - updateUser(t, client, userID) - - listUserRoles(t, client, tenantID, userID) - - deleteUser(t, client, userID) -} - -func findTenant(t *testing.T, client *gophercloud.ServiceClient) string { - var tenantID string - err := tenants.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - tenantList, err := tenants.ExtractTenants(page) - th.AssertNoErr(t, err) - - for _, t := range tenantList { - tenantID = t.ID - break - } - - return true, nil - }) - th.AssertNoErr(t, err) - - return tenantID -} - -func createUser(t *testing.T, client *gophercloud.ServiceClient, tenantID string) string { - t.Log("Creating user") - - opts := users.CreateOpts{ - Name: tools.RandomString("user_", 5), - Enabled: users.Disabled, - TenantID: tenantID, - Email: "new_user@foo.com", - } - - user, err := users.Create(client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created user %s on tenant %s", user.ID, tenantID) - - return user.ID -} - -func listUsers(t *testing.T, client *gophercloud.ServiceClient) { - err := users.List(client).EachPage(func(page pagination.Page) (bool, error) { - userList, err := users.ExtractUsers(page) - th.AssertNoErr(t, err) - - for _, user := range userList { - t.Logf("Listing user: ID [%s] Name [%s] Email [%s] Enabled? [%s]", - user.ID, user.Name, user.Email, strconv.FormatBool(user.Enabled)) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - _, err := users.Get(client, userID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting user %s", userID) -} - -func updateUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - opts := users.UpdateOpts{Name: tools.RandomString("new_name", 5), Email: "new@foo.com"} - user, err := users.Update(client, userID, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Updated user %s: Name [%s] Email [%s]", userID, user.Name, user.Email) -} - -func listUserRoles(t *testing.T, client *gophercloud.ServiceClient, tenantID, userID string) { - count := 0 - err := users.ListRoles(client, tenantID, userID).EachPage(func(page pagination.Page) (bool, error) { - count++ - - roleList, err := users.ExtractRoles(page) - th.AssertNoErr(t, err) - - t.Logf("Listing roles for user %s", userID) - - for _, r := range roleList { - t.Logf("- %s (%s)", r.Name, r.ID) - } - - return true, nil - }) - - if count == 0 { - t.Logf("No roles for user %s", userID) - } - - th.AssertNoErr(t, err) -} - -func deleteUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - res := users.Delete(client, userID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted user %s", userID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/endpoint_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/endpoint_test.go deleted file mode 100644 index ea893c2deae..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/endpoint_test.go +++ /dev/null @@ -1,111 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - endpoints3 "github.com/rackspace/gophercloud/openstack/identity/v3/endpoints" - services3 "github.com/rackspace/gophercloud/openstack/identity/v3/services" - "github.com/rackspace/gophercloud/pagination" -) - -func TestListEndpoints(t *testing.T) { - // Create a service client. - serviceClient := createAuthenticatedClient(t) - if serviceClient == nil { - return - } - - // Use the service to list all available endpoints. - pager := endpoints3.List(serviceClient, endpoints3.ListOpts{}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - endpoints, err := endpoints3.ExtractEndpoints(page) - if err != nil { - t.Fatalf("Error extracting endpoings: %v", err) - } - - for _, endpoint := range endpoints { - t.Logf("Endpoint: %8s %10s %9s %s", - endpoint.ID, - endpoint.Availability, - endpoint.Name, - endpoint.URL) - } - - return true, nil - }) - if err != nil { - t.Errorf("Unexpected error while iterating endpoint pages: %v", err) - } -} - -func TestNavigateCatalog(t *testing.T) { - // Create a service client. - client := createAuthenticatedClient(t) - if client == nil { - return - } - - var compute *services3.Service - var endpoint *endpoints3.Endpoint - - // Discover the service we're interested in. - servicePager := services3.List(client, services3.ListOpts{ServiceType: "compute"}) - err := servicePager.EachPage(func(page pagination.Page) (bool, error) { - part, err := services3.ExtractServices(page) - if err != nil { - return false, err - } - if compute != nil { - t.Fatalf("Expected one service, got more than one page") - return false, nil - } - if len(part) != 1 { - t.Fatalf("Expected one service, got %d", len(part)) - return false, nil - } - - compute = &part[0] - return true, nil - }) - if err != nil { - t.Fatalf("Unexpected error iterating pages: %v", err) - } - - if compute == nil { - t.Fatalf("No compute service found.") - } - - // Enumerate the endpoints available for this service. - computePager := endpoints3.List(client, endpoints3.ListOpts{ - Availability: gophercloud.AvailabilityPublic, - ServiceID: compute.ID, - }) - err = computePager.EachPage(func(page pagination.Page) (bool, error) { - part, err := endpoints3.ExtractEndpoints(page) - if err != nil { - return false, err - } - if endpoint != nil { - t.Fatalf("Expected one endpoint, got more than one page") - return false, nil - } - if len(part) != 1 { - t.Fatalf("Expected one endpoint, got %d", len(part)) - return false, nil - } - - endpoint = &part[0] - return true, nil - }) - - if endpoint == nil { - t.Fatalf("No endpoint found.") - } - - t.Logf("Success. The compute endpoint is at %s.", endpoint.URL) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/identity_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/identity_test.go deleted file mode 100644 index ce643458864..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/identity_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack" - th "github.com/rackspace/gophercloud/testhelper" -) - -func createAuthenticatedClient(t *testing.T) *gophercloud.ServiceClient { - // Obtain credentials from the environment. - ao, err := openstack.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - // Trim out unused fields. - ao.Username, ao.TenantID, ao.TenantName = "", "", "" - - if ao.UserID == "" { - t.Logf("Skipping identity v3 tests because no OS_USERID is present.") - return nil - } - - // Create a client and manually authenticate against v3. - providerClient, err := openstack.NewClient(ao.IdentityEndpoint) - if err != nil { - t.Fatalf("Unable to instantiate client: %v", err) - } - - err = openstack.AuthenticateV3(providerClient, ao) - if err != nil { - t.Fatalf("Unable to authenticate against identity v3: %v", err) - } - - // Create a service client. - return openstack.NewIdentityV3(providerClient) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/service_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/service_test.go deleted file mode 100644 index 082bd11e742..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/service_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "testing" - - services3 "github.com/rackspace/gophercloud/openstack/identity/v3/services" - "github.com/rackspace/gophercloud/pagination" -) - -func TestListServices(t *testing.T) { - // Create a service client. - serviceClient := createAuthenticatedClient(t) - if serviceClient == nil { - return - } - - // Use the client to list all available services. - pager := services3.List(serviceClient, services3.ListOpts{}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - parts, err := services3.ExtractServices(page) - if err != nil { - return false, err - } - - t.Logf("--- Page ---") - for _, service := range parts { - t.Logf("Service: %32s %15s %10s %s", service.ID, service.Type, service.Name, *service.Description) - } - return true, nil - }) - if err != nil { - t.Errorf("Unexpected error traversing pages: %v", err) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/token_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/token_test.go deleted file mode 100644 index 4342ade03cc..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/identity/v3/token_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack" - tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens" -) - -func TestGetToken(t *testing.T) { - // Obtain credentials from the environment. - ao, err := openstack.AuthOptionsFromEnv() - if err != nil { - t.Fatalf("Unable to acquire credentials: %v", err) - } - - // Trim out unused fields. Skip if we don't have a UserID. - ao.Username, ao.TenantID, ao.TenantName = "", "", "" - if ao.UserID == "" { - t.Logf("Skipping identity v3 tests because no OS_USERID is present.") - return - } - - // Create an unauthenticated client. - provider, err := openstack.NewClient(ao.IdentityEndpoint) - if err != nil { - t.Fatalf("Unable to instantiate client: %v", err) - } - - // Create a service client. - service := openstack.NewIdentityV3(provider) - - // Use the service to create a token. - token, err := tokens3.Create(service, ao, nil).Extract() - if err != nil { - t.Fatalf("Unable to get token: %v", err) - } - - t.Logf("Acquired token: %s", token.ID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/apiversion_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/apiversion_test.go deleted file mode 100644 index 99e1d011875..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/apiversion_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/apiversions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListAPIVersions(t *testing.T) { - Setup(t) - defer Teardown() - - pager := apiversions.ListVersions(Client) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - versions, err := apiversions.ExtractAPIVersions(page) - th.AssertNoErr(t, err) - - for _, v := range versions { - t.Logf("API Version: ID [%s] Status [%s]", v.ID, v.Status) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} - -func TestListAPIResources(t *testing.T) { - Setup(t) - defer Teardown() - - pager := apiversions.ListVersionResources(Client, "v2.0") - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - vrs, err := apiversions.ExtractVersionResources(page) - th.AssertNoErr(t, err) - - for _, vr := range vrs { - t.Logf("Network: Name [%s] Collection [%s]", vr.Name, vr.Collection) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extension_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extension_test.go deleted file mode 100644 index edcbba4fd15..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extension_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListExts(t *testing.T) { - Setup(t) - defer Teardown() - - pager := extensions.List(Client) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - exts, err := extensions.ExtractExtensions(page) - th.AssertNoErr(t, err) - - for _, ext := range exts { - t.Logf("Extension: Name [%s] Description [%s]", ext.Name, ext.Description) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} - -func TestGetExt(t *testing.T) { - Setup(t) - defer Teardown() - - ext, err := extensions.Get(Client, "service-type").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, ext.Updated, "2013-01-20T00:00:00-00:00") - th.AssertEquals(t, ext.Name, "Neutron Service Type Management") - th.AssertEquals(t, ext.Namespace, "http://docs.openstack.org/ext/neutron/service-type/api/v1.0") - th.AssertEquals(t, ext.Alias, "service-type") - th.AssertEquals(t, ext.Description, "API for retrieving service providers for Neutron advanced services") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/firewall_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/firewall_test.go deleted file mode 100644 index 80246b6481e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/firewall_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// +build acceptance networking fwaas - -package fwaas - -import ( - "testing" - "time" - - "github.com/rackspace/gophercloud" - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func firewallSetup(t *testing.T) string { - base.Setup(t) - return createPolicy(t, &policies.CreateOpts{}) -} - -func firewallTeardown(t *testing.T, policyID string) { - defer base.Teardown() - deletePolicy(t, policyID) -} - -func TestFirewall(t *testing.T) { - policyID := firewallSetup(t) - defer firewallTeardown(t, policyID) - - firewallID := createFirewall(t, &firewalls.CreateOpts{ - Name: "gophercloud test", - Description: "acceptance test", - PolicyID: policyID, - }) - - waitForFirewallToBeActive(t, firewallID) - - listFirewalls(t) - - updateFirewall(t, firewallID, &firewalls.UpdateOpts{ - Description: "acceptance test updated", - }) - - waitForFirewallToBeActive(t, firewallID) - - deleteFirewall(t, firewallID) - - waitForFirewallToBeDeleted(t, firewallID) -} - -func createFirewall(t *testing.T, opts *firewalls.CreateOpts) string { - f, err := firewalls.Create(base.Client, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created firewall: %#v", opts) - return f.ID -} - -func listFirewalls(t *testing.T) { - err := firewalls.List(base.Client, firewalls.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - firewallList, err := firewalls.ExtractFirewalls(page) - if err != nil { - t.Errorf("Failed to extract firewalls: %v", err) - return false, err - } - - for _, r := range firewallList { - t.Logf("Listing firewalls: ID [%s]", r.ID) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func updateFirewall(t *testing.T, firewallID string, opts *firewalls.UpdateOpts) { - f, err := firewalls.Update(base.Client, firewallID, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Updated firewall ID [%s]", f.ID) -} - -func getFirewall(t *testing.T, firewallID string) *firewalls.Firewall { - f, err := firewalls.Get(base.Client, firewallID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting firewall ID [%s]", f.ID) - return f -} - -func deleteFirewall(t *testing.T, firewallID string) { - res := firewalls.Delete(base.Client, firewallID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted firewall %s", firewallID) -} - -func waitForFirewallToBeActive(t *testing.T, firewallID string) { - for i := 0; i < 10; i++ { - fw := getFirewall(t, firewallID) - if fw.Status == "ACTIVE" { - break - } - time.Sleep(time.Second) - } -} - -func waitForFirewallToBeDeleted(t *testing.T, firewallID string) { - for i := 0; i < 10; i++ { - err := firewalls.Get(base.Client, firewallID).Err - if err != nil { - httpStatus := err.(*gophercloud.UnexpectedResponseCodeError) - if httpStatus.Actual == 404 { - return - } - } - time.Sleep(time.Second) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/policy_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/policy_test.go deleted file mode 100644 index fdca22e3fbc..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/policy_test.go +++ /dev/null @@ -1,107 +0,0 @@ -// +build acceptance networking fwaas - -package fwaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func firewallPolicySetup(t *testing.T) string { - base.Setup(t) - return createRule(t, &rules.CreateOpts{ - Protocol: "tcp", - Action: "allow", - }) -} - -func firewallPolicyTeardown(t *testing.T, ruleID string) { - defer base.Teardown() - deleteRule(t, ruleID) -} - -func TestFirewallPolicy(t *testing.T) { - ruleID := firewallPolicySetup(t) - defer firewallPolicyTeardown(t, ruleID) - - policyID := createPolicy(t, &policies.CreateOpts{ - Name: "gophercloud test", - Description: "acceptance test", - Rules: []string{ - ruleID, - }, - }) - - listPolicies(t) - - updatePolicy(t, policyID, &policies.UpdateOpts{ - Description: "acceptance test updated", - }) - - getPolicy(t, policyID) - - removeRuleFromPolicy(t, policyID, ruleID) - - addRuleToPolicy(t, policyID, ruleID) - - deletePolicy(t, policyID) -} - -func createPolicy(t *testing.T, opts *policies.CreateOpts) string { - p, err := policies.Create(base.Client, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created policy: %#v", opts) - return p.ID -} - -func listPolicies(t *testing.T) { - err := policies.List(base.Client, policies.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - policyList, err := policies.ExtractPolicies(page) - if err != nil { - t.Errorf("Failed to extract policies: %v", err) - return false, err - } - - for _, p := range policyList { - t.Logf("Listing policies: ID [%s]", p.ID) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func updatePolicy(t *testing.T, policyID string, opts *policies.UpdateOpts) { - p, err := policies.Update(base.Client, policyID, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Updated policy ID [%s]", p.ID) -} - -func removeRuleFromPolicy(t *testing.T, policyID string, ruleID string) { - err := policies.RemoveRule(base.Client, policyID, ruleID) - th.AssertNoErr(t, err) - t.Logf("Removed rule [%s] from policy ID [%s]", ruleID, policyID) -} - -func addRuleToPolicy(t *testing.T, policyID string, ruleID string) { - err := policies.InsertRule(base.Client, policyID, ruleID, "", "") - th.AssertNoErr(t, err) - t.Logf("Inserted rule [%s] into policy ID [%s]", ruleID, policyID) -} - -func getPolicy(t *testing.T, policyID string) { - p, err := policies.Get(base.Client, policyID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting policy ID [%s]", p.ID) -} - -func deletePolicy(t *testing.T, policyID string) { - res := policies.Delete(base.Client, policyID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted policy %s", policyID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/rule_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/rule_test.go deleted file mode 100644 index 144aa0998f1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/fwaas/rule_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build acceptance networking fwaas - -package fwaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestFirewallRules(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - ruleID := createRule(t, &rules.CreateOpts{ - Name: "gophercloud_test", - Description: "acceptance test", - Protocol: "tcp", - Action: "allow", - DestinationIPAddress: "192.168.0.0/24", - DestinationPort: "22", - }) - - listRules(t) - - destinationIPAddress := "192.168.1.0/24" - destinationPort := "" - sourcePort := "1234" - - updateRule(t, ruleID, &rules.UpdateOpts{ - DestinationIPAddress: &destinationIPAddress, - DestinationPort: &destinationPort, - SourcePort: &sourcePort, - }) - - getRule(t, ruleID) - - deleteRule(t, ruleID) -} - -func createRule(t *testing.T, opts *rules.CreateOpts) string { - r, err := rules.Create(base.Client, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created rule: %#v", opts) - return r.ID -} - -func listRules(t *testing.T) { - err := rules.List(base.Client, rules.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - ruleList, err := rules.ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract rules: %v", err) - return false, err - } - - for _, r := range ruleList { - t.Logf("Listing rules: ID [%s]", r.ID) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func updateRule(t *testing.T, ruleID string, opts *rules.UpdateOpts) { - r, err := rules.Update(base.Client, ruleID, *opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Updated rule ID [%s]", r.ID) -} - -func getRule(t *testing.T, ruleID string) { - r, err := rules.Get(base.Client, ruleID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting rule ID [%s]", r.ID) -} - -func deleteRule(t *testing.T, ruleID string) { - res := rules.Delete(base.Client, ruleID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted rule %s", ruleID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/layer3_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/layer3_test.go deleted file mode 100644 index 63e0be39d7b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/layer3_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// +build acceptance networking layer3ext - -package extensions - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers" - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -const ( - cidr1 = "10.0.0.1/24" - cidr2 = "20.0.0.1/24" -) - -func TestAll(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - testRouter(t) - testFloatingIP(t) -} - -func testRouter(t *testing.T) { - // Setup: Create network - networkID := createNetwork(t) - - // Create router - routerID := createRouter(t, networkID) - - // Lists routers - listRouters(t) - - // Update router - updateRouter(t, routerID) - - // Get router - getRouter(t, routerID) - - // Create new subnet. Note: this subnet will be deleted when networkID is deleted - subnetID := createSubnet(t, networkID, cidr2) - - // Add interface - addInterface(t, routerID, subnetID) - - // Remove interface - removeInterface(t, routerID, subnetID) - - // Delete router - deleteRouter(t, routerID) - - // Cleanup - deleteNetwork(t, networkID) -} - -func testFloatingIP(t *testing.T) { - // Setup external network - extNetworkID := createNetwork(t) - - // Setup internal network, subnet and port - intNetworkID, subnetID, portID := createInternalTopology(t) - - // Now the important part: we need to allow the external network to talk to - // the internal subnet. For this we need a router that has an interface to - // the internal subnet. - routerID := bridgeIntSubnetWithExtNetwork(t, extNetworkID, subnetID) - - // Create floating IP - ipID := createFloatingIP(t, extNetworkID, portID) - - // Get floating IP - getFloatingIP(t, ipID) - - // Update floating IP - updateFloatingIP(t, ipID, portID) - - // Delete floating IP - deleteFloatingIP(t, ipID) - - // Remove the internal subnet interface - removeInterface(t, routerID, subnetID) - - // Delete router and external network - deleteRouter(t, routerID) - deleteNetwork(t, extNetworkID) - - // Delete internal port and network - deletePort(t, portID) - deleteNetwork(t, intNetworkID) -} - -func createNetwork(t *testing.T) string { - t.Logf("Creating a network") - - asu := true - opts := external.CreateOpts{ - Parent: networks.CreateOpts{Name: "sample_network", AdminStateUp: &asu}, - External: true, - } - n, err := networks.Create(base.Client, opts).Extract() - - th.AssertNoErr(t, err) - - if n.ID == "" { - t.Fatalf("No ID returned when creating a network") - } - - createSubnet(t, n.ID, cidr1) - - t.Logf("Network created: ID [%s]", n.ID) - - return n.ID -} - -func deleteNetwork(t *testing.T, networkID string) { - t.Logf("Deleting network %s", networkID) - networks.Delete(base.Client, networkID) -} - -func deletePort(t *testing.T, portID string) { - t.Logf("Deleting port %s", portID) - ports.Delete(base.Client, portID) -} - -func createInternalTopology(t *testing.T) (string, string, string) { - t.Logf("Creating an internal network (for port)") - opts := networks.CreateOpts{Name: "internal_network"} - n, err := networks.Create(base.Client, opts).Extract() - th.AssertNoErr(t, err) - - // A subnet is also needed - subnetID := createSubnet(t, n.ID, cidr2) - - t.Logf("Creating an internal port on network %s", n.ID) - p, err := ports.Create(base.Client, ports.CreateOpts{ - NetworkID: n.ID, - Name: "fixed_internal_port", - }).Extract() - th.AssertNoErr(t, err) - - return n.ID, subnetID, p.ID -} - -func bridgeIntSubnetWithExtNetwork(t *testing.T, networkID, subnetID string) string { - // Create router with external gateway info - routerID := createRouter(t, networkID) - - // Add interface for internal subnet - addInterface(t, routerID, subnetID) - - return routerID -} - -func createSubnet(t *testing.T, networkID, cidr string) string { - t.Logf("Creating a subnet for network %s", networkID) - - iFalse := false - s, err := subnets.Create(base.Client, subnets.CreateOpts{ - NetworkID: networkID, - CIDR: cidr, - IPVersion: subnets.IPv4, - Name: "my_subnet", - EnableDHCP: &iFalse, - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Subnet created: ID [%s]", s.ID) - - return s.ID -} - -func createRouter(t *testing.T, networkID string) string { - t.Logf("Creating a router for network %s", networkID) - - asu := false - gwi := routers.GatewayInfo{NetworkID: networkID} - r, err := routers.Create(base.Client, routers.CreateOpts{ - Name: "foo_router", - AdminStateUp: &asu, - GatewayInfo: &gwi, - }).Extract() - - th.AssertNoErr(t, err) - - if r.ID == "" { - t.Fatalf("No ID returned when creating a router") - } - - t.Logf("Router created: ID [%s]", r.ID) - - return r.ID -} - -func listRouters(t *testing.T) { - pager := routers.List(base.Client, routers.ListOpts{}) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - routerList, err := routers.ExtractRouters(page) - th.AssertNoErr(t, err) - - for _, r := range routerList { - t.Logf("Listing router: ID [%s] Name [%s] Status [%s] GatewayInfo [%#v]", - r.ID, r.Name, r.Status, r.GatewayInfo) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updateRouter(t *testing.T, routerID string) { - _, err := routers.Update(base.Client, routerID, routers.UpdateOpts{ - Name: "another_name", - }).Extract() - - th.AssertNoErr(t, err) -} - -func getRouter(t *testing.T, routerID string) { - r, err := routers.Get(base.Client, routerID).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Getting router: ID [%s] Name [%s] Status [%s]", r.ID, r.Name, r.Status) -} - -func addInterface(t *testing.T, routerID, subnetID string) { - ir, err := routers.AddInterface(base.Client, routerID, routers.InterfaceOpts{SubnetID: subnetID}).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Interface added to router %s: SubnetID [%s] PortID [%s]", routerID, ir.SubnetID, ir.PortID) -} - -func removeInterface(t *testing.T, routerID, subnetID string) { - ir, err := routers.RemoveInterface(base.Client, routerID, routers.InterfaceOpts{SubnetID: subnetID}).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Interface %s removed from %s", ir.ID, routerID) -} - -func deleteRouter(t *testing.T, routerID string) { - t.Logf("Deleting router %s", routerID) - - res := routers.Delete(base.Client, routerID) - - th.AssertNoErr(t, res.Err) -} - -func createFloatingIP(t *testing.T, networkID, portID string) string { - t.Logf("Creating floating IP on network [%s] with port [%s]", networkID, portID) - - opts := floatingips.CreateOpts{ - FloatingNetworkID: networkID, - PortID: portID, - } - - ip, err := floatingips.Create(base.Client, opts).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Floating IP created: ID [%s] Status [%s] Fixed (internal) IP: [%s] Floating (external) IP: [%s]", - ip.ID, ip.Status, ip.FixedIP, ip.FloatingIP) - - return ip.ID -} - -func getFloatingIP(t *testing.T, ipID string) { - ip, err := floatingips.Get(base.Client, ipID).Extract() - th.AssertNoErr(t, err) - - t.Logf("Getting floating IP: ID [%s] Status [%s]", ip.ID, ip.Status) -} - -func updateFloatingIP(t *testing.T, ipID, portID string) { - t.Logf("Disassociate all ports from IP %s", ipID) - _, err := floatingips.Update(base.Client, ipID, floatingips.UpdateOpts{PortID: ""}).Extract() - th.AssertNoErr(t, err) - - t.Logf("Re-associate the port %s", portID) - _, err = floatingips.Update(base.Client, ipID, floatingips.UpdateOpts{PortID: portID}).Extract() - th.AssertNoErr(t, err) -} - -func deleteFloatingIP(t *testing.T, ipID string) { - t.Logf("Deleting IP %s", ipID) - res := floatingips.Delete(base.Client, ipID) - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/member_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/member_test.go deleted file mode 100644 index 9b60582d140..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/member_test.go +++ /dev/null @@ -1,95 +0,0 @@ -// +build acceptance networking lbaas lbaasmember - -package lbaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestMembers(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // setup - networkID, subnetID := SetupTopology(t) - poolID := CreatePool(t, subnetID) - - // create member - memberID := createMember(t, poolID) - - // list members - listMembers(t) - - // update member - updateMember(t, memberID) - - // get member - getMember(t, memberID) - - // delete member - deleteMember(t, memberID) - - // teardown - DeletePool(t, poolID) - DeleteTopology(t, networkID) -} - -func createMember(t *testing.T, poolID string) string { - m, err := members.Create(base.Client, members.CreateOpts{ - Address: "192.168.199.1", - ProtocolPort: 8080, - PoolID: poolID, - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created member: ID [%s] Status [%s] Weight [%d] Address [%s] Port [%d]", - m.ID, m.Status, m.Weight, m.Address, m.ProtocolPort) - - return m.ID -} - -func listMembers(t *testing.T) { - err := members.List(base.Client, members.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - memberList, err := members.ExtractMembers(page) - if err != nil { - t.Errorf("Failed to extract members: %v", err) - return false, err - } - - for _, m := range memberList { - t.Logf("Listing member: ID [%s] Status [%s]", m.ID, m.Status) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updateMember(t *testing.T, memberID string) { - m, err := members.Update(base.Client, memberID, members.UpdateOpts{AdminStateUp: true}).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Updated member ID [%s]", m.ID) -} - -func getMember(t *testing.T, memberID string) { - m, err := members.Get(base.Client, memberID).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Getting member ID [%s]", m.ID) -} - -func deleteMember(t *testing.T, memberID string) { - res := members.Delete(base.Client, memberID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted member %s", memberID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/monitor_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/monitor_test.go deleted file mode 100644 index 9056fff671b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/monitor_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// +build acceptance networking lbaas lbaasmonitor - -package lbaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestMonitors(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // create monitor - monitorID := CreateMonitor(t) - - // list monitors - listMonitors(t) - - // update monitor - updateMonitor(t, monitorID) - - // get monitor - getMonitor(t, monitorID) - - // delete monitor - deleteMonitor(t, monitorID) -} - -func listMonitors(t *testing.T) { - err := monitors.List(base.Client, monitors.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - monitorList, err := monitors.ExtractMonitors(page) - if err != nil { - t.Errorf("Failed to extract monitors: %v", err) - return false, err - } - - for _, m := range monitorList { - t.Logf("Listing monitor: ID [%s] Type [%s] Delay [%ds] Timeout [%d] Retries [%d] Status [%s]", - m.ID, m.Type, m.Delay, m.Timeout, m.MaxRetries, m.Status) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updateMonitor(t *testing.T, monitorID string) { - opts := monitors.UpdateOpts{Delay: 10, Timeout: 10, MaxRetries: 3} - m, err := monitors.Update(base.Client, monitorID, opts).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Updated monitor ID [%s]", m.ID) -} - -func getMonitor(t *testing.T, monitorID string) { - m, err := monitors.Get(base.Client, monitorID).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Getting monitor ID [%s]: URL path [%s] HTTP Method [%s] Accepted codes [%s]", - m.ID, m.URLPath, m.HTTPMethod, m.ExpectedCodes) -} - -func deleteMonitor(t *testing.T, monitorID string) { - res := monitors.Delete(base.Client, monitorID) - - th.AssertNoErr(t, res.Err) - - t.Logf("Deleted monitor %s", monitorID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/pool_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/pool_test.go deleted file mode 100644 index 81940649c53..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/pool_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build acceptance networking lbaas lbaaspool - -package lbaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestPools(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // setup - networkID, subnetID := SetupTopology(t) - - // create pool - poolID := CreatePool(t, subnetID) - - // list pools - listPools(t) - - // update pool - updatePool(t, poolID) - - // get pool - getPool(t, poolID) - - // create monitor - monitorID := CreateMonitor(t) - - // associate health monitor - associateMonitor(t, poolID, monitorID) - - // disassociate health monitor - disassociateMonitor(t, poolID, monitorID) - - // delete pool - DeletePool(t, poolID) - - // teardown - DeleteTopology(t, networkID) -} - -func listPools(t *testing.T) { - err := pools.List(base.Client, pools.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - poolList, err := pools.ExtractPools(page) - if err != nil { - t.Errorf("Failed to extract pools: %v", err) - return false, err - } - - for _, p := range poolList { - t.Logf("Listing pool: ID [%s] Name [%s] Status [%s] LB algorithm [%s]", p.ID, p.Name, p.Status, p.LBMethod) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updatePool(t *testing.T, poolID string) { - opts := pools.UpdateOpts{Name: "SuperPool", LBMethod: pools.LBMethodLeastConnections} - p, err := pools.Update(base.Client, poolID, opts).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Updated pool ID [%s]", p.ID) -} - -func getPool(t *testing.T, poolID string) { - p, err := pools.Get(base.Client, poolID).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Getting pool ID [%s]", p.ID) -} - -func associateMonitor(t *testing.T, poolID, monitorID string) { - res := pools.AssociateMonitor(base.Client, poolID, monitorID) - - th.AssertNoErr(t, res.Err) - - t.Logf("Associated pool %s with monitor %s", poolID, monitorID) -} - -func disassociateMonitor(t *testing.T, poolID, monitorID string) { - res := pools.DisassociateMonitor(base.Client, poolID, monitorID) - - th.AssertNoErr(t, res.Err) - - t.Logf("Disassociated pool %s with monitor %s", poolID, monitorID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/vip_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/vip_test.go deleted file mode 100644 index c8dff2d93ff..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/lbaas/vip_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// +build acceptance networking lbaas lbaasvip - -package lbaas - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestVIPs(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // setup - networkID, subnetID := SetupTopology(t) - poolID := CreatePool(t, subnetID) - - // create VIP - VIPID := createVIP(t, subnetID, poolID) - - // list VIPs - listVIPs(t) - - // update VIP - updateVIP(t, VIPID) - - // get VIP - getVIP(t, VIPID) - - // delete VIP - deleteVIP(t, VIPID) - - // teardown - DeletePool(t, poolID) - DeleteTopology(t, networkID) -} - -func createVIP(t *testing.T, subnetID, poolID string) string { - p, err := vips.Create(base.Client, vips.CreateOpts{ - Protocol: "HTTP", - Name: "New_VIP", - AdminStateUp: vips.Up, - SubnetID: subnetID, - PoolID: poolID, - ProtocolPort: 80, - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created pool %s", p.ID) - - return p.ID -} - -func listVIPs(t *testing.T) { - err := vips.List(base.Client, vips.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - vipList, err := vips.ExtractVIPs(page) - if err != nil { - t.Errorf("Failed to extract VIPs: %v", err) - return false, err - } - - for _, vip := range vipList { - t.Logf("Listing VIP: ID [%s] Name [%s] Address [%s] Port [%s] Connection Limit [%d]", - vip.ID, vip.Name, vip.Address, vip.ProtocolPort, vip.ConnLimit) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func updateVIP(t *testing.T, VIPID string) { - i1000 := 1000 - _, err := vips.Update(base.Client, VIPID, vips.UpdateOpts{ConnLimit: &i1000}).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Updated VIP ID [%s]", VIPID) -} - -func getVIP(t *testing.T, VIPID string) { - vip, err := vips.Get(base.Client, VIPID).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Getting VIP ID [%s]: Status [%s]", vip.ID, vip.Status) -} - -func deleteVIP(t *testing.T, VIPID string) { - res := vips.Delete(base.Client, VIPID) - - th.AssertNoErr(t, res.Err) - - t.Logf("Deleted VIP %s", VIPID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/provider_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/provider_test.go deleted file mode 100644 index f10c9d9bd12..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/provider_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// +build acceptance networking - -package extensions - -import ( - "strconv" - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestNetworkCRUDOperations(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // Create a network - n, err := networks.Create(base.Client, networks.CreateOpts{Name: "sample_network", AdminStateUp: networks.Up}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Name, "sample_network") - th.AssertEquals(t, n.AdminStateUp, true) - networkID := n.ID - - // List networks - pager := networks.List(base.Client, networks.ListOpts{Limit: 2}) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - networkList, err := networks.ExtractNetworks(page) - th.AssertNoErr(t, err) - - for _, n := range networkList { - t.Logf("Network: ID [%s] Name [%s] Status [%s] Is shared? [%s]", - n.ID, n.Name, n.Status, strconv.FormatBool(n.Shared)) - } - - return true, nil - }) - th.CheckNoErr(t, err) - - // Get a network - if networkID == "" { - t.Fatalf("In order to retrieve a network, the NetworkID must be set") - } - n, err = networks.Get(base.Client, networkID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{}) - th.AssertEquals(t, n.Name, "sample_network") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.Shared, false) - th.AssertEquals(t, n.ID, networkID) - - // Update network - n, err = networks.Update(base.Client, networkID, networks.UpdateOpts{Name: "new_network_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Name, "new_network_name") - - // Delete network - res := networks.Delete(base.Client, networkID) - th.AssertNoErr(t, res.Err) -} - -func TestCreateMultipleNetworks(t *testing.T) { - //networks.CreateMany() -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/security_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/security_test.go deleted file mode 100644 index 7d75292f0de..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/extensions/security_test.go +++ /dev/null @@ -1,171 +0,0 @@ -// +build acceptance networking security - -package extensions - -import ( - "testing" - - base "github.com/rackspace/gophercloud/acceptance/openstack/networking/v2" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSecurityGroups(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // create security group - groupID := createSecGroup(t) - - // delete security group - defer deleteSecGroup(t, groupID) - - // list security group - listSecGroups(t) - - // get security group - getSecGroup(t, groupID) - - // create port with security group - networkID, portID := createPort(t, groupID) - - // teardown - defer deleteNetwork(t, networkID) - - // delete port - defer deletePort(t, portID) -} - -func TestSecurityGroupRules(t *testing.T) { - base.Setup(t) - defer base.Teardown() - - // create security group - groupID := createSecGroup(t) - - defer deleteSecGroup(t, groupID) - - // create security group rule - ruleID := createSecRule(t, groupID) - - // delete security group rule - defer deleteSecRule(t, ruleID) - - // list security group rule - listSecRules(t) - - // get security group rule - getSecRule(t, ruleID) -} - -func createSecGroup(t *testing.T) string { - sg, err := groups.Create(base.Client, groups.CreateOpts{ - Name: "new-webservers", - Description: "security group for webservers", - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created security group %s", sg.ID) - - return sg.ID -} - -func listSecGroups(t *testing.T) { - err := groups.List(base.Client, groups.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - list, err := groups.ExtractGroups(page) - if err != nil { - t.Errorf("Failed to extract secgroups: %v", err) - return false, err - } - - for _, sg := range list { - t.Logf("Listing security group: ID [%s] Name [%s]", sg.ID, sg.Name) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getSecGroup(t *testing.T, id string) { - sg, err := groups.Get(base.Client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting security group: ID [%s] Name [%s] Description [%s]", sg.ID, sg.Name, sg.Description) -} - -func createPort(t *testing.T, groupID string) (string, string) { - n, err := networks.Create(base.Client, networks.CreateOpts{Name: "tmp_network"}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created network %s", n.ID) - - opts := ports.CreateOpts{ - NetworkID: n.ID, - Name: "my_port", - SecurityGroups: []string{groupID}, - } - p, err := ports.Create(base.Client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created port %s with security group %s", p.ID, groupID) - - return n.ID, p.ID -} - -func deleteSecGroup(t *testing.T, groupID string) { - res := groups.Delete(base.Client, groupID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted security group %s", groupID) -} - -func createSecRule(t *testing.T, groupID string) string { - r, err := rules.Create(base.Client, rules.CreateOpts{ - Direction: "ingress", - PortRangeMin: 80, - EtherType: "IPv4", - PortRangeMax: 80, - Protocol: "tcp", - SecGroupID: groupID, - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created security group rule %s", r.ID) - - return r.ID -} - -func listSecRules(t *testing.T) { - err := rules.List(base.Client, rules.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - list, err := rules.ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract sec rules: %v", err) - return false, err - } - - for _, r := range list { - t.Logf("Listing security rule: ID [%s]", r.ID) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getSecRule(t *testing.T, id string) { - r, err := rules.Get(base.Client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting security rule: ID [%s] Direction [%s] EtherType [%s] Protocol [%s]", - r.ID, r.Direction, r.EtherType, r.Protocol) -} - -func deleteSecRule(t *testing.T, id string) { - res := rules.Delete(base.Client, id) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted security rule %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/network_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/network_test.go deleted file mode 100644 index be8a3a195a4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/network_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "strconv" - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestNetworkCRUDOperations(t *testing.T) { - Setup(t) - defer Teardown() - - // Create a network - n, err := networks.Create(Client, networks.CreateOpts{Name: "sample_network", AdminStateUp: networks.Up}).Extract() - th.AssertNoErr(t, err) - defer networks.Delete(Client, n.ID) - th.AssertEquals(t, n.Name, "sample_network") - th.AssertEquals(t, n.AdminStateUp, true) - networkID := n.ID - - // List networks - pager := networks.List(Client, networks.ListOpts{Limit: 2}) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - networkList, err := networks.ExtractNetworks(page) - th.AssertNoErr(t, err) - - for _, n := range networkList { - t.Logf("Network: ID [%s] Name [%s] Status [%s] Is shared? [%s]", - n.ID, n.Name, n.Status, strconv.FormatBool(n.Shared)) - } - - return true, nil - }) - th.CheckNoErr(t, err) - - // Get a network - if networkID == "" { - t.Fatalf("In order to retrieve a network, the NetworkID must be set") - } - n, err = networks.Get(Client, networkID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{}) - th.AssertEquals(t, n.Name, "sample_network") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.Shared, false) - th.AssertEquals(t, n.ID, networkID) - - // Update network - n, err = networks.Update(Client, networkID, networks.UpdateOpts{Name: "new_network_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, n.Name, "new_network_name") - - // Delete network - res := networks.Delete(Client, networkID) - th.AssertNoErr(t, res.Err) -} - -func TestCreateMultipleNetworks(t *testing.T) { - //networks.CreateMany() -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/port_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/port_test.go deleted file mode 100644 index 03e8e278428..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/port_test.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestPortCRUD(t *testing.T) { - Setup(t) - defer Teardown() - - // Setup network - t.Log("Setting up network") - networkID, err := createNetwork() - th.AssertNoErr(t, err) - defer networks.Delete(Client, networkID) - - // Setup subnet - t.Logf("Setting up subnet on network %s", networkID) - subnetID, err := createSubnet(networkID) - th.AssertNoErr(t, err) - defer subnets.Delete(Client, subnetID) - - // Create port - t.Logf("Create port based on subnet %s", subnetID) - portID := createPort(t, networkID, subnetID) - - // List ports - t.Logf("Listing all ports") - listPorts(t) - - // Get port - if portID == "" { - t.Fatalf("In order to retrieve a port, the portID must be set") - } - p, err := ports.Get(Client, portID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, p.ID, portID) - - // Update port - p, err = ports.Update(Client, portID, ports.UpdateOpts{Name: "new_port_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, p.Name, "new_port_name") - - // Delete port - res := ports.Delete(Client, portID) - th.AssertNoErr(t, res.Err) -} - -func createPort(t *testing.T, networkID, subnetID string) string { - enable := false - opts := ports.CreateOpts{ - NetworkID: networkID, - Name: "my_port", - AdminStateUp: &enable, - FixedIPs: []ports.IP{ports.IP{SubnetID: subnetID}}, - } - p, err := ports.Create(Client, opts).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, p.NetworkID, networkID) - th.AssertEquals(t, p.Name, "my_port") - th.AssertEquals(t, p.AdminStateUp, false) - - return p.ID -} - -func listPorts(t *testing.T) { - count := 0 - pager := ports.List(Client, ports.ListOpts{}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("--- Page ---") - - portList, err := ports.ExtractPorts(page) - th.AssertNoErr(t, err) - - for _, p := range portList { - t.Logf("Port: ID [%s] Name [%s] Status [%s] MAC addr [%s] Fixed IPs [%#v] Security groups [%#v]", - p.ID, p.Name, p.Status, p.MACAddress, p.FixedIPs, p.SecurityGroups) - } - - return true, nil - }) - - th.CheckNoErr(t, err) - - if count == 0 { - t.Logf("No pages were iterated over when listing ports") - } -} - -func createNetwork() (string, error) { - res, err := networks.Create(Client, networks.CreateOpts{Name: "tmp_network", AdminStateUp: networks.Up}).Extract() - return res.ID, err -} - -func createSubnet(networkID string) (string, error) { - s, err := subnets.Create(Client, subnets.CreateOpts{ - NetworkID: networkID, - CIDR: "192.168.199.0/24", - IPVersion: subnets.IPv4, - Name: "my_subnet", - EnableDHCP: subnets.Down, - }).Extract() - return s.ID, err -} - -func TestPortBatchCreate(t *testing.T) { - // todo -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/subnet_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/subnet_test.go deleted file mode 100644 index 097a303edee..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/networking/v2/subnet_test.go +++ /dev/null @@ -1,86 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - Setup(t) - defer Teardown() - - pager := subnets.List(Client, subnets.ListOpts{Limit: 2}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - subnetList, err := subnets.ExtractSubnets(page) - th.AssertNoErr(t, err) - - for _, s := range subnetList { - t.Logf("Subnet: ID [%s] Name [%s] IP Version [%d] CIDR [%s] GatewayIP [%s]", - s.ID, s.Name, s.IPVersion, s.CIDR, s.GatewayIP) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} - -func TestCRUD(t *testing.T) { - Setup(t) - defer Teardown() - - // Setup network - t.Log("Setting up network") - n, err := networks.Create(Client, networks.CreateOpts{Name: "tmp_network", AdminStateUp: networks.Up}).Extract() - th.AssertNoErr(t, err) - networkID := n.ID - defer networks.Delete(Client, networkID) - - // Create subnet - t.Log("Create subnet") - enable := false - opts := subnets.CreateOpts{ - NetworkID: networkID, - CIDR: "192.168.199.0/24", - IPVersion: subnets.IPv4, - Name: "my_subnet", - EnableDHCP: &enable, - } - s, err := subnets.Create(Client, opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.NetworkID, networkID) - th.AssertEquals(t, s.CIDR, "192.168.199.0/24") - th.AssertEquals(t, s.IPVersion, 4) - th.AssertEquals(t, s.Name, "my_subnet") - th.AssertEquals(t, s.EnableDHCP, false) - subnetID := s.ID - - // Get subnet - t.Log("Getting subnet") - s, err = subnets.Get(Client, subnetID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, s.ID, subnetID) - - // Update subnet - t.Log("Update subnet") - s, err = subnets.Update(Client, subnetID, subnets.UpdateOpts{Name: "new_subnet_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, s.Name, "new_subnet_name") - - // Delete subnet - t.Log("Delete subnet") - res := subnets.Delete(Client, subnetID) - th.AssertNoErr(t, res.Err) -} - -func TestBatchCreate(t *testing.T) { - // todo -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/accounts_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/accounts_test.go deleted file mode 100644 index 24cc62b4aa0..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/accounts_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "strings" - "testing" - - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAccounts(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - // Update an account's metadata. - updateres := accounts.Update(client, accounts.UpdateOpts{Metadata: metadata}) - t.Logf("Update Account Response: %+v\n", updateres) - updateHeaders, err := updateres.Extract() - th.AssertNoErr(t, err) - t.Logf("Update Account Response Headers: %+v\n", updateHeaders) - - // Defer the deletion of the metadata set above. - defer func() { - tempMap := make(map[string]string) - for k := range metadata { - tempMap[k] = "" - } - updateres = accounts.Update(client, accounts.UpdateOpts{Metadata: tempMap}) - th.AssertNoErr(t, updateres.Err) - }() - - // Extract the custom metadata from the 'Get' response. - res := accounts.Get(client, nil) - - h, err := res.Extract() - th.AssertNoErr(t, err) - t.Logf("Get Account Response Headers: %+v\n", h) - - am, err := res.ExtractMetadata() - th.AssertNoErr(t, err) - for k := range metadata { - if am[k] != metadata[strings.Title(k)] { - t.Errorf("Expected custom metadata with key: %s", k) - return - } - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/containers_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/containers_test.go deleted file mode 100644 index 8328a4fa6f1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/containers_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "strings" - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -// numContainers is the number of containers to create for testing. -var numContainers = 2 - -func TestContainers(t *testing.T) { - // Create a new client to execute the HTTP requests. See common.go for newClient body. - client := newClient(t) - - // Create a slice of random container names. - cNames := make([]string, numContainers) - for i := 0; i < numContainers; i++ { - cNames[i] = tools.RandomString("gophercloud-test-container-", 8) - } - - // Create numContainers containers. - for i := 0; i < len(cNames); i++ { - res := containers.Create(client, cNames[i], nil) - th.AssertNoErr(t, res.Err) - } - // Delete the numContainers containers after function completion. - defer func() { - for i := 0; i < len(cNames); i++ { - res := containers.Delete(client, cNames[i]) - th.AssertNoErr(t, res.Err) - } - }() - - // List the numContainer names that were just created. To just list those, - // the 'prefix' parameter is used. - err := containers.List(client, &containers.ListOpts{Full: true, Prefix: "gophercloud-test-container-"}).EachPage(func(page pagination.Page) (bool, error) { - containerList, err := containers.ExtractInfo(page) - th.AssertNoErr(t, err) - - for _, n := range containerList { - t.Logf("Container: Name [%s] Count [%d] Bytes [%d]", - n.Name, n.Count, n.Bytes) - } - - return true, nil - }) - th.AssertNoErr(t, err) - - // List the info for the numContainer containers that were created. - err = containers.List(client, &containers.ListOpts{Full: false, Prefix: "gophercloud-test-container-"}).EachPage(func(page pagination.Page) (bool, error) { - containerList, err := containers.ExtractNames(page) - th.AssertNoErr(t, err) - for _, n := range containerList { - t.Logf("Container: Name [%s]", n) - } - - return true, nil - }) - th.AssertNoErr(t, err) - - // Update one of the numContainer container metadata. - updateres := containers.Update(client, cNames[0], &containers.UpdateOpts{Metadata: metadata}) - th.AssertNoErr(t, updateres.Err) - // After the tests are done, delete the metadata that was set. - defer func() { - tempMap := make(map[string]string) - for k := range metadata { - tempMap[k] = "" - } - res := containers.Update(client, cNames[0], &containers.UpdateOpts{Metadata: tempMap}) - th.AssertNoErr(t, res.Err) - }() - - // Retrieve a container's metadata. - cm, err := containers.Get(client, cNames[0]).ExtractMetadata() - th.AssertNoErr(t, err) - for k := range metadata { - if cm[k] != metadata[strings.Title(k)] { - t.Errorf("Expected custom metadata with key: %s", k) - } - } -} - -func TestListAllContainers(t *testing.T) { - // Create a new client to execute the HTTP requests. See common.go for newClient body. - client := newClient(t) - - numContainers := 20 - - // Create a slice of random container names. - cNames := make([]string, numContainers) - for i := 0; i < numContainers; i++ { - cNames[i] = tools.RandomString("gophercloud-test-container-", 8) - } - - // Create numContainers containers. - for i := 0; i < len(cNames); i++ { - res := containers.Create(client, cNames[i], nil) - th.AssertNoErr(t, res.Err) - } - // Delete the numContainers containers after function completion. - defer func() { - for i := 0; i < len(cNames); i++ { - res := containers.Delete(client, cNames[i]) - th.AssertNoErr(t, res.Err) - } - }() - - // List all the numContainer names that were just created. To just list those, - // the 'prefix' parameter is used. - allPages, err := containers.List(client, &containers.ListOpts{Full: true, Limit: 5, Prefix: "gophercloud-test-container-"}).AllPages() - th.AssertNoErr(t, err) - containerInfoList, err := containers.ExtractInfo(allPages) - th.AssertNoErr(t, err) - for _, n := range containerInfoList { - t.Logf("Container: Name [%s] Count [%d] Bytes [%d]", - n.Name, n.Count, n.Bytes) - } - th.AssertEquals(t, numContainers, len(containerInfoList)) - - // List the info for all the numContainer containers that were created. - allPages, err = containers.List(client, &containers.ListOpts{Full: false, Limit: 2, Prefix: "gophercloud-test-container-"}).AllPages() - th.AssertNoErr(t, err) - containerNamesList, err := containers.ExtractNames(allPages) - th.AssertNoErr(t, err) - for _, n := range containerNamesList { - t.Logf("Container: Name [%s]", n) - } - th.AssertEquals(t, numContainers, len(containerNamesList)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/objects_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/objects_test.go deleted file mode 100644 index a8de338c3dd..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/objectstorage/v1/objects_test.go +++ /dev/null @@ -1,119 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "bytes" - "strings" - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -// numObjects is the number of objects to create for testing. -var numObjects = 2 - -func TestObjects(t *testing.T) { - // Create a provider client for executing the HTTP request. - // See common.go for more information. - client := newClient(t) - - // Make a slice of length numObjects to hold the random object names. - oNames := make([]string, numObjects) - for i := 0; i < len(oNames); i++ { - oNames[i] = tools.RandomString("test-object-", 8) - } - - // Create a container to hold the test objects. - cName := tools.RandomString("test-container-", 8) - header, err := containers.Create(client, cName, nil).ExtractHeader() - th.AssertNoErr(t, err) - t.Logf("Create object headers: %+v\n", header) - - // Defer deletion of the container until after testing. - defer func() { - res := containers.Delete(client, cName) - th.AssertNoErr(t, res.Err) - }() - - // Create a slice of buffers to hold the test object content. - oContents := make([]*bytes.Buffer, numObjects) - for i := 0; i < numObjects; i++ { - oContents[i] = bytes.NewBuffer([]byte(tools.RandomString("", 10))) - res := objects.Create(client, cName, oNames[i], oContents[i], nil) - th.AssertNoErr(t, res.Err) - } - // Delete the objects after testing. - defer func() { - for i := 0; i < numObjects; i++ { - res := objects.Delete(client, cName, oNames[i], nil) - th.AssertNoErr(t, res.Err) - } - }() - - ons := make([]string, 0, len(oNames)) - err = objects.List(client, cName, &objects.ListOpts{Full: false, Prefix: "test-object-"}).EachPage(func(page pagination.Page) (bool, error) { - names, err := objects.ExtractNames(page) - th.AssertNoErr(t, err) - ons = append(ons, names...) - - return true, nil - }) - th.AssertNoErr(t, err) - th.AssertEquals(t, len(ons), len(oNames)) - - ois := make([]objects.Object, 0, len(oNames)) - err = objects.List(client, cName, &objects.ListOpts{Full: true, Prefix: "test-object-"}).EachPage(func(page pagination.Page) (bool, error) { - info, err := objects.ExtractInfo(page) - th.AssertNoErr(t, err) - - ois = append(ois, info...) - - return true, nil - }) - th.AssertNoErr(t, err) - th.AssertEquals(t, len(ois), len(oNames)) - - // Copy the contents of one object to another. - copyres := objects.Copy(client, cName, oNames[0], &objects.CopyOpts{Destination: cName + "/" + oNames[1]}) - th.AssertNoErr(t, copyres.Err) - - // Download one of the objects that was created above. - o1Content, err := objects.Download(client, cName, oNames[0], nil).ExtractContent() - th.AssertNoErr(t, err) - - // Download the another object that was create above. - o2Content, err := objects.Download(client, cName, oNames[1], nil).ExtractContent() - th.AssertNoErr(t, err) - - // Compare the two object's contents to test that the copy worked. - th.AssertEquals(t, string(o2Content), string(o1Content)) - - // Update an object's metadata. - updateres := objects.Update(client, cName, oNames[0], &objects.UpdateOpts{Metadata: metadata}) - th.AssertNoErr(t, updateres.Err) - - // Delete the object's metadata after testing. - defer func() { - tempMap := make(map[string]string) - for k := range metadata { - tempMap[k] = "" - } - res := objects.Update(client, cName, oNames[0], &objects.UpdateOpts{Metadata: tempMap}) - th.AssertNoErr(t, res.Err) - }() - - // Retrieve an object's metadata. - om, err := objects.Get(client, cName, oNames[0], nil).ExtractMetadata() - th.AssertNoErr(t, err) - for k := range metadata { - if om[k] != metadata[strings.Title(k)] { - t.Errorf("Expected custom metadata with key: %s", k) - return - } - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/buildinfo_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/buildinfo_test.go deleted file mode 100644 index 05a5e1d67ec..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/buildinfo_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBuildInfo(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - bi, err := buildinfo.Get(client).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved build info: %+v\n", bi) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackevents_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackevents_test.go deleted file mode 100644 index e356c86aa9d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackevents_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackEvents(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - resourceName := "hello_world" - var eventID string - - createOpts := stacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - err = stackevents.List(client, stackName, stack.ID, nil).EachPage(func(page pagination.Page) (bool, error) { - events, err := stackevents.ExtractEvents(page) - th.AssertNoErr(t, err) - t.Logf("listed events: %+v\n", events) - eventID = events[0].ID - return false, nil - }) - th.AssertNoErr(t, err) - - err = stackevents.ListResourceEvents(client, stackName, stack.ID, resourceName, nil).EachPage(func(page pagination.Page) (bool, error) { - resourceEvents, err := stackevents.ExtractEvents(page) - th.AssertNoErr(t, err) - t.Logf("listed resource events: %+v\n", resourceEvents) - return false, nil - }) - th.AssertNoErr(t, err) - - event, err := stackevents.Get(client, stackName, stack.ID, resourceName, eventID).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved event: %+v\n", event) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackresources_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackresources_test.go deleted file mode 100644 index b614f1cef5f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stackresources_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackResources(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - - createOpts := stacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - resourceName := "hello_world" - resource, err := stackresources.Get(client, stackName, stack.ID, resourceName).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack resource: %+v\n", resource) - - metadata, err := stackresources.Metadata(client, stackName, stack.ID, resourceName).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack resource metadata: %+v\n", metadata) - - err = stackresources.List(client, stackName, stack.ID, stackresources.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - resources, err := stackresources.ExtractResources(page) - th.AssertNoErr(t, err) - t.Logf("resources: %+v\n", resources) - return false, nil - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacks_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacks_test.go deleted file mode 100644 index 01e76d61403..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacks_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStacks(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName1 := "gophercloud-test-stack-2" - createOpts := stacks.CreateOpts{ - Name: stackName1, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName1, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName1) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - updateOpts := stacks.UpdateOpts{ - Template: template, - Timeout: 20, - } - err = stacks.Update(client, stackName1, stack.ID, updateOpts).ExtractErr() - th.AssertNoErr(t, err) - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "UPDATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - t.Logf("Updated stack") - - err = stacks.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - stackList, err := stacks.ExtractStacks(page) - th.AssertNoErr(t, err) - - t.Logf("Got stack list: %+v\n", stackList) - - return true, nil - }) - th.AssertNoErr(t, err) - - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack: %+v\n", getStack) - - abandonedStack, err := stacks.Abandon(client, stackName1, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Abandonded stack %+v\n", abandonedStack) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacktemplates_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacktemplates_test.go deleted file mode 100644 index 14d8f4437ae..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/orchestration/v1/stacktemplates_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackTemplates(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - - createOpts := stacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - tmpl, err := stacktemplates.Get(client, stackName, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved template: %+v\n", tmpl) - - validateOpts := stacktemplates.ValidateOpts{ - Template: map[string]interface{}{ - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": map[string]interface{}{ - "flavor": map[string]interface{}{ - "default": "m1.tiny", - "type": "string", - }, - }, - "resources": map[string]interface{}{ - "hello_world": map[string]interface{}{ - "type": "OS::Nova::Server", - "properties": map[string]interface{}{ - "key_name": "heat_key", - "flavor": map[string]interface{}{ - "get_param": "flavor", - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n", - }, - }, - }, - }, - } - validatedTemplate, err := stacktemplates.Validate(client, validateOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("validated template: %+v\n", validatedTemplate) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/snapshot_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/snapshot_test.go deleted file mode 100644 index 25b2cfeeeb2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/snapshot_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// +build acceptance blockstorage snapshots - -package v1 - -import ( - "testing" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/snapshots" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSnapshots(t *testing.T) { - client := setup(t) - volID := testVolumeCreate(t, client) - - t.Log("Creating snapshots") - s := testSnapshotCreate(t, client, volID) - id := s.ID - - t.Log("Listing snapshots") - testSnapshotList(t, client) - - t.Logf("Getting snapshot %s", id) - testSnapshotGet(t, client, id) - - t.Logf("Updating snapshot %s", id) - testSnapshotUpdate(t, client, id) - - t.Logf("Deleting snapshot %s", id) - testSnapshotDelete(t, client, id) - s.WaitUntilDeleted(client, -1) - - t.Logf("Deleting volume %s", volID) - testVolumeDelete(t, client, volID) -} - -func testSnapshotCreate(t *testing.T, client *gophercloud.ServiceClient, volID string) *snapshots.Snapshot { - opts := snapshots.CreateOpts{VolumeID: volID, Name: "snapshot-001"} - s, err := snapshots.Create(client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created snapshot %s", s.ID) - - t.Logf("Waiting for new snapshot to become available...") - start := time.Now().Second() - s.WaitUntilComplete(client, -1) - t.Logf("Snapshot completed after %ds", time.Now().Second()-start) - - return s -} - -func testSnapshotList(t *testing.T, client *gophercloud.ServiceClient) { - snapshots.List(client).EachPage(func(page pagination.Page) (bool, error) { - sList, err := snapshots.ExtractSnapshots(page) - th.AssertNoErr(t, err) - - for _, s := range sList { - t.Logf("Snapshot: ID [%s] Name [%s] Volume ID [%s] Progress [%s] Created [%s]", - s.ID, s.Name, s.VolumeID, s.Progress, s.CreatedAt) - } - - return true, nil - }) -} - -func testSnapshotGet(t *testing.T, client *gophercloud.ServiceClient, id string) { - _, err := snapshots.Get(client, id).Extract() - th.AssertNoErr(t, err) -} - -func testSnapshotUpdate(t *testing.T, client *gophercloud.ServiceClient, id string) { - _, err := snapshots.Update(client, id, snapshots.UpdateOpts{Name: "new_name"}).Extract() - th.AssertNoErr(t, err) -} - -func testSnapshotDelete(t *testing.T, client *gophercloud.ServiceClient, id string) { - res := snapshots.Delete(client, id) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted snapshot %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_test.go deleted file mode 100644 index f86f9adedd3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// +build acceptance blockstorage volumes - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestVolumes(t *testing.T) { - client := setup(t) - - t.Logf("Listing volumes") - testVolumeList(t, client) - - t.Logf("Creating volume") - volumeID := testVolumeCreate(t, client) - - t.Logf("Getting volume %s", volumeID) - testVolumeGet(t, client, volumeID) - - t.Logf("Updating volume %s", volumeID) - testVolumeUpdate(t, client, volumeID) - - t.Logf("Deleting volume %s", volumeID) - testVolumeDelete(t, client, volumeID) -} - -func testVolumeList(t *testing.T, client *gophercloud.ServiceClient) { - volumes.List(client).EachPage(func(page pagination.Page) (bool, error) { - vList, err := volumes.ExtractVolumes(page) - th.AssertNoErr(t, err) - - for _, v := range vList { - t.Logf("Volume: ID [%s] Name [%s] Type [%s] Created [%s]", v.ID, v.Name, - v.VolumeType, v.CreatedAt) - } - - return true, nil - }) -} - -func testVolumeCreate(t *testing.T, client *gophercloud.ServiceClient) string { - vol, err := volumes.Create(client, os.CreateOpts{Size: 75}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created volume: ID [%s] Size [%s]", vol.ID, vol.Size) - return vol.ID -} - -func testVolumeGet(t *testing.T, client *gophercloud.ServiceClient, id string) { - vol, err := volumes.Get(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Created volume: ID [%s] Size [%s]", vol.ID, vol.Size) -} - -func testVolumeUpdate(t *testing.T, client *gophercloud.ServiceClient, id string) { - vol, err := volumes.Update(client, id, volumes.UpdateOpts{Name: "new_name"}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created volume: ID [%s] Name [%s]", vol.ID, vol.Name) -} - -func testVolumeDelete(t *testing.T, client *gophercloud.ServiceClient, id string) { - res := volumes.Delete(client, id) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted volume %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_type_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_type_test.go deleted file mode 100644 index 716f2b9fd5b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/blockstorage/v1/volume_type_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build acceptance blockstorage volumetypes - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumetypes" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAll(t *testing.T) { - client := setup(t) - - t.Logf("Listing volume types") - id := testList(t, client) - - t.Logf("Getting volume type %s", id) - testGet(t, client, id) -} - -func testList(t *testing.T, client *gophercloud.ServiceClient) string { - var lastID string - - volumetypes.List(client).EachPage(func(page pagination.Page) (bool, error) { - typeList, err := volumetypes.ExtractVolumeTypes(page) - th.AssertNoErr(t, err) - - for _, vt := range typeList { - t.Logf("Volume type: ID [%s] Name [%s]", vt.ID, vt.Name) - lastID = vt.ID - } - - return true, nil - }) - - return lastID -} - -func testGet(t *testing.T, client *gophercloud.ServiceClient, id string) { - vt, err := volumetypes.Get(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Volume: ID [%s] Name [%s]", vt.ID, vt.Name) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/base_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/base_test.go deleted file mode 100644 index 135f5b330af..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/base_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/cdn/v1/base" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBaseOps(t *testing.T) { - client := newClient(t) - t.Log("Retrieving Home Document") - testHomeDocumentGet(t, client) - - t.Log("Pinging root URL") - testPing(t, client) -} - -func testHomeDocumentGet(t *testing.T, client *gophercloud.ServiceClient) { - hd, err := base.Get(client).Extract() - th.AssertNoErr(t, err) - t.Logf("Retrieved home document: %+v", *hd) -} - -func testPing(t *testing.T, client *gophercloud.ServiceClient) { - err := base.Ping(client).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Successfully pinged root URL") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/flavor_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/flavor_test.go deleted file mode 100644 index f26cff0140c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/flavor_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/cdn/v1/flavors" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/cdn/v1/flavors" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestFlavor(t *testing.T) { - client := newClient(t) - - t.Log("Listing Flavors") - id := testFlavorsList(t, client) - - t.Log("Retrieving Flavor") - testFlavorGet(t, client, id) -} - -func testFlavorsList(t *testing.T, client *gophercloud.ServiceClient) string { - var id string - err := flavors.List(client).EachPage(func(page pagination.Page) (bool, error) { - flavorList, err := os.ExtractFlavors(page) - th.AssertNoErr(t, err) - - for _, flavor := range flavorList { - t.Logf("Listing flavor: ID [%s] Providers [%+v]", flavor.ID, flavor.Providers) - id = flavor.ID - } - - return true, nil - }) - - th.AssertNoErr(t, err) - return id -} - -func testFlavorGet(t *testing.T, client *gophercloud.ServiceClient, id string) { - flavor, err := flavors.Get(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Retrieved Flavor: %+v", *flavor) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/service_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/service_test.go deleted file mode 100644 index c19c241c364..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/service_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/cdn/v1/services" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/cdn/v1/services" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestService(t *testing.T) { - client := newClient(t) - - t.Log("Creating Service") - loc := testServiceCreate(t, client, "test-site-1") - t.Logf("Created service at location: %s", loc) - - defer testServiceDelete(t, client, loc) - - t.Log("Updating Service") - testServiceUpdate(t, client, loc) - - t.Log("Retrieving Service") - testServiceGet(t, client, loc) - - t.Log("Listing Services") - testServiceList(t, client) -} - -func testServiceCreate(t *testing.T, client *gophercloud.ServiceClient, name string) string { - createOpts := os.CreateOpts{ - Name: name, - Domains: []os.Domain{ - os.Domain{ - Domain: "www." + name + ".com", - }, - }, - Origins: []os.Origin{ - os.Origin{ - Origin: name + ".com", - Port: 80, - SSL: false, - }, - }, - FlavorID: "cdn", - } - l, err := services.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - return l -} - -func testServiceGet(t *testing.T, client *gophercloud.ServiceClient, id string) { - s, err := services.Get(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Retrieved service: %+v", *s) -} - -func testServiceUpdate(t *testing.T, client *gophercloud.ServiceClient, id string) { - opts := os.UpdateOpts{ - os.Append{ - Value: os.Domain{Domain: "newDomain.com", Protocol: "http"}, - }, - } - - loc, err := services.Update(client, id, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Successfully updated service at location: %s", loc) -} - -func testServiceList(t *testing.T, client *gophercloud.ServiceClient) { - err := services.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - serviceList, err := os.ExtractServices(page) - th.AssertNoErr(t, err) - - for _, service := range serviceList { - t.Logf("Listing service: %+v", service) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func testServiceDelete(t *testing.T, client *gophercloud.ServiceClient, id string) { - err := services.Delete(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Successfully deleted service (%s)", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/serviceasset_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/serviceasset_test.go deleted file mode 100644 index c32bf253da2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/cdn/v1/serviceasset_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - osServiceAssets "github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets" - "github.com/rackspace/gophercloud/rackspace/cdn/v1/serviceassets" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestServiceAsset(t *testing.T) { - client := newClient(t) - - t.Log("Creating Service") - loc := testServiceCreate(t, client, "test-site-2") - t.Logf("Created service at location: %s", loc) - - t.Log("Deleting Service Assets") - testServiceAssetDelete(t, client, loc) -} - -func testServiceAssetDelete(t *testing.T, client *gophercloud.ServiceClient, url string) { - deleteOpts := osServiceAssets.DeleteOpts{ - All: true, - } - err := serviceassets.Delete(client, url, deleteOpts).ExtractErr() - th.AssertNoErr(t, err) - t.Log("Successfully deleted all Service Assets") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/client_test.go deleted file mode 100644 index 61214c047a9..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/client_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build acceptance - -package rackspace - -import ( - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/rackspace" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAuthenticatedClient(t *testing.T) { - // Obtain credentials from the environment. - ao, err := rackspace.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - client, err := rackspace.AuthenticatedClient(tools.OnlyRS(ao)) - if err != nil { - t.Fatalf("Unable to authenticate: %v", err) - } - - if client.TokenID == "" { - t.Errorf("No token ID assigned to the client") - } - - t.Logf("Client successfully acquired a token: %v", client.TokenID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/bootfromvolume_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/bootfromvolume_test.go deleted file mode 100644 index d7e6aa712c1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/bootfromvolume_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/acceptance/tools" - osBFV "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume" - "github.com/rackspace/gophercloud/rackspace/compute/v2/bootfromvolume" - "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBootFromVolume(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - options, err := optionsFromEnv() - th.AssertNoErr(t, err) - - name := tools.RandomString("Gophercloud-", 8) - t.Logf("Creating server [%s].", name) - - bd := []osBFV.BlockDevice{ - osBFV.BlockDevice{ - UUID: options.imageID, - SourceType: osBFV.Image, - VolumeSize: 10, - }, - } - - server, err := bootfromvolume.Create(client, servers.CreateOpts{ - Name: name, - FlavorRef: "performance1-1", - BlockDevice: bd, - }).Extract() - th.AssertNoErr(t, err) - t.Logf("Created server: %+v\n", server) - defer deleteServer(t, client, server) - - getServer(t, client, server) - - listServers(t, client) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/compute_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/compute_test.go deleted file mode 100644 index 3ca6dc9b6c8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/compute_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "errors" - "os" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/rackspace" -) - -func newClient() (*gophercloud.ServiceClient, error) { - // Obtain credentials from the environment. - options, err := rackspace.AuthOptionsFromEnv() - if err != nil { - return nil, err - } - options = tools.OnlyRS(options) - region := os.Getenv("RS_REGION") - - if options.Username == "" { - return nil, errors.New("Please provide a Rackspace username as RS_USERNAME.") - } - if options.APIKey == "" { - return nil, errors.New("Please provide a Rackspace API key as RS_API_KEY.") - } - if region == "" { - return nil, errors.New("Please provide a Rackspace region as RS_REGION.") - } - - client, err := rackspace.AuthenticatedClient(options) - if err != nil { - return nil, err - } - - return rackspace.NewComputeV2(client, gophercloud.EndpointOpts{ - Region: region, - }) -} - -type serverOpts struct { - imageID string - flavorID string -} - -func optionsFromEnv() (*serverOpts, error) { - options := &serverOpts{ - imageID: os.Getenv("RS_IMAGE_ID"), - flavorID: os.Getenv("RS_FLAVOR_ID"), - } - if options.imageID == "" { - return nil, errors.New("Please provide a valid Rackspace image ID as RS_IMAGE_ID") - } - if options.flavorID == "" { - return nil, errors.New("Please provide a valid Rackspace flavor ID as RS_FLAVOR_ID") - } - return options, nil -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/flavors_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/flavors_test.go deleted file mode 100644 index 4618ecc8a9b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/flavors_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/flavors" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListFlavors(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - count := 0 - err = flavors.ListDetail(client, nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("-- Page %0d --", count) - - fs, err := flavors.ExtractFlavors(page) - th.AssertNoErr(t, err) - - for i, flavor := range fs { - t.Logf("[%02d] id=[%s]", i, flavor.ID) - t.Logf(" name=[%s]", flavor.Name) - t.Logf(" disk=[%d]", flavor.Disk) - t.Logf(" RAM=[%d]", flavor.RAM) - t.Logf(" rxtx_factor=[%f]", flavor.RxTxFactor) - t.Logf(" swap=[%d]", flavor.Swap) - t.Logf(" VCPUs=[%d]", flavor.VCPUs) - } - - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No flavors listed!") - } -} - -func TestGetFlavor(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - options, err := optionsFromEnv() - th.AssertNoErr(t, err) - - flavor, err := flavors.Get(client, options.flavorID).Extract() - th.AssertNoErr(t, err) - - t.Logf("Requested flavor:") - t.Logf(" id=[%s]", flavor.ID) - t.Logf(" name=[%s]", flavor.Name) - t.Logf(" disk=[%d]", flavor.Disk) - t.Logf(" RAM=[%d]", flavor.RAM) - t.Logf(" rxtx_factor=[%f]", flavor.RxTxFactor) - t.Logf(" swap=[%d]", flavor.Swap) - t.Logf(" VCPUs=[%d]", flavor.VCPUs) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/images_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/images_test.go deleted file mode 100644 index 5e36c2e4545..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/images_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/images" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListImages(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - count := 0 - err = images.ListDetail(client, nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("-- Page %02d --", count) - - is, err := images.ExtractImages(page) - th.AssertNoErr(t, err) - - for i, image := range is { - t.Logf("[%02d] id=[%s]", i, image.ID) - t.Logf(" name=[%s]", image.Name) - t.Logf(" created=[%s]", image.Created) - t.Logf(" updated=[%s]", image.Updated) - t.Logf(" min disk=[%d]", image.MinDisk) - t.Logf(" min RAM=[%d]", image.MinRAM) - t.Logf(" progress=[%d]", image.Progress) - t.Logf(" status=[%s]", image.Status) - } - - return true, nil - }) - th.AssertNoErr(t, err) - if count < 1 { - t.Errorf("Expected at least one page of images.") - } -} - -func TestGetImage(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - options, err := optionsFromEnv() - th.AssertNoErr(t, err) - - image, err := images.Get(client, options.imageID).Extract() - th.AssertNoErr(t, err) - - t.Logf("Requested image:") - t.Logf(" id=[%s]", image.ID) - t.Logf(" name=[%s]", image.Name) - t.Logf(" created=[%s]", image.Created) - t.Logf(" updated=[%s]", image.Updated) - t.Logf(" min disk=[%d]", image.MinDisk) - t.Logf(" min RAM=[%d]", image.MinRAM) - t.Logf(" progress=[%d]", image.Progress) - t.Logf(" status=[%s]", image.Status) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/keypairs_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/keypairs_test.go deleted file mode 100644 index 9bd6eb42848..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/keypairs_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// +build acceptance rackspace - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - os "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs" - th "github.com/rackspace/gophercloud/testhelper" -) - -func deleteKeyPair(t *testing.T, client *gophercloud.ServiceClient, name string) { - err := keypairs.Delete(client, name).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Successfully deleted key [%s].", name) -} - -func TestCreateKeyPair(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - name := tools.RandomString("createdkey-", 8) - k, err := keypairs.Create(client, os.CreateOpts{Name: name}).Extract() - th.AssertNoErr(t, err) - defer deleteKeyPair(t, client, name) - - t.Logf("Created a new keypair:") - t.Logf(" name=[%s]", k.Name) - t.Logf(" fingerprint=[%s]", k.Fingerprint) - t.Logf(" publickey=[%s]", tools.Elide(k.PublicKey)) - t.Logf(" privatekey=[%s]", tools.Elide(k.PrivateKey)) - t.Logf(" userid=[%s]", k.UserID) -} - -func TestImportKeyPair(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - name := tools.RandomString("importedkey-", 8) - pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDlIQ3r+zd97kb9Hzmujd3V6pbO53eb3Go4q2E8iqVGWQfZTrFdL9KACJnqJIm9HmncfRkUTxE37hqeGCCv8uD+ZPmPiZG2E60OX1mGDjbbzAyReRwYWXgXHopggZTLak5k4mwZYaxwaufbVBDRn847e01lZnaXaszEToLM37NLw+uz29sl3TwYy2R0RGHPwPc160aWmdLjSyd1Nd4c9pvvOP/EoEuBjIC6NJJwg2Rvg9sjjx9jYj0QUgc8CqKLN25oMZ69kNJzlFylKRUoeeVr89txlR59yehJWk6Uw6lYFTdJmcmQOFVAJ12RMmS1hLWCM8UzAgtw+EDa0eqBxBDl smash@winter" - - k, err := keypairs.Create(client, os.CreateOpts{ - Name: name, - PublicKey: pubkey, - }).Extract() - th.AssertNoErr(t, err) - defer deleteKeyPair(t, client, name) - - th.CheckEquals(t, pubkey, k.PublicKey) - th.CheckEquals(t, "", k.PrivateKey) - - t.Logf("Imported an existing keypair:") - t.Logf(" name=[%s]", k.Name) - t.Logf(" fingerprint=[%s]", k.Fingerprint) - t.Logf(" publickey=[%s]", tools.Elide(k.PublicKey)) - t.Logf(" privatekey=[%s]", tools.Elide(k.PrivateKey)) - t.Logf(" userid=[%s]", k.UserID) -} - -func TestListKeyPairs(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - count := 0 - err = keypairs.List(client).EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("--- %02d ---", count) - - ks, err := keypairs.ExtractKeyPairs(page) - th.AssertNoErr(t, err) - - for i, keypair := range ks { - t.Logf("[%02d] name=[%s]", i, keypair.Name) - t.Logf(" fingerprint=[%s]", keypair.Fingerprint) - t.Logf(" publickey=[%s]", tools.Elide(keypair.PublicKey)) - t.Logf(" privatekey=[%s]", tools.Elide(keypair.PrivateKey)) - t.Logf(" userid=[%s]", keypair.UserID) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/networks_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/networks_test.go deleted file mode 100644 index e8fc4d37dfc..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/networks_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// +build acceptance rackspace - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/networks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestNetworks(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - // Create a network - n, err := networks.Create(client, networks.CreateOpts{Label: "sample_network", CIDR: "172.20.0.0/24"}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created network: %+v\n", n) - defer networks.Delete(client, n.ID) - th.AssertEquals(t, n.Label, "sample_network") - th.AssertEquals(t, n.CIDR, "172.20.0.0/24") - networkID := n.ID - - // List networks - pager := networks.List(client) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - networkList, err := networks.ExtractNetworks(page) - th.AssertNoErr(t, err) - - for _, n := range networkList { - t.Logf("Network: ID [%s] Label [%s] CIDR [%s]", - n.ID, n.Label, n.CIDR) - } - - return true, nil - }) - th.CheckNoErr(t, err) - - // Get a network - if networkID == "" { - t.Fatalf("In order to retrieve a network, the NetworkID must be set") - } - n, err = networks.Get(client, networkID).Extract() - t.Logf("Retrieved Network: %+v\n", n) - th.AssertNoErr(t, err) - th.AssertEquals(t, n.CIDR, "172.20.0.0/24") - th.AssertEquals(t, n.Label, "sample_network") - th.AssertEquals(t, n.ID, networkID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/servers_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/servers_test.go deleted file mode 100644 index a8b5937b6ee..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/servers_test.go +++ /dev/null @@ -1,217 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig" - oskey "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - os "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs" - "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func createServerKeyPair(t *testing.T, client *gophercloud.ServiceClient) *oskey.KeyPair { - name := tools.RandomString("importedkey-", 8) - pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDlIQ3r+zd97kb9Hzmujd3V6pbO53eb3Go4q2E8iqVGWQfZTrFdL9KACJnqJIm9HmncfRkUTxE37hqeGCCv8uD+ZPmPiZG2E60OX1mGDjbbzAyReRwYWXgXHopggZTLak5k4mwZYaxwaufbVBDRn847e01lZnaXaszEToLM37NLw+uz29sl3TwYy2R0RGHPwPc160aWmdLjSyd1Nd4c9pvvOP/EoEuBjIC6NJJwg2Rvg9sjjx9jYj0QUgc8CqKLN25oMZ69kNJzlFylKRUoeeVr89txlR59yehJWk6Uw6lYFTdJmcmQOFVAJ12RMmS1hLWCM8UzAgtw+EDa0eqBxBDl smash@winter" - - k, err := keypairs.Create(client, oskey.CreateOpts{ - Name: name, - PublicKey: pubkey, - }).Extract() - th.AssertNoErr(t, err) - - return k -} - -func createServer(t *testing.T, client *gophercloud.ServiceClient, keyName string) *os.Server { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - options, err := optionsFromEnv() - th.AssertNoErr(t, err) - - name := tools.RandomString("Gophercloud-", 8) - - pwd := tools.MakeNewPassword("") - - opts := &servers.CreateOpts{ - Name: name, - ImageRef: options.imageID, - FlavorRef: options.flavorID, - DiskConfig: diskconfig.Manual, - AdminPass: pwd, - } - - if keyName != "" { - opts.KeyPair = keyName - } - - t.Logf("Creating server [%s].", name) - s, err := servers.Create(client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Creating server.") - - err = servers.WaitForStatus(client, s.ID, "ACTIVE", 300) - th.AssertNoErr(t, err) - t.Logf("Server created successfully.") - - th.CheckEquals(t, pwd, s.AdminPass) - - return s -} - -func logServer(t *testing.T, server *os.Server, index int) { - if index == -1 { - t.Logf(" id=[%s]", server.ID) - } else { - t.Logf("[%02d] id=[%s]", index, server.ID) - } - t.Logf(" name=[%s]", server.Name) - t.Logf(" tenant ID=[%s]", server.TenantID) - t.Logf(" user ID=[%s]", server.UserID) - t.Logf(" updated=[%s]", server.Updated) - t.Logf(" created=[%s]", server.Created) - t.Logf(" host ID=[%s]", server.HostID) - t.Logf(" access IPv4=[%s]", server.AccessIPv4) - t.Logf(" access IPv6=[%s]", server.AccessIPv6) - t.Logf(" image=[%v]", server.Image) - t.Logf(" flavor=[%v]", server.Flavor) - t.Logf(" addresses=[%v]", server.Addresses) - t.Logf(" metadata=[%v]", server.Metadata) - t.Logf(" links=[%v]", server.Links) - t.Logf(" keyname=[%s]", server.KeyName) - t.Logf(" admin password=[%s]", server.AdminPass) - t.Logf(" status=[%s]", server.Status) - t.Logf(" progress=[%d]", server.Progress) -} - -func getServer(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.Get") - - details, err := servers.Get(client, server.ID).Extract() - th.AssertNoErr(t, err) - logServer(t, details, -1) -} - -func updateServer(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.Get") - - opts := os.UpdateOpts{ - Name: "updated-server", - } - updatedServer, err := servers.Update(client, server.ID, opts).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "updated-server", updatedServer.Name) - logServer(t, updatedServer, -1) -} - -func listServers(t *testing.T, client *gophercloud.ServiceClient) { - t.Logf("> servers.List") - - count := 0 - err := servers.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("--- Page %02d ---", count) - - s, err := servers.ExtractServers(page) - th.AssertNoErr(t, err) - for index, server := range s { - logServer(t, &server, index) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func changeAdminPassword(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.ChangeAdminPassword") - - original := server.AdminPass - - t.Logf("Changing server password.") - err := servers.ChangeAdminPassword(client, server.ID, tools.MakeNewPassword(original)).ExtractErr() - th.AssertNoErr(t, err) - - err = servers.WaitForStatus(client, server.ID, "ACTIVE", 300) - th.AssertNoErr(t, err) - t.Logf("Password changed successfully.") -} - -func rebootServer(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.Reboot") - - err := servers.Reboot(client, server.ID, os.HardReboot).ExtractErr() - th.AssertNoErr(t, err) - - err = servers.WaitForStatus(client, server.ID, "ACTIVE", 300) - th.AssertNoErr(t, err) - - t.Logf("Server successfully rebooted.") -} - -func rebuildServer(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.Rebuild") - - options, err := optionsFromEnv() - th.AssertNoErr(t, err) - - opts := servers.RebuildOpts{ - Name: tools.RandomString("RenamedGopher", 16), - AdminPass: tools.MakeNewPassword(server.AdminPass), - ImageID: options.imageID, - DiskConfig: diskconfig.Manual, - } - after, err := servers.Rebuild(client, server.ID, opts).Extract() - th.AssertNoErr(t, err) - th.CheckEquals(t, after.ID, server.ID) - - err = servers.WaitForStatus(client, after.ID, "ACTIVE", 300) - th.AssertNoErr(t, err) - - t.Logf("Server successfully rebuilt.") - logServer(t, after, -1) -} - -func deleteServer(t *testing.T, client *gophercloud.ServiceClient, server *os.Server) { - t.Logf("> servers.Delete") - - res := servers.Delete(client, server.ID) - th.AssertNoErr(t, res.Err) - - t.Logf("Server deleted successfully.") -} - -func deleteServerKeyPair(t *testing.T, client *gophercloud.ServiceClient, k *oskey.KeyPair) { - t.Logf("> keypairs.Delete") - - err := keypairs.Delete(client, k.Name).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Keypair deleted successfully.") -} - -func TestServerOperations(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - kp := createServerKeyPair(t, client) - defer deleteServerKeyPair(t, client, kp) - - server := createServer(t, client, kp.Name) - defer deleteServer(t, client, server) - - getServer(t, client, server) - updateServer(t, client, server) - listServers(t, client) - changeAdminPassword(t, client, server) - rebootServer(t, client, server) - rebuildServer(t, client, server) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/virtualinterfaces_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/virtualinterfaces_test.go deleted file mode 100644 index 39475e176e2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/virtualinterfaces_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// +build acceptance rackspace - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/networks" - "github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestVirtualInterfaces(t *testing.T) { - client, err := newClient() - th.AssertNoErr(t, err) - - // Create a server - server := createServer(t, client, "") - t.Logf("Created Server: %v\n", server) - defer deleteServer(t, client, server) - serverID := server.ID - - // Create a network - n, err := networks.Create(client, networks.CreateOpts{Label: "sample_network", CIDR: "172.20.0.0/24"}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created Network: %v\n", n) - defer networks.Delete(client, n.ID) - networkID := n.ID - - // Create a virtual interface - vi, err := virtualinterfaces.Create(client, serverID, networkID).Extract() - th.AssertNoErr(t, err) - t.Logf("Created virtual interface: %+v\n", vi) - defer virtualinterfaces.Delete(client, serverID, vi.ID) - - // List virtual interfaces - pager := virtualinterfaces.List(client, serverID) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - virtualinterfacesList, err := virtualinterfaces.ExtractVirtualInterfaces(page) - th.AssertNoErr(t, err) - - for _, vi := range virtualinterfacesList { - t.Logf("Virtual Interface: ID [%s] MAC Address [%s] IP Addresses [%v]", - vi.ID, vi.MACAddress, vi.IPAddresses) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/volumeattach_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/volumeattach_test.go deleted file mode 100644 index 9848e2eba59..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/compute/v2/volumeattach_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// +build acceptance compute servers - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack" - osVolumes "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - osVolumeAttach "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach" - osServers "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/rackspace" - "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes" - "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" - "github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach" - th "github.com/rackspace/gophercloud/testhelper" -) - -func newBlockClient(t *testing.T) (*gophercloud.ServiceClient, error) { - ao, err := rackspace.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - - client, err := rackspace.AuthenticatedClient(ao) - th.AssertNoErr(t, err) - - return openstack.NewBlockStorageV1(client, gophercloud.EndpointOpts{ - Region: os.Getenv("RS_REGION_NAME"), - }) -} - -func createVAServer(t *testing.T, computeClient *gophercloud.ServiceClient, choices *serverOpts) (*osServers.Server, error) { - if testing.Short() { - t.Skip("Skipping test that requires server creation in short mode.") - } - - name := tools.RandomString("ACPTTEST", 16) - t.Logf("Attempting to create server: %s\n", name) - - pwd := tools.MakeNewPassword("") - - server, err := servers.Create(computeClient, osServers.CreateOpts{ - Name: name, - FlavorRef: choices.flavorID, - ImageRef: choices.imageID, - AdminPass: pwd, - }).Extract() - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - - th.AssertEquals(t, pwd, server.AdminPass) - - return server, err -} - -func createVAVolume(t *testing.T, blockClient *gophercloud.ServiceClient) (*volumes.Volume, error) { - volume, err := volumes.Create(blockClient, &osVolumes.CreateOpts{ - Size: 80, - Name: "gophercloud-test-volume", - }).Extract() - th.AssertNoErr(t, err) - defer func() { - err = osVolumes.WaitForStatus(blockClient, volume.ID, "available", 60) - th.AssertNoErr(t, err) - }() - - return volume, err -} - -func createVolumeAttachment(t *testing.T, computeClient *gophercloud.ServiceClient, blockClient *gophercloud.ServiceClient, serverID string, volumeID string) { - va, err := volumeattach.Create(computeClient, serverID, &osVolumeAttach.CreateOpts{ - VolumeID: volumeID, - }).Extract() - th.AssertNoErr(t, err) - defer func() { - err = osVolumes.WaitForStatus(blockClient, volumeID, "in-use", 60) - th.AssertNoErr(t, err) - err = volumeattach.Delete(computeClient, serverID, va.ID).ExtractErr() - th.AssertNoErr(t, err) - err = osVolumes.WaitForStatus(blockClient, volumeID, "available", 60) - th.AssertNoErr(t, err) - }() - t.Logf("Attached volume to server: %+v", va) -} - -func TestAttachVolume(t *testing.T) { - choices, err := optionsFromEnv() - if err != nil { - t.Fatal(err) - } - - computeClient, err := newClient() - if err != nil { - t.Fatalf("Unable to create a compute client: %v", err) - } - - blockClient, err := newBlockClient(t) - if err != nil { - t.Fatalf("Unable to create a blockstorage client: %v", err) - } - - server, err := createVAServer(t, computeClient, choices) - if err != nil { - t.Fatalf("Unable to create server: %v", err) - } - defer func() { - servers.Delete(computeClient, server.ID) - t.Logf("Server deleted.") - }() - - if err = osServers.WaitForStatus(computeClient, server.ID, "ACTIVE", 300); err != nil { - t.Fatalf("Unable to wait for server: %v", err) - } - - volume, err := createVAVolume(t, blockClient) - if err != nil { - t.Fatalf("Unable to create volume: %v", err) - } - defer func() { - err = volumes.Delete(blockClient, volume.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Volume deleted.") - }() - - createVolumeAttachment(t, computeClient, blockClient, server.ID, volume.ID) - -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/extension_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/extension_test.go deleted file mode 100644 index a50e015522d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/extension_test.go +++ /dev/null @@ -1,54 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - extensions2 "github.com/rackspace/gophercloud/rackspace/identity/v2/extensions" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestExtensions(t *testing.T) { - service := authenticatedClient(t) - - t.Logf("Extensions available on this identity endpoint:") - count := 0 - var chosen string - err := extensions2.List(service).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - extensions, err := extensions2.ExtractExtensions(page) - th.AssertNoErr(t, err) - - for i, ext := range extensions { - if chosen == "" { - chosen = ext.Alias - } - - t.Logf("[%02d] name=[%s] namespace=[%s]", i, ext.Name, ext.Namespace) - t.Logf(" alias=[%s] updated=[%s]", ext.Alias, ext.Updated) - t.Logf(" description=[%s]", ext.Description) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - - if chosen == "" { - t.Logf("No extensions found.") - return - } - - ext, err := extensions2.Get(service, chosen).Extract() - th.AssertNoErr(t, err) - - t.Logf("Detail for extension [%s]:", chosen) - t.Logf(" name=[%s]", ext.Name) - t.Logf(" namespace=[%s]", ext.Namespace) - t.Logf(" alias=[%s]", ext.Alias) - t.Logf(" updated=[%s]", ext.Updated) - t.Logf(" description=[%s]", ext.Description) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/identity_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/identity_test.go deleted file mode 100644 index 1182982f44d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/identity_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/rackspace" - th "github.com/rackspace/gophercloud/testhelper" -) - -func rackspaceAuthOptions(t *testing.T) gophercloud.AuthOptions { - // Obtain credentials from the environment. - options, err := rackspace.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - options = tools.OnlyRS(options) - - if options.Username == "" { - t.Fatal("Please provide a Rackspace username as RS_USERNAME.") - } - if options.APIKey == "" { - t.Fatal("Please provide a Rackspace API key as RS_API_KEY.") - } - - return options -} - -func createClient(t *testing.T, auth bool) *gophercloud.ServiceClient { - ao := rackspaceAuthOptions(t) - - provider, err := rackspace.NewClient(ao.IdentityEndpoint) - th.AssertNoErr(t, err) - - if auth { - err = rackspace.Authenticate(provider, ao) - th.AssertNoErr(t, err) - } - - return rackspace.NewIdentityV2(provider) -} - -func unauthenticatedClient(t *testing.T) *gophercloud.ServiceClient { - return createClient(t, false) -} - -func authenticatedClient(t *testing.T) *gophercloud.ServiceClient { - return createClient(t, true) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/role_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/role_test.go deleted file mode 100644 index efaeb75cde8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/role_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build acceptance identity roles - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/identity/v2/roles" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestRoles(t *testing.T) { - client := authenticatedClient(t) - - userID := createUser(t, client) - roleID := listRoles(t, client) - - addUserRole(t, client, userID, roleID) - - deleteUserRole(t, client, userID, roleID) - - deleteUser(t, client, userID) -} - -func listRoles(t *testing.T, client *gophercloud.ServiceClient) string { - var roleID string - - err := roles.List(client).EachPage(func(page pagination.Page) (bool, error) { - roleList, err := os.ExtractRoles(page) - th.AssertNoErr(t, err) - - for _, role := range roleList { - t.Logf("Listing role: ID [%s] Name [%s]", role.ID, role.Name) - roleID = role.ID - } - - return true, nil - }) - - th.AssertNoErr(t, err) - - return roleID -} - -func addUserRole(t *testing.T, client *gophercloud.ServiceClient, userID, roleID string) { - err := roles.AddUserRole(client, userID, roleID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Added role %s to user %s", roleID, userID) -} - -func deleteUserRole(t *testing.T, client *gophercloud.ServiceClient, userID, roleID string) { - err := roles.DeleteUserRole(client, userID, roleID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Removed role %s from user %s", roleID, userID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tenant_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tenant_test.go deleted file mode 100644 index 6081a498e34..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tenant_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - rstenants "github.com/rackspace/gophercloud/rackspace/identity/v2/tenants" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestTenants(t *testing.T) { - service := authenticatedClient(t) - - t.Logf("Tenants available to the currently issued token:") - count := 0 - err := rstenants.List(service, nil).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - tenants, err := rstenants.ExtractTenants(page) - th.AssertNoErr(t, err) - - for i, tenant := range tenants { - t.Logf("[%02d] id=[%s]", i, tenant.ID) - t.Logf(" name=[%s] enabled=[%v]", i, tenant.Name, tenant.Enabled) - t.Logf(" description=[%s]", tenant.Description) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No tenants listed for your current token.") - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tokens_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tokens_test.go deleted file mode 100644 index 95ee7e660cd..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/tokens_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build acceptance - -package v2 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/rackspace" - "github.com/rackspace/gophercloud/rackspace/identity/v2/tokens" - th "github.com/rackspace/gophercloud/testhelper" -) - -func rackspaceAuthOptions(t *testing.T) gophercloud.AuthOptions { - // Obtain credentials from the environment. - options, err := rackspace.AuthOptionsFromEnv() - th.AssertNoErr(t, err) - options = tools.OnlyRS(options) - - if options.Username == "" { - t.Fatal("Please provide a Rackspace username as RS_USERNAME.") - } - if options.APIKey == "" { - t.Fatal("Please provide a Rackspace API key as RS_API_KEY.") - } - - return options -} - -func createClient(t *testing.T, auth bool) *gophercloud.ServiceClient { - ao := rackspaceAuthOptions(t) - - provider, err := rackspace.NewClient(ao.IdentityEndpoint) - th.AssertNoErr(t, err) - - if auth { - err = rackspace.Authenticate(provider, ao) - th.AssertNoErr(t, err) - } - - return rackspace.NewIdentityV2(provider) -} - -func TestTokenAuth(t *testing.T) { - authedClient := createClient(t, true) - token := authedClient.TokenID - - tenantID := os.Getenv("RS_TENANT_ID") - if tenantID == "" { - t.Skip("You must set RS_TENANT_ID environment variable to run this test") - } - - authOpts := tokens.AuthOptions{} - authOpts.TenantID = tenantID - authOpts.Token = token - - _, err := tokens.Create(authedClient, authOpts).ExtractToken() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/user_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/user_test.go deleted file mode 100644 index 28c0c832bef..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/identity/v2/user_test.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build acceptance identity - -package v2 - -import ( - "strconv" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - os "github.com/rackspace/gophercloud/openstack/identity/v2/users" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/identity/v2/users" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestUsers(t *testing.T) { - client := authenticatedClient(t) - - userID := createUser(t, client) - - listUsers(t, client) - - getUser(t, client, userID) - - updateUser(t, client, userID) - - resetApiKey(t, client, userID) - - deleteUser(t, client, userID) -} - -func createUser(t *testing.T, client *gophercloud.ServiceClient) string { - t.Log("Creating user") - - opts := users.CreateOpts{ - Username: tools.RandomString("user_", 5), - Enabled: os.Disabled, - Email: "new_user@foo.com", - } - - user, err := users.Create(client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created user %s", user.ID) - - return user.ID -} - -func listUsers(t *testing.T, client *gophercloud.ServiceClient) { - err := users.List(client).EachPage(func(page pagination.Page) (bool, error) { - userList, err := os.ExtractUsers(page) - th.AssertNoErr(t, err) - - for _, user := range userList { - t.Logf("Listing user: ID [%s] Username [%s] Email [%s] Enabled? [%s]", - user.ID, user.Username, user.Email, strconv.FormatBool(user.Enabled)) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - _, err := users.Get(client, userID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting user %s", userID) -} - -func updateUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - opts := users.UpdateOpts{Username: tools.RandomString("new_name", 5), Email: "new@foo.com"} - user, err := users.Update(client, userID, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Updated user %s: Username [%s] Email [%s]", userID, user.Username, user.Email) -} - -func deleteUser(t *testing.T, client *gophercloud.ServiceClient, userID string) { - res := users.Delete(client, userID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted user %s", userID) -} - -func resetApiKey(t *testing.T, client *gophercloud.ServiceClient, userID string) { - key, err := users.ResetAPIKey(client, userID).Extract() - th.AssertNoErr(t, err) - - if key.APIKey == "" { - t.Fatal("failed to reset API key for user") - } - - t.Logf("Reset API key for user %s to %s", key.Username, key.APIKey) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/acl_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/acl_test.go deleted file mode 100644 index 7a380273c62..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/acl_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/lb/v1/acl" - "github.com/rackspace/gophercloud/rackspace/lb/v1/lbs" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestACL(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 1) - lbID := ids[0] - - createACL(t, client, lbID) - - waitForLB(client, lbID, lbs.ACTIVE) - - networkIDs := showACL(t, client, lbID) - - deleteNetworkItem(t, client, lbID, networkIDs[0]) - waitForLB(client, lbID, lbs.ACTIVE) - - bulkDeleteACL(t, client, lbID, networkIDs[1:2]) - waitForLB(client, lbID, lbs.ACTIVE) - - deleteACL(t, client, lbID) - waitForLB(client, lbID, lbs.ACTIVE) - - deleteLB(t, client, lbID) -} - -func createACL(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - opts := acl.CreateOpts{ - acl.CreateOpt{Address: "206.160.163.21", Type: acl.DENY}, - acl.CreateOpt{Address: "206.160.165.11", Type: acl.DENY}, - acl.CreateOpt{Address: "206.160.165.12", Type: acl.DENY}, - acl.CreateOpt{Address: "206.160.165.13", Type: acl.ALLOW}, - } - - err := acl.Create(client, lbID, opts).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Created ACL items for LB %d", lbID) -} - -func showACL(t *testing.T, client *gophercloud.ServiceClient, lbID int) []int { - ids := []int{} - - err := acl.List(client, lbID).EachPage(func(page pagination.Page) (bool, error) { - accessList, err := acl.ExtractAccessList(page) - th.AssertNoErr(t, err) - - for _, i := range accessList { - t.Logf("Listing network item: ID [%s] Address [%s] Type [%s]", i.ID, i.Address, i.Type) - ids = append(ids, i.ID) - } - - return true, nil - }) - th.AssertNoErr(t, err) - - return ids -} - -func deleteNetworkItem(t *testing.T, client *gophercloud.ServiceClient, lbID, itemID int) { - err := acl.Delete(client, lbID, itemID).ExtractErr() - - th.AssertNoErr(t, err) - - t.Logf("Deleted network item %d", itemID) -} - -func bulkDeleteACL(t *testing.T, client *gophercloud.ServiceClient, lbID int, items []int) { - err := acl.BulkDelete(client, lbID, items).ExtractErr() - - th.AssertNoErr(t, err) - - t.Logf("Deleted network items %s", intsToStr(items)) -} - -func deleteACL(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := acl.DeleteAll(client, lbID).ExtractErr() - - th.AssertNoErr(t, err) - - t.Logf("Deleted ACL from LB %d", lbID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/lb_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/lb_test.go deleted file mode 100644 index c67ddecad93..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/lb_test.go +++ /dev/null @@ -1,214 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "strconv" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/lb/v1/lbs" - "github.com/rackspace/gophercloud/rackspace/lb/v1/vips" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestLBs(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 3) - id := ids[0] - - listLBProtocols(t, client) - - listLBAlgorithms(t, client) - - listLBs(t, client) - - getLB(t, client, id) - - checkLBLogging(t, client, id) - - checkErrorPage(t, client, id) - - getStats(t, client, id) - - updateLB(t, client, id) - - deleteLB(t, client, id) - - batchDeleteLBs(t, client, ids[1:]) -} - -func createLB(t *testing.T, client *gophercloud.ServiceClient, count int) []int { - ids := []int{} - - for i := 0; i < count; i++ { - opts := lbs.CreateOpts{ - Name: tools.RandomString("test_", 5), - Port: 80, - Protocol: "HTTP", - VIPs: []vips.VIP{ - vips.VIP{Type: vips.PUBLIC}, - }, - } - - lb, err := lbs.Create(client, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Created LB %d - waiting for it to build...", lb.ID) - waitForLB(client, lb.ID, lbs.ACTIVE) - t.Logf("LB %d has reached ACTIVE state", lb.ID) - - ids = append(ids, lb.ID) - } - - return ids -} - -func waitForLB(client *gophercloud.ServiceClient, id int, state lbs.Status) { - gophercloud.WaitFor(60, func() (bool, error) { - lb, err := lbs.Get(client, id).Extract() - if err != nil { - return false, err - } - if lb.Status != state { - return false, nil - } - return true, nil - }) -} - -func listLBProtocols(t *testing.T, client *gophercloud.ServiceClient) { - err := lbs.ListProtocols(client).EachPage(func(page pagination.Page) (bool, error) { - pList, err := lbs.ExtractProtocols(page) - th.AssertNoErr(t, err) - - for _, p := range pList { - t.Logf("Listing protocol: Name [%s]", p.Name) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func listLBAlgorithms(t *testing.T, client *gophercloud.ServiceClient) { - err := lbs.ListAlgorithms(client).EachPage(func(page pagination.Page) (bool, error) { - aList, err := lbs.ExtractAlgorithms(page) - th.AssertNoErr(t, err) - - for _, a := range aList { - t.Logf("Listing algorithm: Name [%s]", a.Name) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func listLBs(t *testing.T, client *gophercloud.ServiceClient) { - err := lbs.List(client, lbs.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - lbList, err := lbs.ExtractLBs(page) - th.AssertNoErr(t, err) - - for _, lb := range lbList { - t.Logf("Listing LB: ID [%d] Name [%s] Protocol [%s] Status [%s] Node count [%d] Port [%d]", - lb.ID, lb.Name, lb.Protocol, lb.Status, lb.NodeCount, lb.Port) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getLB(t *testing.T, client *gophercloud.ServiceClient, id int) { - lb, err := lbs.Get(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting LB %d: Created [%s] VIPs [%#v] Logging [%#v] Persistence [%#v] SourceAddrs [%#v]", - lb.ID, lb.Created, lb.VIPs, lb.ConnectionLogging, lb.SessionPersistence, lb.SourceAddrs) -} - -func updateLB(t *testing.T, client *gophercloud.ServiceClient, id int) { - opts := lbs.UpdateOpts{ - Name: tools.RandomString("new_", 5), - Protocol: "TCP", - HalfClosed: gophercloud.Enabled, - Algorithm: "RANDOM", - Port: 8080, - Timeout: 100, - HTTPSRedirect: gophercloud.Disabled, - } - - err := lbs.Update(client, id, opts).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Updating LB %d - waiting for it to finish", id) - waitForLB(client, id, lbs.ACTIVE) - t.Logf("LB %d has reached ACTIVE state", id) -} - -func deleteLB(t *testing.T, client *gophercloud.ServiceClient, id int) { - err := lbs.Delete(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted LB %d", id) -} - -func batchDeleteLBs(t *testing.T, client *gophercloud.ServiceClient, ids []int) { - err := lbs.BulkDelete(client, ids).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted LB %s", intsToStr(ids)) -} - -func checkLBLogging(t *testing.T, client *gophercloud.ServiceClient, id int) { - err := lbs.EnableLogging(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Enabled logging for LB %d", id) - - res, err := lbs.IsLoggingEnabled(client, id) - th.AssertNoErr(t, err) - t.Logf("LB %d log enabled? %s", id, strconv.FormatBool(res)) - - waitForLB(client, id, lbs.ACTIVE) - - err = lbs.DisableLogging(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Disabled logging for LB %d", id) -} - -func checkErrorPage(t *testing.T, client *gophercloud.ServiceClient, id int) { - content, err := lbs.SetErrorPage(client, id, "New content!").Extract() - t.Logf("Set error page for LB %d", id) - - content, err = lbs.GetErrorPage(client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Error page for LB %d: %s", id, content) - - err = lbs.DeleteErrorPage(client, id).ExtractErr() - t.Logf("Deleted error page for LB %d", id) -} - -func getStats(t *testing.T, client *gophercloud.ServiceClient, id int) { - waitForLB(client, id, lbs.ACTIVE) - - stats, err := lbs.GetStats(client, id).Extract() - th.AssertNoErr(t, err) - - t.Logf("Stats for LB %d: %#v", id, stats) -} - -func checkCaching(t *testing.T, client *gophercloud.ServiceClient, id int) { - err := lbs.EnableCaching(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Enabled caching for LB %d", id) - - res, err := lbs.IsContentCached(client, id) - th.AssertNoErr(t, err) - t.Logf("Is caching enabled for LB? %s", strconv.FormatBool(res)) - - err = lbs.DisableCaching(client, id).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Disabled caching for LB %d", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/monitor_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/monitor_test.go deleted file mode 100644 index c1a8e24dd9b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/monitor_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/lb/v1/lbs" - "github.com/rackspace/gophercloud/rackspace/lb/v1/monitors" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestMonitors(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 1) - lbID := ids[0] - - getMonitor(t, client, lbID) - - updateMonitor(t, client, lbID) - - deleteMonitor(t, client, lbID) - - deleteLB(t, client, lbID) -} - -func getMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - hm, err := monitors.Get(client, lbID).Extract() - th.AssertNoErr(t, err) - t.Logf("Health monitor for LB %d: Type [%s] Delay [%d] Timeout [%d] AttemptLimit [%d]", - lbID, hm.Type, hm.Delay, hm.Timeout, hm.AttemptLimit) -} - -func updateMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - opts := monitors.UpdateHTTPMonitorOpts{ - AttemptLimit: 3, - Delay: 10, - Timeout: 10, - BodyRegex: "hello is it me you're looking for", - Path: "/foo", - StatusRegex: "200", - Type: monitors.HTTP, - } - - err := monitors.Update(client, lbID, opts).ExtractErr() - th.AssertNoErr(t, err) - - waitForLB(client, lbID, lbs.ACTIVE) - t.Logf("Updated monitor for LB %d", lbID) -} - -func deleteMonitor(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := monitors.Delete(client, lbID).ExtractErr() - th.AssertNoErr(t, err) - - waitForLB(client, lbID, lbs.ACTIVE) - t.Logf("Deleted monitor for LB %d", lbID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/node_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/node_test.go deleted file mode 100644 index 18b9fe71ce3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/node_test.go +++ /dev/null @@ -1,175 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "os" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/acceptance/tools" - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/compute/v2/servers" - "github.com/rackspace/gophercloud/rackspace/lb/v1/lbs" - "github.com/rackspace/gophercloud/rackspace/lb/v1/nodes" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestNodes(t *testing.T) { - client := setup(t) - - serverIP := findServer(t) - ids := createLB(t, client, 1) - lbID := ids[0] - - nodeID := addNodes(t, client, lbID, serverIP) - - listNodes(t, client, lbID) - - getNode(t, client, lbID, nodeID) - - updateNode(t, client, lbID, nodeID) - - listEvents(t, client, lbID) - - deleteNode(t, client, lbID, nodeID) - - waitForLB(client, lbID, lbs.ACTIVE) - deleteLB(t, client, lbID) -} - -func findServer(t *testing.T) string { - var serverIP string - - client, err := newComputeClient() - th.AssertNoErr(t, err) - - err = servers.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - sList, err := servers.ExtractServers(page) - th.AssertNoErr(t, err) - - for _, s := range sList { - serverIP = s.AccessIPv4 - t.Logf("Found an existing server: ID [%s] Public IP [%s]", s.ID, serverIP) - break - } - - return true, nil - }) - th.AssertNoErr(t, err) - - if serverIP == "" { - t.Log("No server found, creating one") - - imageRef := os.Getenv("RS_IMAGE_ID") - if imageRef == "" { - t.Fatalf("OS var RS_IMAGE_ID undefined") - } - flavorRef := os.Getenv("RS_FLAVOR_ID") - if flavorRef == "" { - t.Fatalf("OS var RS_FLAVOR_ID undefined") - } - - opts := &servers.CreateOpts{ - Name: tools.RandomString("lb_test_", 5), - ImageRef: imageRef, - FlavorRef: flavorRef, - DiskConfig: diskconfig.Manual, - } - - s, err := servers.Create(client, opts).Extract() - th.AssertNoErr(t, err) - serverIP = s.AccessIPv4 - - t.Logf("Created server %s, waiting for it to build", s.ID) - err = servers.WaitForStatus(client, s.ID, "ACTIVE", 300) - th.AssertNoErr(t, err) - t.Logf("Server created successfully.") - } - - return serverIP -} - -func addNodes(t *testing.T, client *gophercloud.ServiceClient, lbID int, serverIP string) int { - opts := nodes.CreateOpts{ - nodes.CreateOpt{ - Address: serverIP, - Port: 80, - Condition: nodes.ENABLED, - Type: nodes.PRIMARY, - }, - } - - page := nodes.Create(client, lbID, opts) - - nodeList, err := page.ExtractNodes() - th.AssertNoErr(t, err) - - var nodeID int - for _, n := range nodeList { - nodeID = n.ID - } - if nodeID == 0 { - t.Fatalf("nodeID could not be extracted from create response") - } - - t.Logf("Added node %d to LB %d", nodeID, lbID) - waitForLB(client, lbID, lbs.ACTIVE) - - return nodeID -} - -func listNodes(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := nodes.List(client, lbID, nil).EachPage(func(page pagination.Page) (bool, error) { - nodeList, err := nodes.ExtractNodes(page) - th.AssertNoErr(t, err) - - for _, n := range nodeList { - t.Logf("Listing node: ID [%d] Address [%s:%d] Status [%s]", n.ID, n.Address, n.Port, n.Status) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func getNode(t *testing.T, client *gophercloud.ServiceClient, lbID int, nodeID int) { - node, err := nodes.Get(client, lbID, nodeID).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting node %d: Type [%s] Weight [%d]", nodeID, node.Type, node.Weight) -} - -func updateNode(t *testing.T, client *gophercloud.ServiceClient, lbID int, nodeID int) { - opts := nodes.UpdateOpts{ - Weight: gophercloud.IntToPointer(10), - Condition: nodes.DRAINING, - Type: nodes.SECONDARY, - } - err := nodes.Update(client, lbID, nodeID, opts).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Updated node %d", nodeID) - waitForLB(client, lbID, lbs.ACTIVE) -} - -func listEvents(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - pager := nodes.ListEvents(client, lbID, nodes.ListEventsOpts{}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - eventList, err := nodes.ExtractNodeEvents(page) - th.AssertNoErr(t, err) - - for _, e := range eventList { - t.Logf("Listing events for node %d: Type [%s] Msg [%s] Severity [%s] Date [%s]", - e.NodeID, e.Type, e.DetailedMessage, e.Severity, e.Created) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func deleteNode(t *testing.T, client *gophercloud.ServiceClient, lbID int, nodeID int) { - err := nodes.Delete(client, lbID, nodeID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted node %d", nodeID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/session_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/session_test.go deleted file mode 100644 index 8d85655f6b1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/session_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/lb/v1/sessions" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSession(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 1) - lbID := ids[0] - - getSession(t, client, lbID) - - enableSession(t, client, lbID) - waitForLB(client, lbID, "ACTIVE") - - disableSession(t, client, lbID) - waitForLB(client, lbID, "ACTIVE") - - deleteLB(t, client, lbID) -} - -func getSession(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - sp, err := sessions.Get(client, lbID).Extract() - th.AssertNoErr(t, err) - t.Logf("Session config: Type [%s]", sp.Type) -} - -func enableSession(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - opts := sessions.CreateOpts{Type: sessions.HTTPCOOKIE} - err := sessions.Enable(client, lbID, opts).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Enable %s sessions for %d", opts.Type, lbID) -} - -func disableSession(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := sessions.Disable(client, lbID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Disable sessions for %d", lbID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/throttle_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/throttle_test.go deleted file mode 100644 index 1cc12356caf..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/throttle_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/lb/v1/throttle" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestThrottle(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 1) - lbID := ids[0] - - getThrottleConfig(t, client, lbID) - - createThrottleConfig(t, client, lbID) - waitForLB(client, lbID, "ACTIVE") - - deleteThrottleConfig(t, client, lbID) - waitForLB(client, lbID, "ACTIVE") - - deleteLB(t, client, lbID) -} - -func getThrottleConfig(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - sp, err := throttle.Get(client, lbID).Extract() - th.AssertNoErr(t, err) - t.Logf("Throttle config: MaxConns [%s]", sp.MaxConnections) -} - -func createThrottleConfig(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - opts := throttle.CreateOpts{ - MaxConnections: 200, - MaxConnectionRate: 100, - MinConnections: 0, - RateInterval: 10, - } - - err := throttle.Create(client, lbID, opts).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Enable throttling for %d", lbID) -} - -func deleteThrottleConfig(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := throttle.Delete(client, lbID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Disable throttling for %d", lbID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/vip_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/vip_test.go deleted file mode 100644 index bc0c2a89f2a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/lb/v1/vip_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// +build acceptance lbs - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/lb/v1/lbs" - "github.com/rackspace/gophercloud/rackspace/lb/v1/vips" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestVIPs(t *testing.T) { - client := setup(t) - - ids := createLB(t, client, 1) - lbID := ids[0] - - listVIPs(t, client, lbID) - - vipIDs := addVIPs(t, client, lbID, 3) - - deleteVIP(t, client, lbID, vipIDs[0]) - - bulkDeleteVIPs(t, client, lbID, vipIDs[1:]) - - waitForLB(client, lbID, lbs.ACTIVE) - deleteLB(t, client, lbID) -} - -func listVIPs(t *testing.T, client *gophercloud.ServiceClient, lbID int) { - err := vips.List(client, lbID).EachPage(func(page pagination.Page) (bool, error) { - vipList, err := vips.ExtractVIPs(page) - th.AssertNoErr(t, err) - - for _, vip := range vipList { - t.Logf("Listing VIP: ID [%s] Address [%s] Type [%s] Version [%s]", - vip.ID, vip.Address, vip.Type, vip.Version) - } - - return true, nil - }) - th.AssertNoErr(t, err) -} - -func addVIPs(t *testing.T, client *gophercloud.ServiceClient, lbID, count int) []int { - ids := []int{} - - for i := 0; i < count; i++ { - opts := vips.CreateOpts{ - Type: vips.PUBLIC, - Version: vips.IPV6, - } - - vip, err := vips.Create(client, lbID, opts).Extract() - th.AssertNoErr(t, err) - - t.Logf("Created VIP %d", vip.ID) - - waitForLB(client, lbID, lbs.ACTIVE) - - ids = append(ids, vip.ID) - } - - return ids -} - -func deleteVIP(t *testing.T, client *gophercloud.ServiceClient, lbID, vipID int) { - err := vips.Delete(client, lbID, vipID).ExtractErr() - th.AssertNoErr(t, err) - - t.Logf("Deleted VIP %d", vipID) - - waitForLB(client, lbID, lbs.ACTIVE) -} - -func bulkDeleteVIPs(t *testing.T, client *gophercloud.ServiceClient, lbID int, ids []int) { - err := vips.BulkDelete(client, lbID, ids).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted VIPs %s", intsToStr(ids)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/network_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/network_test.go deleted file mode 100644 index 3862123bfd9..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/network_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "strconv" - "testing" - - os "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/networking/v2/networks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestNetworkCRUDOperations(t *testing.T) { - Setup(t) - defer Teardown() - - // Create a network - n, err := networks.Create(Client, os.CreateOpts{Name: "sample_network", AdminStateUp: os.Up}).Extract() - th.AssertNoErr(t, err) - defer networks.Delete(Client, n.ID) - th.AssertEquals(t, "sample_network", n.Name) - th.AssertEquals(t, true, n.AdminStateUp) - networkID := n.ID - - // List networks - pager := networks.List(Client, os.ListOpts{Limit: 2}) - err = pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - networkList, err := os.ExtractNetworks(page) - th.AssertNoErr(t, err) - - for _, n := range networkList { - t.Logf("Network: ID [%s] Name [%s] Status [%s] Is shared? [%s]", - n.ID, n.Name, n.Status, strconv.FormatBool(n.Shared)) - } - - return true, nil - }) - th.CheckNoErr(t, err) - - // Get a network - if networkID == "" { - t.Fatalf("In order to retrieve a network, the NetworkID must be set") - } - n, err = networks.Get(Client, networkID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "ACTIVE", n.Status) - th.AssertDeepEquals(t, []string{}, n.Subnets) - th.AssertEquals(t, "sample_network", n.Name) - th.AssertEquals(t, true, n.AdminStateUp) - th.AssertEquals(t, false, n.Shared) - th.AssertEquals(t, networkID, n.ID) - - // Update network - n, err = networks.Update(Client, networkID, os.UpdateOpts{Name: "new_network_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "new_network_name", n.Name) - - // Delete network - res := networks.Delete(Client, networkID) - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/port_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/port_test.go deleted file mode 100644 index 3c42bb20cd3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/port_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - osNetworks "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - osPorts "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - osSubnets "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/networking/v2/networks" - "github.com/rackspace/gophercloud/rackspace/networking/v2/ports" - "github.com/rackspace/gophercloud/rackspace/networking/v2/subnets" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestPortCRUD(t *testing.T) { - Setup(t) - defer Teardown() - - // Setup network - t.Log("Setting up network") - networkID, err := createNetwork() - th.AssertNoErr(t, err) - defer networks.Delete(Client, networkID) - - // Setup subnet - t.Logf("Setting up subnet on network %s", networkID) - subnetID, err := createSubnet(networkID) - th.AssertNoErr(t, err) - defer subnets.Delete(Client, subnetID) - - // Create port - t.Logf("Create port based on subnet %s", subnetID) - portID := createPort(t, networkID, subnetID) - - // List ports - t.Logf("Listing all ports") - listPorts(t) - - // Get port - if portID == "" { - t.Fatalf("In order to retrieve a port, the portID must be set") - } - p, err := ports.Get(Client, portID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, portID, p.ID) - - // Update port - p, err = ports.Update(Client, portID, osPorts.UpdateOpts{Name: "new_port_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "new_port_name", p.Name) - - // Delete port - res := ports.Delete(Client, portID) - th.AssertNoErr(t, res.Err) -} - -func createPort(t *testing.T, networkID, subnetID string) string { - enable := true - opts := osPorts.CreateOpts{ - NetworkID: networkID, - Name: "my_port", - AdminStateUp: &enable, - FixedIPs: []osPorts.IP{osPorts.IP{SubnetID: subnetID}}, - } - p, err := ports.Create(Client, opts).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, networkID, p.NetworkID) - th.AssertEquals(t, "my_port", p.Name) - th.AssertEquals(t, true, p.AdminStateUp) - - return p.ID -} - -func listPorts(t *testing.T) { - count := 0 - pager := ports.List(Client, osPorts.ListOpts{}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - count++ - t.Logf("--- Page ---") - - portList, err := osPorts.ExtractPorts(page) - th.AssertNoErr(t, err) - - for _, p := range portList { - t.Logf("Port: ID [%s] Name [%s] Status [%s] MAC addr [%s] Fixed IPs [%#v] Security groups [%#v]", - p.ID, p.Name, p.Status, p.MACAddress, p.FixedIPs, p.SecurityGroups) - } - - return true, nil - }) - - th.CheckNoErr(t, err) - - if count == 0 { - t.Logf("No pages were iterated over when listing ports") - } -} - -func createNetwork() (string, error) { - res, err := networks.Create(Client, osNetworks.CreateOpts{Name: "tmp_network", AdminStateUp: osNetworks.Up}).Extract() - return res.ID, err -} - -func createSubnet(networkID string) (string, error) { - s, err := subnets.Create(Client, osSubnets.CreateOpts{ - NetworkID: networkID, - CIDR: "192.168.199.0/24", - IPVersion: osSubnets.IPv4, - Name: "my_subnet", - EnableDHCP: osSubnets.Down, - }).Extract() - return s.ID, err -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/security_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/security_test.go deleted file mode 100644 index ec029913e3b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/security_test.go +++ /dev/null @@ -1,165 +0,0 @@ -// +build acceptance networking security - -package v2 - -import ( - "testing" - - osGroups "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups" - osRules "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - osNetworks "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - osPorts "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - "github.com/rackspace/gophercloud/pagination" - rsNetworks "github.com/rackspace/gophercloud/rackspace/networking/v2/networks" - rsPorts "github.com/rackspace/gophercloud/rackspace/networking/v2/ports" - rsGroups "github.com/rackspace/gophercloud/rackspace/networking/v2/security/groups" - rsRules "github.com/rackspace/gophercloud/rackspace/networking/v2/security/rules" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestSecurityGroups(t *testing.T) { - Setup(t) - defer Teardown() - - // create security group - groupID := createSecGroup(t) - - // delete security group - defer deleteSecGroup(t, groupID) - - // list security group - listSecGroups(t) - - // get security group - getSecGroup(t, groupID) -} - -func TestSecurityGroupRules(t *testing.T) { - Setup(t) - defer Teardown() - - // create security group - groupID := createSecGroup(t) - - defer deleteSecGroup(t, groupID) - - // create security group rule - ruleID := createSecRule(t, groupID) - - // delete security group rule - defer deleteSecRule(t, ruleID) - - // list security group rule - listSecRules(t) - - // get security group rule - getSecRule(t, ruleID) -} - -func createSecGroup(t *testing.T) string { - sg, err := rsGroups.Create(Client, osGroups.CreateOpts{ - Name: "new-webservers", - Description: "security group for webservers", - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created security group %s", sg.ID) - - return sg.ID -} - -func listSecGroups(t *testing.T) { - err := rsGroups.List(Client, osGroups.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - list, err := osGroups.ExtractGroups(page) - if err != nil { - t.Errorf("Failed to extract secgroups: %v", err) - return false, err - } - - for _, sg := range list { - t.Logf("Listing security group: ID [%s] Name [%s]", sg.ID, sg.Name) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getSecGroup(t *testing.T, id string) { - sg, err := rsGroups.Get(Client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting security group: ID [%s] Name [%s] Description [%s]", sg.ID, sg.Name, sg.Description) -} - -func createSecGroupPort(t *testing.T, groupID string) (string, string) { - n, err := rsNetworks.Create(Client, osNetworks.CreateOpts{Name: "tmp_network"}).Extract() - th.AssertNoErr(t, err) - t.Logf("Created network %s", n.ID) - - opts := osPorts.CreateOpts{ - NetworkID: n.ID, - Name: "my_port", - SecurityGroups: []string{groupID}, - } - p, err := rsPorts.Create(Client, opts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created port %s with security group %s", p.ID, groupID) - - return n.ID, p.ID -} - -func deleteSecGroup(t *testing.T, groupID string) { - res := rsGroups.Delete(Client, groupID) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted security group %s", groupID) -} - -func createSecRule(t *testing.T, groupID string) string { - r, err := rsRules.Create(Client, osRules.CreateOpts{ - Direction: "ingress", - PortRangeMin: 80, - EtherType: "IPv4", - PortRangeMax: 80, - Protocol: "tcp", - SecGroupID: groupID, - }).Extract() - - th.AssertNoErr(t, err) - - t.Logf("Created security group rule %s", r.ID) - - return r.ID -} - -func listSecRules(t *testing.T) { - err := rsRules.List(Client, osRules.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - list, err := osRules.ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract sec rules: %v", err) - return false, err - } - - for _, r := range list { - t.Logf("Listing security rule: ID [%s]", r.ID) - } - - return true, nil - }) - - th.AssertNoErr(t, err) -} - -func getSecRule(t *testing.T, id string) { - r, err := rsRules.Get(Client, id).Extract() - th.AssertNoErr(t, err) - t.Logf("Getting security rule: ID [%s] Direction [%s] EtherType [%s] Protocol [%s]", - r.ID, r.Direction, r.EtherType, r.Protocol) -} - -func deleteSecRule(t *testing.T, id string) { - res := rsRules.Delete(Client, id) - th.AssertNoErr(t, res.Err) - t.Logf("Deleted security rule %s", id) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/subnet_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/subnet_test.go deleted file mode 100644 index c4014320a4c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/networking/v2/subnet_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build acceptance networking - -package v2 - -import ( - "testing" - - osNetworks "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - osSubnets "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/networking/v2/networks" - "github.com/rackspace/gophercloud/rackspace/networking/v2/subnets" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestListSubnets(t *testing.T) { - Setup(t) - defer Teardown() - - pager := subnets.List(Client, osSubnets.ListOpts{Limit: 2}) - err := pager.EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page ---") - - subnetList, err := osSubnets.ExtractSubnets(page) - th.AssertNoErr(t, err) - - for _, s := range subnetList { - t.Logf("Subnet: ID [%s] Name [%s] IP Version [%d] CIDR [%s] GatewayIP [%s]", - s.ID, s.Name, s.IPVersion, s.CIDR, s.GatewayIP) - } - - return true, nil - }) - th.CheckNoErr(t, err) -} - -func TestSubnetCRUD(t *testing.T) { - Setup(t) - defer Teardown() - - // Setup network - t.Log("Setting up network") - n, err := networks.Create(Client, osNetworks.CreateOpts{Name: "tmp_network", AdminStateUp: osNetworks.Up}).Extract() - th.AssertNoErr(t, err) - networkID := n.ID - defer networks.Delete(Client, networkID) - - // Create subnet - t.Log("Create subnet") - enable := false - opts := osSubnets.CreateOpts{ - NetworkID: networkID, - CIDR: "192.168.199.0/24", - IPVersion: osSubnets.IPv4, - Name: "my_subnet", - EnableDHCP: &enable, - } - s, err := subnets.Create(Client, opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, networkID, s.NetworkID) - th.AssertEquals(t, "192.168.199.0/24", s.CIDR) - th.AssertEquals(t, 4, s.IPVersion) - th.AssertEquals(t, "my_subnet", s.Name) - th.AssertEquals(t, false, s.EnableDHCP) - subnetID := s.ID - - // Get subnet - t.Log("Getting subnet") - s, err = subnets.Get(Client, subnetID).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, subnetID, s.ID) - - // Update subnet - t.Log("Update subnet") - s, err = subnets.Update(Client, subnetID, osSubnets.UpdateOpts{Name: "new_subnet_name"}).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "new_subnet_name", s.Name) - - // Delete subnet - t.Log("Delete subnet") - res := subnets.Delete(Client, subnetID) - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/accounts_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/accounts_test.go deleted file mode 100644 index 8b3cde45e45..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/accounts_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build acceptance rackspace - -package v1 - -import ( - "testing" - - raxAccounts "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAccounts(t *testing.T) { - c, err := createClient(t, false) - th.AssertNoErr(t, err) - - updateHeaders, err := raxAccounts.Update(c, raxAccounts.UpdateOpts{Metadata: map[string]string{"white": "mountains"}}).Extract() - th.AssertNoErr(t, err) - t.Logf("Update Account Response Headers: %+v\n", updateHeaders) - defer func() { - updateres := raxAccounts.Update(c, raxAccounts.UpdateOpts{Metadata: map[string]string{"white": ""}}) - th.AssertNoErr(t, updateres.Err) - metadata, err := raxAccounts.Get(c).ExtractMetadata() - th.AssertNoErr(t, err) - t.Logf("Metadata from Get Account request (after update reverted): %+v\n", metadata) - th.CheckEquals(t, metadata["White"], "") - }() - - getResp := raxAccounts.Get(c) - th.AssertNoErr(t, getResp.Err) - - getHeaders, _ := getResp.Extract() - t.Logf("Get Account Response Headers: %+v\n", getHeaders) - - metadata, _ := getResp.ExtractMetadata() - t.Logf("Metadata from Get Account request (after update): %+v\n", metadata) - - th.CheckEquals(t, metadata["White"], "mountains") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/bulk_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/bulk_test.go deleted file mode 100644 index 79013a564a9..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/bulk_test.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build acceptance rackspace objectstorage v1 - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBulk(t *testing.T) { - c, err := createClient(t, false) - th.AssertNoErr(t, err) - - var options bulk.DeleteOpts - options = append(options, "container/object1") - res := bulk.Delete(c, options) - th.AssertNoErr(t, res.Err) - body, err := res.ExtractBody() - th.AssertNoErr(t, err) - t.Logf("Response body from Bulk Delete Request: %+v\n", body) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdncontainers_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdncontainers_test.go deleted file mode 100644 index 0f56f4978af..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdncontainers_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build acceptance rackspace objectstorage v1 - -package v1 - -import ( - "testing" - - osContainers "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/pagination" - raxCDNContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers" - raxContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCDNContainers(t *testing.T) { - raxClient, err := createClient(t, false) - th.AssertNoErr(t, err) - - createres := raxContainers.Create(raxClient, "gophercloud-test", nil) - th.AssertNoErr(t, createres.Err) - t.Logf("Headers from Create Container request: %+v\n", createres.Header) - defer func() { - res := raxContainers.Delete(raxClient, "gophercloud-test") - th.AssertNoErr(t, res.Err) - }() - - raxCDNClient, err := createClient(t, true) - th.AssertNoErr(t, err) - enableRes := raxCDNContainers.Enable(raxCDNClient, "gophercloud-test", raxCDNContainers.EnableOpts{CDNEnabled: true, TTL: 900}) - t.Logf("Header map from Enable CDN Container request: %+v\n", enableRes.Header) - enableHeader, err := enableRes.Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Enable CDN Container request: %+v\n", enableHeader) - - t.Logf("Container Names available to the currently issued token:") - count := 0 - err = raxCDNContainers.List(raxCDNClient, &osContainers.ListOpts{Full: false}).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - names, err := raxCDNContainers.ExtractNames(page) - th.AssertNoErr(t, err) - - for i, name := range names { - t.Logf("[%02d] %s", i, name) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No CDN containers listed for your current token.") - } - - updateOpts := raxCDNContainers.UpdateOpts{XCDNEnabled: raxCDNContainers.Disabled, XLogRetention: raxCDNContainers.Enabled} - updateHeader, err := raxCDNContainers.Update(raxCDNClient, "gophercloud-test", updateOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Update CDN Container request: %+v\n", updateHeader) - - getRes := raxCDNContainers.Get(raxCDNClient, "gophercloud-test") - getHeader, err := getRes.Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Get CDN Container request (after update): %+v\n", getHeader) - metadata, err := getRes.ExtractMetadata() - t.Logf("Metadata from Get CDN Container request (after update): %+v\n", metadata) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdnobjects_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdnobjects_test.go deleted file mode 100644 index 0c0ab8a1ed0..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/cdnobjects_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build acceptance rackspace objectstorage v1 - -package v1 - -import ( - "bytes" - "testing" - - raxCDNContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers" - raxCDNObjects "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdnobjects" - raxContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers" - raxObjects "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCDNObjects(t *testing.T) { - raxClient, err := createClient(t, false) - th.AssertNoErr(t, err) - - createContResult := raxContainers.Create(raxClient, "gophercloud-test", nil) - th.AssertNoErr(t, createContResult.Err) - t.Logf("Headers from Create Container request: %+v\n", createContResult.Header) - defer func() { - deleteResult := raxContainers.Delete(raxClient, "gophercloud-test") - th.AssertNoErr(t, deleteResult.Err) - }() - - header, err := raxObjects.Create(raxClient, "gophercloud-test", "test-object", bytes.NewBufferString("gophercloud cdn test"), nil).ExtractHeader() - th.AssertNoErr(t, err) - t.Logf("Headers from Create Object request: %+v\n", header) - defer func() { - deleteResult := raxObjects.Delete(raxClient, "gophercloud-test", "test-object", nil) - th.AssertNoErr(t, deleteResult.Err) - }() - - raxCDNClient, err := createClient(t, true) - th.AssertNoErr(t, err) - - enableHeader, err := raxCDNContainers.Enable(raxCDNClient, "gophercloud-test", raxCDNContainers.EnableOpts{CDNEnabled: true, TTL: 900}).Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Enable CDN Container request: %+v\n", enableHeader) - - objCDNURL, err := raxCDNObjects.CDNURL(raxCDNClient, "gophercloud-test", "test-object") - th.AssertNoErr(t, err) - t.Logf("%s CDN URL: %s\n", "test_object", objCDNURL) - - deleteHeader, err := raxCDNObjects.Delete(raxCDNClient, "gophercloud-test", "test-object", nil).Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Delete CDN Object request: %+v\n", deleteHeader) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/containers_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/containers_test.go deleted file mode 100644 index c89551373f1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/containers_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// +build acceptance rackspace objectstorage v1 - -package v1 - -import ( - "testing" - - osContainers "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/pagination" - raxContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestContainers(t *testing.T) { - c, err := createClient(t, false) - th.AssertNoErr(t, err) - - t.Logf("Containers Info available to the currently issued token:") - count := 0 - err = raxContainers.List(c, &osContainers.ListOpts{Full: true}).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - containers, err := raxContainers.ExtractInfo(page) - th.AssertNoErr(t, err) - - for i, container := range containers { - t.Logf("[%02d] name=[%s]", i, container.Name) - t.Logf(" count=[%d]", container.Count) - t.Logf(" bytes=[%d]", container.Bytes) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No containers listed for your current token.") - } - - t.Logf("Container Names available to the currently issued token:") - count = 0 - err = raxContainers.List(c, &osContainers.ListOpts{Full: false}).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - names, err := raxContainers.ExtractNames(page) - th.AssertNoErr(t, err) - - for i, name := range names { - t.Logf("[%02d] %s", i, name) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No containers listed for your current token.") - } - - createHeader, err := raxContainers.Create(c, "gophercloud-test", nil).Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Create Container request: %+v\n", createHeader) - defer func() { - deleteres := raxContainers.Delete(c, "gophercloud-test") - deleteHeader, err := deleteres.Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Delete Container request: %+v\n", deleteres.Header) - t.Logf("Headers from Delete Container request: %+v\n", deleteHeader) - }() - - updateHeader, err := raxContainers.Update(c, "gophercloud-test", raxContainers.UpdateOpts{Metadata: map[string]string{"white": "mountains"}}).Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Update Container request: %+v\n", updateHeader) - defer func() { - res := raxContainers.Update(c, "gophercloud-test", raxContainers.UpdateOpts{Metadata: map[string]string{"white": ""}}) - th.AssertNoErr(t, res.Err) - metadata, err := raxContainers.Get(c, "gophercloud-test").ExtractMetadata() - th.AssertNoErr(t, err) - t.Logf("Metadata from Get Container request (after update reverted): %+v\n", metadata) - th.CheckEquals(t, metadata["White"], "") - }() - - getres := raxContainers.Get(c, "gophercloud-test") - getHeader, err := getres.Extract() - th.AssertNoErr(t, err) - t.Logf("Headers from Get Container request (after update): %+v\n", getHeader) - metadata, err := getres.ExtractMetadata() - t.Logf("Metadata from Get Container request (after update): %+v\n", metadata) - th.CheckEquals(t, metadata["White"], "mountains") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/objects_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/objects_test.go deleted file mode 100644 index 585dea7696a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/objectstorage/v1/objects_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// +build acceptance rackspace objectstorage v1 - -package v1 - -import ( - "bytes" - "testing" - - osObjects "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects" - "github.com/rackspace/gophercloud/pagination" - raxContainers "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers" - raxObjects "github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestObjects(t *testing.T) { - c, err := createClient(t, false) - th.AssertNoErr(t, err) - - res := raxContainers.Create(c, "gophercloud-test", nil) - th.AssertNoErr(t, res.Err) - - defer func() { - t.Logf("Deleting container...") - res := raxContainers.Delete(c, "gophercloud-test") - th.AssertNoErr(t, res.Err) - }() - - content := bytes.NewBufferString("Lewis Carroll") - options := &osObjects.CreateOpts{ContentType: "text/plain"} - createres := raxObjects.Create(c, "gophercloud-test", "o1", content, options) - th.AssertNoErr(t, createres.Err) - - defer func() { - t.Logf("Deleting object o1...") - res := raxObjects.Delete(c, "gophercloud-test", "o1", nil) - th.AssertNoErr(t, res.Err) - }() - - t.Logf("Objects Info available to the currently issued token:") - count := 0 - err = raxObjects.List(c, "gophercloud-test", &osObjects.ListOpts{Full: true}).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - objects, err := raxObjects.ExtractInfo(page) - th.AssertNoErr(t, err) - - for i, object := range objects { - t.Logf("[%02d] name=[%s]", i, object.Name) - t.Logf(" content-type=[%s]", object.ContentType) - t.Logf(" bytes=[%d]", object.Bytes) - t.Logf(" last-modified=[%s]", object.LastModified) - t.Logf(" hash=[%s]", object.Hash) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No objects listed for your current token.") - } - t.Logf("Container Names available to the currently issued token:") - count = 0 - err = raxObjects.List(c, "gophercloud-test", &osObjects.ListOpts{Full: false}).EachPage(func(page pagination.Page) (bool, error) { - t.Logf("--- Page %02d ---", count) - - names, err := raxObjects.ExtractNames(page) - th.AssertNoErr(t, err) - - for i, name := range names { - t.Logf("[%02d] %s", i, name) - } - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - if count == 0 { - t.Errorf("No objects listed for your current token.") - } - - copyres := raxObjects.Copy(c, "gophercloud-test", "o1", &raxObjects.CopyOpts{Destination: "gophercloud-test/o2"}) - th.AssertNoErr(t, copyres.Err) - defer func() { - t.Logf("Deleting object o2...") - res := raxObjects.Delete(c, "gophercloud-test", "o2", nil) - th.AssertNoErr(t, res.Err) - }() - - o1Content, err := raxObjects.Download(c, "gophercloud-test", "o1", nil).ExtractContent() - th.AssertNoErr(t, err) - o2Content, err := raxObjects.Download(c, "gophercloud-test", "o2", nil).ExtractContent() - th.AssertNoErr(t, err) - th.AssertEquals(t, string(o2Content), string(o1Content)) - - updateres := raxObjects.Update(c, "gophercloud-test", "o2", osObjects.UpdateOpts{Metadata: map[string]string{"white": "mountains"}}) - th.AssertNoErr(t, updateres.Err) - t.Logf("Headers from Update Account request: %+v\n", updateres.Header) - defer func() { - res := raxObjects.Update(c, "gophercloud-test", "o2", osObjects.UpdateOpts{Metadata: map[string]string{"white": ""}}) - th.AssertNoErr(t, res.Err) - metadata, err := raxObjects.Get(c, "gophercloud-test", "o2", nil).ExtractMetadata() - th.AssertNoErr(t, err) - t.Logf("Metadata from Get Account request (after update reverted): %+v\n", metadata) - th.CheckEquals(t, "", metadata["White"]) - }() - - getres := raxObjects.Get(c, "gophercloud-test", "o2", nil) - th.AssertNoErr(t, getres.Err) - t.Logf("Headers from Get Account request (after update): %+v\n", getres.Header) - metadata, err := getres.ExtractMetadata() - th.AssertNoErr(t, err) - t.Logf("Metadata from Get Account request (after update): %+v\n", metadata) - th.CheckEquals(t, "mountains", metadata["White"]) - - createTempURLOpts := osObjects.CreateTempURLOpts{ - Method: osObjects.GET, - TTL: 600, - } - tempURL, err := raxObjects.CreateTempURL(c, "gophercloud-test", "o1", createTempURLOpts) - th.AssertNoErr(t, err) - t.Logf("TempURL for object (%s): %s", "o1", tempURL) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/buildinfo_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/buildinfo_test.go deleted file mode 100644 index 42cc048e3b8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/buildinfo_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/buildinfo" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestBuildInfo(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - bi, err := buildinfo.Get(client).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved build info: %+v\n", bi) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackevents_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackevents_test.go deleted file mode 100644 index 9e3fc084ad8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackevents_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - osStackEvents "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents" - osStacks "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackevents" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackEvents(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - resourceName := "hello_world" - var eventID string - - createOpts := osStacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - err = stackevents.List(client, stackName, stack.ID, nil).EachPage(func(page pagination.Page) (bool, error) { - events, err := osStackEvents.ExtractEvents(page) - th.AssertNoErr(t, err) - t.Logf("listed events: %+v\n", events) - eventID = events[0].ID - return false, nil - }) - th.AssertNoErr(t, err) - - err = stackevents.ListResourceEvents(client, stackName, stack.ID, resourceName, nil).EachPage(func(page pagination.Page) (bool, error) { - resourceEvents, err := osStackEvents.ExtractResourceEvents(page) - th.AssertNoErr(t, err) - t.Logf("listed resource events: %+v\n", resourceEvents) - return false, nil - }) - th.AssertNoErr(t, err) - - event, err := stackevents.Get(client, stackName, stack.ID, resourceName, eventID).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved event: %+v\n", event) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackresources_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackresources_test.go deleted file mode 100644 index 65926e78dc6..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stackresources_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - osStackResources "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources" - osStacks "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackResources(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - - createOpts := osStacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - resourceName := "hello_world" - resource, err := stackresources.Get(client, stackName, stack.ID, resourceName).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack resource: %+v\n", resource) - - metadata, err := stackresources.Metadata(client, stackName, stack.ID, resourceName).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack resource metadata: %+v\n", metadata) - - err = stackresources.List(client, stackName, stack.ID, nil).EachPage(func(page pagination.Page) (bool, error) { - resources, err := osStackResources.ExtractResources(page) - th.AssertNoErr(t, err) - t.Logf("resources: %+v\n", resources) - return false, nil - }) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacks_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacks_test.go deleted file mode 100644 index cfec4e9817e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacks_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - osStacks "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStacks(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName1 := "gophercloud-test-stack-2" - createOpts := osStacks.CreateOpts{ - Name: stackName1, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName1, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName1) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - updateOpts := osStacks.UpdateOpts{ - Template: template, - Timeout: 20, - } - err = stacks.Update(client, stackName1, stack.ID, updateOpts).ExtractErr() - th.AssertNoErr(t, err) - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "UPDATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - t.Logf("Updated stack") - - err = stacks.List(client, nil).EachPage(func(page pagination.Page) (bool, error) { - stackList, err := osStacks.ExtractStacks(page) - th.AssertNoErr(t, err) - - t.Logf("Got stack list: %+v\n", stackList) - - return true, nil - }) - th.AssertNoErr(t, err) - - getStack, err := stacks.Get(client, stackName1, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Got stack: %+v\n", getStack) - - abandonedStack, err := stacks.Abandon(client, stackName1, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("Abandonded stack %+v\n", abandonedStack) - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacktemplates_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacktemplates_test.go deleted file mode 100644 index 1f7b2171065..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/orchestration/v1/stacktemplates_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// +build acceptance - -package v1 - -import ( - "testing" - - "github.com/rackspace/gophercloud" - osStacks "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - osStacktemplates "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestStackTemplates(t *testing.T) { - // Create a provider client for making the HTTP requests. - // See common.go in this directory for more information. - client := newClient(t) - - stackName := "postman_stack_2" - - createOpts := osStacks.CreateOpts{ - Name: stackName, - Template: template, - Timeout: 5, - } - stack, err := stacks.Create(client, createOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("Created stack: %+v\n", stack) - defer func() { - err := stacks.Delete(client, stackName, stack.ID).ExtractErr() - th.AssertNoErr(t, err) - t.Logf("Deleted stack (%s)", stackName) - }() - err = gophercloud.WaitFor(60, func() (bool, error) { - getStack, err := stacks.Get(client, stackName, stack.ID).Extract() - if err != nil { - return false, err - } - if getStack.Status == "CREATE_COMPLETE" { - return true, nil - } - return false, nil - }) - - tmpl, err := stacktemplates.Get(client, stackName, stack.ID).Extract() - th.AssertNoErr(t, err) - t.Logf("retrieved template: %+v\n", tmpl) - - validateOpts := osStacktemplates.ValidateOpts{ - Template: map[string]interface{}{ - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": map[string]interface{}{ - "flavor": map[string]interface{}{ - "default": "m1.tiny", - "type": "string", - }, - }, - "resources": map[string]interface{}{ - "hello_world": map[string]interface{}{ - "type": "OS::Nova::Server", - "properties": map[string]interface{}{ - "key_name": "heat_key", - "flavor": map[string]interface{}{ - "get_param": "flavor", - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n", - }, - }, - }, - }, - } - validatedTemplate, err := stacktemplates.Validate(client, validateOpts).Extract() - th.AssertNoErr(t, err) - t.Logf("validated template: %+v\n", validatedTemplate) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/cloudnetworks_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/cloudnetworks_test.go deleted file mode 100644 index 2c6287e9f77..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/cloudnetworks_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "fmt" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/rackconnect/v3/cloudnetworks" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCloudNetworks(t *testing.T) { - c := newClient(t) - cnID := testListNetworks(t, c) - testGetNetworks(t, c, cnID) -} - -func testListNetworks(t *testing.T, c *gophercloud.ServiceClient) string { - allPages, err := cloudnetworks.List(c).AllPages() - th.AssertNoErr(t, err) - allcn, err := cloudnetworks.ExtractCloudNetworks(allPages) - fmt.Printf("Listing all cloud networks: %+v\n\n", allcn) - var cnID string - if len(allcn) > 0 { - cnID = allcn[0].ID - } - return cnID -} - -func testGetNetworks(t *testing.T, c *gophercloud.ServiceClient, id string) { - cn, err := cloudnetworks.Get(c, id).Extract() - th.AssertNoErr(t, err) - fmt.Printf("Retrieved cloud network: %+v\n\n", cn) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/lbpools_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/lbpools_test.go deleted file mode 100644 index 85ac931b9ca..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/lbpools_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "fmt" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/rackconnect/v3/lbpools" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestLBPools(t *testing.T) { - c := newClient(t) - pID := testListPools(t, c) - testGetPools(t, c, pID) - nID := testListNodes(t, c, pID) - testListNodeDetails(t, c, pID) - testGetNode(t, c, pID, nID) - testGetNodeDetails(t, c, pID, nID) -} - -func testListPools(t *testing.T, c *gophercloud.ServiceClient) string { - allPages, err := lbpools.List(c).AllPages() - th.AssertNoErr(t, err) - allp, err := lbpools.ExtractPools(allPages) - fmt.Printf("Listing all LB pools: %+v\n\n", allp) - var pID string - if len(allp) > 0 { - pID = allp[0].ID - } - return pID -} - -func testGetPools(t *testing.T, c *gophercloud.ServiceClient, pID string) { - p, err := lbpools.Get(c, pID).Extract() - th.AssertNoErr(t, err) - fmt.Printf("Retrieved LB pool: %+v\n\n", p) -} - -func testListNodes(t *testing.T, c *gophercloud.ServiceClient, pID string) string { - allPages, err := lbpools.ListNodes(c, pID).AllPages() - th.AssertNoErr(t, err) - alln, err := lbpools.ExtractNodes(allPages) - fmt.Printf("Listing all LB pool nodes for pool (%s): %+v\n\n", pID, alln) - var nID string - if len(alln) > 0 { - nID = alln[0].ID - } - return nID -} - -func testListNodeDetails(t *testing.T, c *gophercloud.ServiceClient, pID string) { - allPages, err := lbpools.ListNodesDetails(c, pID).AllPages() - th.AssertNoErr(t, err) - alln, err := lbpools.ExtractNodesDetails(allPages) - fmt.Printf("Listing all LB pool nodes details for pool (%s): %+v\n\n", pID, alln) -} - -func testGetNode(t *testing.T, c *gophercloud.ServiceClient, pID, nID string) { - n, err := lbpools.GetNode(c, pID, nID).Extract() - th.AssertNoErr(t, err) - fmt.Printf("Retrieved LB node: %+v\n\n", n) -} - -func testGetNodeDetails(t *testing.T, c *gophercloud.ServiceClient, pID, nID string) { - n, err := lbpools.GetNodeDetails(c, pID, nID).Extract() - th.AssertNoErr(t, err) - fmt.Printf("Retrieved LB node details: %+v\n\n", n) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/publicips_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/publicips_test.go deleted file mode 100644 index 8dc62703ba7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/rackspace/rackconnect/v3/publicips_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build acceptance - -package v3 - -import ( - "fmt" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/rackspace/rackconnect/v3/publicips" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestPublicIPs(t *testing.T) { - c := newClient(t) - ipID := testListIPs(t, c) - sID := testGetIP(t, c, ipID) - testListIPsForServer(t, c, sID) -} - -func testListIPs(t *testing.T, c *gophercloud.ServiceClient) string { - allPages, err := publicips.List(c).AllPages() - th.AssertNoErr(t, err) - allip, err := publicips.ExtractPublicIPs(allPages) - fmt.Printf("Listing all public IPs: %+v\n\n", allip) - var ipID string - if len(allip) > 0 { - ipID = allip[0].ID - } - return ipID -} - -func testGetIP(t *testing.T, c *gophercloud.ServiceClient, ipID string) string { - ip, err := publicips.Get(c, ipID).Extract() - th.AssertNoErr(t, err) - fmt.Printf("Retrieved public IP (%s): %+v\n\n", ipID, ip) - return ip.CloudServer.ID -} - -func testListIPsForServer(t *testing.T, c *gophercloud.ServiceClient, sID string) { - allPages, err := publicips.ListForServer(c, sID).AllPages() - th.AssertNoErr(t, err) - allip, err := publicips.ExtractPublicIPs(allPages) - fmt.Printf("Listing all public IPs for server (%s): %+v\n\n", sID, allip) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/endpoint_search_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/endpoint_search_test.go deleted file mode 100644 index 34574534274..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/endpoint_search_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package gophercloud - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestApplyDefaultsToEndpointOpts(t *testing.T) { - eo := EndpointOpts{Availability: AvailabilityPublic} - eo.ApplyDefaults("compute") - expected := EndpointOpts{Availability: AvailabilityPublic, Type: "compute"} - th.CheckDeepEquals(t, expected, eo) - - eo = EndpointOpts{Type: "compute"} - eo.ApplyDefaults("object-store") - expected = EndpointOpts{Availability: AvailabilityPublic, Type: "compute"} - th.CheckDeepEquals(t, expected, eo) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/requests_test.go deleted file mode 100644 index 56b5e4fc72b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/requests_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package apiversions - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListVersions(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, `{ - "versions": [ - { - "status": "CURRENT", - "updated": "2012-01-04T11:33:21Z", - "id": "v1.0", - "links": [ - { - "href": "http://23.253.228.211:8776/v1/", - "rel": "self" - } - ] - }, - { - "status": "CURRENT", - "updated": "2012-11-21T11:33:21Z", - "id": "v2.0", - "links": [ - { - "href": "http://23.253.228.211:8776/v2/", - "rel": "self" - } - ] - } - ] - }`) - }) - - count := 0 - - List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractAPIVersions(page) - if err != nil { - t.Errorf("Failed to extract API versions: %v", err) - return false, err - } - - expected := []APIVersion{ - APIVersion{ - ID: "v1.0", - Status: "CURRENT", - Updated: "2012-01-04T11:33:21Z", - }, - APIVersion{ - ID: "v2.0", - Status: "CURRENT", - Updated: "2012-11-21T11:33:21Z", - }, - } - - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestAPIInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v1/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, `{ - "version": { - "status": "CURRENT", - "updated": "2012-01-04T11:33:21Z", - "media-types": [ - { - "base": "application/xml", - "type": "application/vnd.openstack.volume+xml;version=1" - }, - { - "base": "application/json", - "type": "application/vnd.openstack.volume+json;version=1" - } - ], - "id": "v1.0", - "links": [ - { - "href": "http://23.253.228.211:8776/v1/", - "rel": "self" - }, - { - "href": "http://jorgew.github.com/block-storage-api/content/os-block-storage-1.0.pdf", - "type": "application/pdf", - "rel": "describedby" - }, - { - "href": "http://docs.rackspacecloud.com/servers/api/v1.1/application.wadl", - "type": "application/vnd.sun.wadl+xml", - "rel": "describedby" - } - ] - } - }`) - }) - - actual, err := Get(client.ServiceClient(), "v1").Extract() - if err != nil { - t.Errorf("Failed to extract version: %v", err) - } - - expected := APIVersion{ - ID: "v1.0", - Status: "CURRENT", - Updated: "2012-01-04T11:33:21Z", - } - - th.AssertEquals(t, actual.ID, expected.ID) - th.AssertEquals(t, actual.Status, expected.Status) - th.AssertEquals(t, actual.Updated, expected.Updated) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/urls_test.go deleted file mode 100644 index 37e91425b5a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/apiversions/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package apiversions - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "v1") - expected := endpoint + "v1/" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/requests_test.go deleted file mode 100644 index d0f9e887e81..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/requests_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package snapshots - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockListResponse(t) - - count := 0 - - List(client.ServiceClient(), &ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractSnapshots(page) - if err != nil { - t.Errorf("Failed to extract snapshots: %v", err) - return false, err - } - - expected := []Snapshot{ - Snapshot{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "snapshot-001", - }, - Snapshot{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "snapshot-002", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockGetResponse(t) - - v, err := Get(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, v.Name, "snapshot-001") - th.AssertEquals(t, v.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockCreateResponse(t) - - options := CreateOpts{VolumeID: "1234", Name: "snapshot-001"} - n, err := Create(client.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.VolumeID, "1234") - th.AssertEquals(t, n.Name, "snapshot-001") - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestUpdateMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockUpdateMetadataResponse(t) - - expected := map[string]interface{}{"key": "v1"} - - options := &UpdateMetadataOpts{ - Metadata: map[string]interface{}{ - "key": "v1", - }, - } - - actual, err := UpdateMetadata(client.ServiceClient(), "123", options).ExtractMetadata() - - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, actual, expected) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockDeleteResponse(t) - - res := Delete(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/urls_test.go deleted file mode 100644 index feacf7f69b5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots/urls_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package snapshots - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "snapshots" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "snapshots/foo" - th.AssertEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "snapshots/foo" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "snapshots" - th.AssertEquals(t, expected, actual) -} - -func TestMetadataURL(t *testing.T) { - actual := metadataURL(endpointClient(), "foo") - expected := endpoint + "snapshots/foo/metadata" - th.AssertEquals(t, expected, actual) -} - -func TestUpdateMetadataURL(t *testing.T) { - actual := updateMetadataURL(endpointClient(), "foo") - expected := endpoint + "snapshots/foo/metadata" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests_test.go deleted file mode 100644 index 75c2bbc5965..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/requests_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package volumes - -import ( - "testing" - - fixtures "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/testing" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockListResponse(t) - - count := 0 - - List(client.ServiceClient(), &ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVolumes(page) - if err != nil { - t.Errorf("Failed to extract volumes: %v", err) - return false, err - } - - expected := []Volume{ - Volume{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "vol-001", - }, - Volume{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "vol-002", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestListAll(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockListResponse(t) - - allPages, err := List(client.ServiceClient(), &ListOpts{}).AllPages() - th.AssertNoErr(t, err) - actual, err := ExtractVolumes(allPages) - th.AssertNoErr(t, err) - - expected := []Volume{ - Volume{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "vol-001", - }, - Volume{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "vol-002", - }, - } - - th.CheckDeepEquals(t, expected, actual) - -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockGetResponse(t) - - v, err := Get(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, v.Name, "vol-001") - th.AssertEquals(t, v.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertEquals(t, v.Attachments[0]["device"], "/dev/vde") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockCreateResponse(t) - - options := &CreateOpts{Size: 75} - n, err := Create(client.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Size, 4) - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockDeleteResponse(t) - - res := Delete(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertNoErr(t, res.Err) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - fixtures.MockUpdateResponse(t) - - options := UpdateOpts{Name: "vol-002"} - v, err := Update(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22", options).Extract() - th.AssertNoErr(t, err) - th.CheckEquals(t, "vol-002", v.Name) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls_test.go deleted file mode 100644 index a95270e14cb..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/urls_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package volumes - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "volumes" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "volumes" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "volumes/foo" - th.AssertEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "volumes/foo" - th.AssertEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "volumes/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/requests_test.go deleted file mode 100644 index 8d40bfe1d48..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/requests_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package volumetypes - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockListResponse(t) - - count := 0 - - List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVolumeTypes(page) - if err != nil { - t.Errorf("Failed to extract volume types: %v", err) - return false, err - } - - expected := []VolumeType{ - VolumeType{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "vol-type-001", - ExtraSpecs: map[string]interface{}{ - "capabilities": "gpu", - }, - }, - VolumeType{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "vol-type-002", - ExtraSpecs: map[string]interface{}{}, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockGetResponse(t) - - vt, err := Get(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, vt.ExtraSpecs, map[string]interface{}{"serverNumber": "2"}) - th.AssertEquals(t, vt.Name, "vol-type-001") - th.AssertEquals(t, vt.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/types", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "volume_type": { - "name": "vol-type-001" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "volume_type": { - "name": "vol-type-001", - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - } -} - `) - }) - - options := &CreateOpts{Name: "vol-type-001"} - n, err := Create(client.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Name, "vol-type-001") - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/types/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - w.WriteHeader(http.StatusAccepted) - }) - - err := Delete(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/urls_test.go deleted file mode 100644 index 44016e29549..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes/urls_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package volumetypes - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "types" - th.AssertEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "types" - th.AssertEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "types/foo" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "types/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/base/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/base/requests_test.go deleted file mode 100644 index 2c20a71103f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/base/requests_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package base - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetHomeDocument(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(fake.ServiceClient()).Extract() - th.CheckNoErr(t, err) - - expected := HomeDocument{ - "rel/cdn": map[string]interface{}{ - "href-template": "services{?marker,limit}", - "href-vars": map[string]interface{}{ - "marker": "param/marker", - "limit": "param/limit", - }, - "hints": map[string]interface{}{ - "allow": []string{"GET"}, - "formats": map[string]interface{}{ - "application/json": map[string]interface{}{}, - }, - }, - }, - } - th.CheckDeepEquals(t, expected, *actual) -} - -func TestPing(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandlePingSuccessfully(t) - - err := Ping(fake.ServiceClient()).ExtractErr() - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/flavors/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/flavors/requests_test.go deleted file mode 100644 index f7317382797..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/flavors/requests_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package flavors - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleListCDNFlavorsSuccessfully(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractFlavors(page) - if err != nil { - t.Errorf("Failed to extract flavors: %v", err) - return false, err - } - - expected := []Flavor{ - Flavor{ - ID: "europe", - Providers: []Provider{ - Provider{ - Provider: "Fastly", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "http://www.fastly.com", - Rel: "provider_url", - }, - }, - }, - }, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/europe", - Rel: "self", - }, - }, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleGetCDNFlavorSuccessfully(t) - - expected := &Flavor{ - ID: "asia", - Providers: []Provider{ - Provider{ - Provider: "ChinaCache", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "http://www.chinacache.com", - Rel: "provider_url", - }, - }, - }, - }, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/asia", - Rel: "self", - }, - }, - } - - actual, err := Get(fake.ServiceClient(), "asia").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets/requests_test.go deleted file mode 100644 index dde7bc171d2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets/requests_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package serviceassets - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleDeleteCDNAssetSuccessfully(t) - - err := Delete(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", nil).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/requests_test.go deleted file mode 100644 index 59e826f048d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/cdn/v1/services/requests_test.go +++ /dev/null @@ -1,358 +0,0 @@ -package services - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleListCDNServiceSuccessfully(t) - - count := 0 - - err := List(fake.ServiceClient(), &ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractServices(page) - if err != nil { - t.Errorf("Failed to extract services: %v", err) - return false, err - } - - expected := []Service{ - Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Name: "mywebsite.com", - Domains: []Domain{ - Domain{ - Domain: "www.mywebsite.com", - }, - }, - Origins: []Origin{ - Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Caching: []CacheRule{ - CacheRule{ - Name: "default", - TTL: 3600, - }, - CacheRule{ - Name: "home", - TTL: 17200, - Rules: []TTLRule{ - TTLRule{ - Name: "index", - RequestURL: "/index.htm", - }, - }, - }, - CacheRule{ - Name: "images", - TTL: 12800, - Rules: []TTLRule{ - TTLRule{ - Name: "images", - RequestURL: "*.png", - }, - }, - }, - }, - Restrictions: []Restriction{ - Restriction{ - Name: "website only", - Rules: []RestrictionRule{ - RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - FlavorID: "asia", - Status: "deployed", - Errors: []Error{}, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Rel: "self", - }, - gophercloud.Link{ - Href: "mywebsite.com.cdn123.poppycdn.net", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/asia", - Rel: "flavor", - }, - }, - }, - Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1", - Name: "myothersite.com", - Domains: []Domain{ - Domain{ - Domain: "www.myothersite.com", - }, - }, - Origins: []Origin{ - Origin{ - Origin: "44.33.22.11", - Port: 80, - SSL: false, - }, - Origin{ - Origin: "77.66.55.44", - Port: 80, - SSL: false, - Rules: []OriginRule{ - OriginRule{ - Name: "videos", - RequestURL: "^/videos/*.m3u", - }, - }, - }, - }, - Caching: []CacheRule{ - CacheRule{ - Name: "default", - TTL: 3600, - }, - }, - Restrictions: []Restriction{}, - FlavorID: "europe", - Status: "deployed", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1", - Rel: "self", - }, - gophercloud.Link{ - Href: "myothersite.com.poppycdn.net", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/europe", - Rel: "flavor", - }, - }, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleCreateCDNServiceSuccessfully(t) - - createOpts := CreateOpts{ - Name: "mywebsite.com", - Domains: []Domain{ - Domain{ - Domain: "www.mywebsite.com", - }, - Domain{ - Domain: "blog.mywebsite.com", - }, - }, - Origins: []Origin{ - Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Restrictions: []Restriction{ - Restriction{ - Name: "website only", - Rules: []RestrictionRule{ - RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - Caching: []CacheRule{ - CacheRule{ - Name: "default", - TTL: 3600, - }, - }, - FlavorID: "cdn", - } - - expected := "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" - actual, err := Create(fake.ServiceClient(), createOpts).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, expected, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleGetCDNServiceSuccessfully(t) - - expected := &Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Name: "mywebsite.com", - Domains: []Domain{ - Domain{ - Domain: "www.mywebsite.com", - Protocol: "http", - }, - }, - Origins: []Origin{ - Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Caching: []CacheRule{ - CacheRule{ - Name: "default", - TTL: 3600, - }, - CacheRule{ - Name: "home", - TTL: 17200, - Rules: []TTLRule{ - TTLRule{ - Name: "index", - RequestURL: "/index.htm", - }, - }, - }, - CacheRule{ - Name: "images", - TTL: 12800, - Rules: []TTLRule{ - TTLRule{ - Name: "images", - RequestURL: "*.png", - }, - }, - }, - }, - Restrictions: []Restriction{ - Restriction{ - Name: "website only", - Rules: []RestrictionRule{ - RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - FlavorID: "cdn", - Status: "deployed", - Errors: []Error{}, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://global.cdn.api.rackspacecloud.com/v1.0/110011/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Rel: "self", - }, - gophercloud.Link{ - Href: "blog.mywebsite.com.cdn1.raxcdn.com", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://global.cdn.api.rackspacecloud.com/v1.0/110011/flavors/cdn", - Rel: "flavor", - }, - }, - } - - actual, err := Get(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestSuccessfulUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleUpdateCDNServiceSuccessfully(t) - - expected := "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" - ops := UpdateOpts{ - // Append a single Domain - Append{Value: Domain{Domain: "appended.mocksite4.com"}}, - // Insert a single Domain - Insertion{ - Index: 4, - Value: Domain{Domain: "inserted.mocksite4.com"}, - }, - // Bulk addition - Append{ - Value: DomainList{ - Domain{Domain: "bulkadded1.mocksite4.com"}, - Domain{Domain: "bulkadded2.mocksite4.com"}, - }, - }, - // Replace a single Origin - Replacement{ - Index: 2, - Value: Origin{Origin: "44.33.22.11", Port: 80, SSL: false}, - }, - // Bulk replace Origins - Replacement{ - Index: 0, // Ignored - Value: OriginList{ - Origin{Origin: "44.33.22.11", Port: 80, SSL: false}, - Origin{Origin: "55.44.33.22", Port: 443, SSL: true}, - }, - }, - // Remove a single CacheRule - Removal{ - Index: 8, - Path: PathCaching, - }, - // Bulk removal - Removal{ - All: true, - Path: PathCaching, - }, - // Service name replacement - NameReplacement{ - NewName: "differentServiceName", - }, - } - - actual, err := Update(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", ops).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, expected, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleDeleteCDNServiceSuccessfully(t) - - err := Delete(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/client_test.go deleted file mode 100644 index 257260c4e19..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/client_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package openstack - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAuthenticatedClientV3(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - const ID = "0123456789" - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, ` - { - "versions": { - "values": [ - { - "status": "stable", - "id": "v3.0", - "links": [ - { "href": "%s", "rel": "self" } - ] - }, - { - "status": "stable", - "id": "v2.0", - "links": [ - { "href": "%s", "rel": "self" } - ] - } - ] - } - } - `, th.Endpoint()+"v3/", th.Endpoint()+"v2.0/") - }) - - th.Mux.HandleFunc("/v3/auth/tokens", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("X-Subject-Token", ID) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ "token": { "expires_at": "2013-02-02T18:30:59.000000Z" } }`) - }) - - options := gophercloud.AuthOptions{ - UserID: "me", - Password: "secret", - IdentityEndpoint: th.Endpoint(), - } - client, err := AuthenticatedClient(options) - th.AssertNoErr(t, err) - th.CheckEquals(t, ID, client.TokenID) -} - -func TestAuthenticatedClientV2(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, ` - { - "versions": { - "values": [ - { - "status": "experimental", - "id": "v3.0", - "links": [ - { "href": "%s", "rel": "self" } - ] - }, - { - "status": "stable", - "id": "v2.0", - "links": [ - { "href": "%s", "rel": "self" } - ] - } - ] - } - } - `, th.Endpoint()+"v3/", th.Endpoint()+"v2.0/") - }) - - th.Mux.HandleFunc("/v2.0/tokens", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, ` - { - "access": { - "token": { - "id": "01234567890", - "expires": "2014-10-01T10:00:00.000000Z" - }, - "serviceCatalog": [ - { - "name": "Cloud Servers", - "type": "compute", - "endpoints": [ - { - "tenantId": "t1000", - "publicURL": "https://compute.north.host.com/v1/t1000", - "internalURL": "https://compute.north.internal/v1/t1000", - "region": "North", - "versionId": "1", - "versionInfo": "https://compute.north.host.com/v1/", - "versionList": "https://compute.north.host.com/" - }, - { - "tenantId": "t1000", - "publicURL": "https://compute.north.host.com/v1.1/t1000", - "internalURL": "https://compute.north.internal/v1.1/t1000", - "region": "North", - "versionId": "1.1", - "versionInfo": "https://compute.north.host.com/v1.1/", - "versionList": "https://compute.north.host.com/" - } - ], - "endpoints_links": [] - }, - { - "name": "Cloud Files", - "type": "object-store", - "endpoints": [ - { - "tenantId": "t1000", - "publicURL": "https://storage.north.host.com/v1/t1000", - "internalURL": "https://storage.north.internal/v1/t1000", - "region": "North", - "versionId": "1", - "versionInfo": "https://storage.north.host.com/v1/", - "versionList": "https://storage.north.host.com/" - }, - { - "tenantId": "t1000", - "publicURL": "https://storage.south.host.com/v1/t1000", - "internalURL": "https://storage.south.internal/v1/t1000", - "region": "South", - "versionId": "1", - "versionInfo": "https://storage.south.host.com/v1/", - "versionList": "https://storage.south.host.com/" - } - ] - } - ] - } - } - `) - }) - - options := gophercloud.AuthOptions{ - Username: "me", - Password: "secret", - IdentityEndpoint: th.Endpoint(), - } - client, err := AuthenticatedClient(options) - th.AssertNoErr(t, err) - th.CheckEquals(t, "01234567890", client.TokenID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/requests_test.go deleted file mode 100644 index 6550283df71..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/requests_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package extensions - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListExtensionsSuccessfully(t) - - count := 0 - - List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractExtensions(page) - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, ExpectedExtensions, actual) - - return true, nil - }) - - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetExtensionSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "agent").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, SingleExtension, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/urls_test.go deleted file mode 100644 index 3223b1ca8b0..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/common/extensions/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package extensions - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestExtensionURL(t *testing.T) { - actual := ExtensionURL(endpointClient(), "agent") - expected := endpoint + "extensions/agent" - th.AssertEquals(t, expected, actual) -} - -func TestListExtensionURL(t *testing.T) { - actual := ListExtensionURL(endpointClient()) - expected := endpoint + "extensions" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests_test.go deleted file mode 100644 index 8a7fa746753..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/requests_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package bootfromvolume - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCreateOpts(t *testing.T) { - base := servers.CreateOpts{ - Name: "createdserver", - ImageRef: "asdfasdfasdf", - FlavorRef: "performance1-1", - } - - ext := CreateOptsExt{ - CreateOptsBuilder: base, - BlockDevice: []BlockDevice{ - BlockDevice{ - UUID: "123456", - SourceType: Image, - DestinationType: "volume", - VolumeSize: 10, - }, - }, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "asdfasdfasdf", - "flavorRef": "performance1-1", - "flavorName": "", - "imageName": "", - "block_device_mapping_v2":[ - { - "uuid":"123456", - "source_type":"image", - "destination_type":"volume", - "boot_index": "0", - "delete_on_termination": "false", - "volume_size": "10" - } - ] - } - } - ` - actual, err := ext.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls_test.go deleted file mode 100644 index 6ee647732d4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume/urls_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package bootfromvolume - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestCreateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-volumes_boot", createURL(c)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/defsecrules/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/defsecrules/requests_test.go deleted file mode 100644 index d4ebe87c564..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/defsecrules/requests_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package defsecrules - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ruleID = "{ruleID}" - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListRulesResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractDefaultRules(page) - th.AssertNoErr(t, err) - - expected := []DefaultRule{ - DefaultRule{ - FromPort: 80, - ID: ruleID, - IPProtocol: "TCP", - IPRange: secgroups.IPRange{CIDR: "10.10.10.0/24"}, - ToPort: 80, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateRuleResponse(t) - - opts := CreateOpts{ - IPProtocol: "TCP", - FromPort: 80, - ToPort: 80, - CIDR: "10.10.12.0/24", - } - - group, err := Create(client.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := &DefaultRule{ - ID: ruleID, - FromPort: 80, - ToPort: 80, - IPProtocol: "TCP", - IPRange: secgroups.IPRange{CIDR: "10.10.12.0/24"}, - } - th.AssertDeepEquals(t, expected, group) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetRuleResponse(t, ruleID) - - group, err := Get(client.ServiceClient(), ruleID).Extract() - th.AssertNoErr(t, err) - - expected := &DefaultRule{ - ID: ruleID, - FromPort: 80, - ToPort: 80, - IPProtocol: "TCP", - IPRange: secgroups.IPRange{CIDR: "10.10.12.0/24"}, - } - - th.AssertDeepEquals(t, expected, group) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteRuleResponse(t, ruleID) - - err := Delete(client.ServiceClient(), ruleID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/delegate_test.go deleted file mode 100644 index c3c525fa20e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/delegate_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package extensions - -import ( - "fmt" - "net/http" - "testing" - - common "github.com/rackspace/gophercloud/openstack/common/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/extensions", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - - fmt.Fprintf(w, ` -{ - "extensions": [ - { - "updated": "2013-01-20T00:00:00-00:00", - "name": "Neutron Service Type Management", - "links": [], - "namespace": "http://docs.openstack.org/ext/neutron/service-type/api/v1.0", - "alias": "service-type", - "description": "API for retrieving service providers for Neutron advanced services" - } - ] -} - `) - }) - - count := 0 - List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractExtensions(page) - th.AssertNoErr(t, err) - - expected := []common.Extension{ - common.Extension{ - Updated: "2013-01-20T00:00:00-00:00", - Name: "Neutron Service Type Management", - Links: []interface{}{}, - Namespace: "http://docs.openstack.org/ext/neutron/service-type/api/v1.0", - Alias: "service-type", - Description: "API for retrieving service providers for Neutron advanced services", - }, - } - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/extensions/agent", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "extension": { - "updated": "2013-02-03T10:00:00-00:00", - "name": "agent", - "links": [], - "namespace": "http://docs.openstack.org/ext/agent/api/v2.0", - "alias": "agent", - "description": "The agent management extension." - } -} - `) - }) - - ext, err := Get(client.ServiceClient(), "agent").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, ext.Updated, "2013-02-03T10:00:00-00:00") - th.AssertEquals(t, ext.Name, "agent") - th.AssertEquals(t, ext.Namespace, "http://docs.openstack.org/ext/agent/api/v2.0") - th.AssertEquals(t, ext.Alias, "agent") - th.AssertEquals(t, ext.Description, "The agent management extension.") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/requests_test.go deleted file mode 100644 index 17418a3ce3a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/requests_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package diskconfig - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCreateOpts(t *testing.T) { - base := servers.CreateOpts{ - Name: "createdserver", - ImageRef: "asdfasdfasdf", - FlavorRef: "performance1-1", - } - - ext := CreateOptsExt{ - CreateOptsBuilder: base, - DiskConfig: Manual, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "asdfasdfasdf", - "flavorRef": "performance1-1", - "flavorName": "", - "imageName": "", - "OS-DCF:diskConfig": "MANUAL" - } - } - ` - actual, err := ext.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} - -func TestRebuildOpts(t *testing.T) { - base := servers.RebuildOpts{ - Name: "rebuiltserver", - AdminPass: "swordfish", - ImageID: "asdfasdfasdf", - } - - ext := RebuildOptsExt{ - RebuildOptsBuilder: base, - DiskConfig: Auto, - } - - actual, err := ext.ToServerRebuildMap() - th.AssertNoErr(t, err) - - expected := ` - { - "rebuild": { - "name": "rebuiltserver", - "imageRef": "asdfasdfasdf", - "adminPass": "swordfish", - "OS-DCF:diskConfig": "AUTO" - } - } - ` - th.CheckJSONEquals(t, expected, actual) -} - -func TestResizeOpts(t *testing.T) { - base := servers.ResizeOpts{ - FlavorRef: "performance1-8", - } - - ext := ResizeOptsExt{ - ResizeOptsBuilder: base, - DiskConfig: Auto, - } - - actual, err := ext.ToServerResizeMap() - th.AssertNoErr(t, err) - - expected := ` - { - "resize": { - "flavorRef": "performance1-8", - "OS-DCF:diskConfig": "AUTO" - } - } - ` - th.CheckJSONEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/results_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/results_test.go deleted file mode 100644 index dd8d2b7dfa7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig/results_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package diskconfig - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestExtractGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - servers.HandleServerGetSuccessfully(t) - - config, err := ExtractGet(servers.Get(client.ServiceClient(), "1234asdf")) - th.AssertNoErr(t, err) - th.CheckEquals(t, Manual, *config) -} - -func TestExtractUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - servers.HandleServerUpdateSuccessfully(t) - - r := servers.Update(client.ServiceClient(), "1234asdf", servers.UpdateOpts{ - Name: "new-name", - }) - config, err := ExtractUpdate(r) - th.AssertNoErr(t, err) - th.CheckEquals(t, Manual, *config) -} - -func TestExtractRebuild(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - servers.HandleRebuildSuccessfully(t, servers.SingleServerBody) - - r := servers.Rebuild(client.ServiceClient(), "1234asdf", servers.RebuildOpts{ - Name: "new-name", - AdminPass: "swordfish", - ImageID: "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - AccessIPv4: "1.2.3.4", - }) - config, err := ExtractRebuild(r) - th.AssertNoErr(t, err) - th.CheckEquals(t, Manual, *config) -} - -func TestExtractList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - servers.HandleServerListSuccessfully(t) - - pages := 0 - err := servers.List(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - pages++ - - config, err := ExtractDiskConfig(page, 0) - th.AssertNoErr(t, err) - th.CheckEquals(t, Manual, *config) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, pages, 1) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests_test.go deleted file mode 100644 index ed2460edc67..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/requests_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package floatingip - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractFloatingIPs(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedFloatingIPsSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateSuccessfully(t) - - actual, err := Create(client.ServiceClient(), CreateOpts{ - Pool: "nova", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &CreatedFloatingIP, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "2").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &SecondFloatingIP, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteSuccessfully(t) - - err := Delete(client.ServiceClient(), "1").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestAssociate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleAssociateSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - fip := "10.10.10.2" - - err := Associate(client.ServiceClient(), serverId, fip).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDisassociate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDisassociateSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - fip := "10.10.10.2" - - err := Disassociate(client.ServiceClient(), serverId, fip).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls_test.go deleted file mode 100644 index f73d6fb0f9f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip/urls_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package floatingip - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-floating-ips", listURL(c)) -} - -func TestCreateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-floating-ips", createURL(c)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-floating-ips/"+id, getURL(c, id)) -} - -func TestDeleteURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-floating-ips/"+id, deleteURL(c, id)) -} - -func TestAssociateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/action", associateURL(c, serverId)) -} - -func TestDisassociateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/action", disassociateURL(c, serverId)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests_test.go deleted file mode 100644 index 67d1833f572..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/requests_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package keypairs - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractKeyPairs(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedKeyPairSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateSuccessfully(t) - - actual, err := Create(client.ServiceClient(), CreateOpts{ - Name: "createdkey", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &CreatedKeyPair, actual) -} - -func TestImport(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleImportSuccessfully(t) - - actual, err := Create(client.ServiceClient(), CreateOpts{ - Name: "importedkey", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated by Nova", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &ImportedKeyPair, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "firstkey").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &FirstKeyPair, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteSuccessfully(t) - - err := Delete(client.ServiceClient(), "deletedkey").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls_test.go deleted file mode 100644 index 60efd2a5d33..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs/urls_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package keypairs - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-keypairs", listURL(c)) -} - -func TestCreateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-keypairs", createURL(c)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-keypairs/wat", getURL(c, "wat")) -} - -func TestDeleteURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-keypairs/wat", deleteURL(c, "wat")) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/requests_test.go deleted file mode 100644 index 722b3f0bd07..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/requests_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package networks - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNetworks(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedNetworkSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "20c8acc0-f747-4d71-a389-46d078ebf000").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &SecondNetwork, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/urls_test.go deleted file mode 100644 index be54c90a566..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/networks/urls_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package networks - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-networks", listURL(c)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-networks/"+id, getURL(c, id)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests_test.go deleted file mode 100644 index 9b38b35d9c4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/schedulerhints/requests_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package schedulerhints - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCreateOpts(t *testing.T) { - base := servers.CreateOpts{ - Name: "createdserver", - ImageRef: "asdfasdfasdf", - FlavorRef: "performance1-1", - } - - schedulerHints := SchedulerHints{ - Group: "101aed42-22d9-4a3e-9ba1-21103b0d1aba", - DifferentHost: []string{ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287", - }, - SameHost: []string{ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287", - }, - Query: []interface{}{">=", "$free_ram_mb", "1024"}, - TargetCell: "foobar", - BuildNearHostIP: "192.168.1.1/24", - } - - ext := CreateOptsExt{ - CreateOptsBuilder: base, - SchedulerHints: schedulerHints, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "asdfasdfasdf", - "flavorRef": "performance1-1", - "flavorName": "", - "imageName": "" - }, - "os:scheduler_hints": { - "group": "101aed42-22d9-4a3e-9ba1-21103b0d1aba", - "different_host": [ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287" - ], - "same_host": [ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287" - ], - "query": [ - ">=", "$free_ram_mb", "1024" - ], - "target_cell": "foobar", - "build_near_host_ip": "192.168.1.1", - "cidr": "/24" - } - } - ` - actual, err := ext.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} - -func TestCreateOptsWithComplexQuery(t *testing.T) { - base := servers.CreateOpts{ - Name: "createdserver", - ImageRef: "asdfasdfasdf", - FlavorRef: "performance1-1", - } - - schedulerHints := SchedulerHints{ - Group: "101aed42-22d9-4a3e-9ba1-21103b0d1aba", - DifferentHost: []string{ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287", - }, - SameHost: []string{ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287", - }, - Query: []interface{}{"and", []string{">=", "$free_ram_mb", "1024"}, []string{">=", "$free_disk_mb", "204800"}}, - TargetCell: "foobar", - BuildNearHostIP: "192.168.1.1/24", - } - - ext := CreateOptsExt{ - CreateOptsBuilder: base, - SchedulerHints: schedulerHints, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "asdfasdfasdf", - "flavorRef": "performance1-1", - "flavorName": "", - "imageName": "" - }, - "os:scheduler_hints": { - "group": "101aed42-22d9-4a3e-9ba1-21103b0d1aba", - "different_host": [ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287" - ], - "same_host": [ - "a0cf03a5-d921-4877-bb5c-86d26cf818e1", - "8c19174f-4220-44f0-824a-cd1eeef10287" - ], - "query": [ - "and", - [">=", "$free_ram_mb", "1024"], - [">=", "$free_disk_mb", "204800"] - ], - "target_cell": "foobar", - "build_near_host_ip": "192.168.1.1", - "cidr": "/24" - } - } - ` - actual, err := ext.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests_test.go deleted file mode 100644 index 4e21d5deaa1..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups/requests_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package secgroups - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - serverID = "{serverID}" - groupID = "{groupID}" - ruleID = "{ruleID}" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListGroupsResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractSecurityGroups(page) - if err != nil { - t.Errorf("Failed to extract users: %v", err) - return false, err - } - - expected := []SecurityGroup{ - SecurityGroup{ - ID: groupID, - Description: "default", - Name: "default", - Rules: []Rule{}, - TenantID: "openstack", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestListByServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListGroupsByServerResponse(t, serverID) - - count := 0 - - err := ListByServer(client.ServiceClient(), serverID).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractSecurityGroups(page) - if err != nil { - t.Errorf("Failed to extract users: %v", err) - return false, err - } - - expected := []SecurityGroup{ - SecurityGroup{ - ID: groupID, - Description: "default", - Name: "default", - Rules: []Rule{}, - TenantID: "openstack", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateGroupResponse(t) - - opts := CreateOpts{ - Name: "test", - Description: "something", - } - - group, err := Create(client.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := &SecurityGroup{ - ID: groupID, - Name: "test", - Description: "something", - TenantID: "openstack", - Rules: []Rule{}, - } - th.AssertDeepEquals(t, expected, group) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateGroupResponse(t, groupID) - - opts := UpdateOpts{ - Name: "new_name", - Description: "new_desc", - } - - group, err := Update(client.ServiceClient(), groupID, opts).Extract() - th.AssertNoErr(t, err) - - expected := &SecurityGroup{ - ID: groupID, - Name: "new_name", - Description: "something", - TenantID: "openstack", - Rules: []Rule{}, - } - th.AssertDeepEquals(t, expected, group) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetGroupsResponse(t, groupID) - - group, err := Get(client.ServiceClient(), groupID).Extract() - th.AssertNoErr(t, err) - - expected := &SecurityGroup{ - ID: groupID, - Description: "default", - Name: "default", - TenantID: "openstack", - Rules: []Rule{ - Rule{ - FromPort: 80, - ToPort: 85, - IPProtocol: "TCP", - IPRange: IPRange{CIDR: "0.0.0.0"}, - Group: Group{TenantID: "openstack", Name: "default"}, - ParentGroupID: groupID, - ID: ruleID, - }, - }, - } - - th.AssertDeepEquals(t, expected, group) -} - -func TestGetNumericID(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - numericGroupID := 12345 - - mockGetNumericIDGroupResponse(t, numericGroupID) - - group, err := Get(client.ServiceClient(), "12345").Extract() - th.AssertNoErr(t, err) - - expected := &SecurityGroup{ID: "12345"} - th.AssertDeepEquals(t, expected, group) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteGroupResponse(t, groupID) - - err := Delete(client.ServiceClient(), groupID).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestAddRule(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockAddRuleResponse(t) - - opts := CreateRuleOpts{ - ParentGroupID: groupID, - FromPort: 22, - ToPort: 22, - IPProtocol: "TCP", - CIDR: "0.0.0.0/0", - } - - rule, err := CreateRule(client.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := &Rule{ - FromPort: 22, - ToPort: 22, - Group: Group{}, - IPProtocol: "TCP", - ParentGroupID: groupID, - IPRange: IPRange{CIDR: "0.0.0.0/0"}, - ID: ruleID, - } - - th.AssertDeepEquals(t, expected, rule) -} - -func TestDeleteRule(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteRuleResponse(t, ruleID) - - err := DeleteRule(client.ServiceClient(), ruleID).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestAddServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockAddServerToGroupResponse(t, serverID) - - err := AddServerToGroup(client.ServiceClient(), serverID, "test").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestRemoveServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockRemoveServerFromGroupResponse(t, serverID) - - err := RemoveServerFromGroup(client.ServiceClient(), serverID, "test").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests_test.go deleted file mode 100644 index 07fec51b1b8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/requests_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package servergroups - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractServerGroups(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedServerGroupSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateSuccessfully(t) - - actual, err := Create(client.ServiceClient(), CreateOpts{ - Name: "test", - Policies: []string{"anti-affinity"}, - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &CreatedServerGroup, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "4d8c3732-a248-40ed-bebc-539a6ffd25c0").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &FirstServerGroup, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteSuccessfully(t) - - err := Delete(client.ServiceClient(), "616fb98f-46ca-475e-917e-2563e5a8cd19").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls_test.go deleted file mode 100644 index bff4dfc7205..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/servergroups/urls_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package servergroups - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-server-groups", listURL(c)) -} - -func TestCreateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-server-groups", createURL(c)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-server-groups/"+id, getURL(c, id)) -} - -func TestDeleteURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-server-groups/"+id, deleteURL(c, id)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests_test.go deleted file mode 100644 index 97a121b19aa..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/startstop/requests_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package startstop - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const serverID = "{serverId}" - -func TestStart(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockStartServerResponse(t, serverID) - - err := Start(client.ServiceClient(), serverID).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestStop(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockStopServerResponse(t, serverID) - - err := Stop(client.ServiceClient(), serverID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests_test.go deleted file mode 100644 index fc4ee4f4bab..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/requests_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package tenantnetworks - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNetworks(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedNetworkSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "20c8acc0-f747-4d71-a389-46d078ebf000").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &SecondNetwork, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls_test.go deleted file mode 100644 index 39c464e9fbb..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks/urls_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package tenantnetworks - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - - th.CheckEquals(t, c.Endpoint+"os-tenant-networks", listURL(c)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - id := "1" - - th.CheckEquals(t, c.Endpoint+"os-tenant-networks/"+id, getURL(c, id)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests_test.go deleted file mode 100644 index b0a765befa9..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/requests_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package volumeattach - -import ( - "testing" - - fixtures "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/testing" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// FirstVolumeAttachment is the first result in ListOutput. -var FirstVolumeAttachment = VolumeAttachment{ - Device: "/dev/vdd", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f803", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f803", -} - -// SecondVolumeAttachment is the first result in ListOutput. -var SecondVolumeAttachment = VolumeAttachment{ - Device: "/dev/vdc", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", -} - -// ExpectedVolumeAttachmentSlide is the slice of results that should be parsed -// from ListOutput, in the expected order. -var ExpectedVolumeAttachmentSlice = []VolumeAttachment{FirstVolumeAttachment, SecondVolumeAttachment} - -//CreatedVolumeAttachment is the parsed result from CreatedOutput. -var CreatedVolumeAttachment = VolumeAttachment{ - Device: "/dev/vdc", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleListSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - count := 0 - err := List(client.ServiceClient(), serverId).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVolumeAttachments(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedVolumeAttachmentSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleCreateSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - actual, err := Create(client.ServiceClient(), serverId, CreateOpts{ - Device: "/dev/vdc", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &CreatedVolumeAttachment, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleGetSuccessfully(t) - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - actual, err := Get(client.ServiceClient(), serverId, aId).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &SecondVolumeAttachment, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleDeleteSuccessfully(t) - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - err := Delete(client.ServiceClient(), serverId, aId).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls_test.go deleted file mode 100644 index 8ee0e42d456..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/urls_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package volumeattach - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/os-volume_attachments", listURL(c, serverId)) -} - -func TestCreateURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/os-volume_attachments", createURL(c, serverId)) -} - -func TestGetURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/os-volume_attachments/"+aId, getURL(c, serverId, aId)) -} - -func TestDeleteURL(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - c := client.ServiceClient() - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - - th.CheckEquals(t, c.Endpoint+"servers/"+serverId+"/os-volume_attachments/"+aId, deleteURL(c, serverId, aId)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests_test.go deleted file mode 100644 index fbd7c331402..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/requests_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package flavors - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -const tokenID = "blerb" - -func TestListFlavors(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/flavors/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ` - { - "flavors": [ - { - "id": "1", - "name": "m1.tiny", - "disk": 1, - "ram": 512, - "vcpus": 1 - }, - { - "id": "2", - "name": "m2.small", - "disk": 10, - "ram": 1024, - "vcpus": 2 - } - ], - "flavors_links": [ - { - "href": "%s/flavors/detail?marker=2", - "rel": "next" - } - ] - } - `, th.Server.URL) - case "2": - fmt.Fprintf(w, `{ "flavors": [] }`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) - - pages := 0 - err := ListDetail(fake.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractFlavors(page) - if err != nil { - return false, err - } - - expected := []Flavor{ - Flavor{ID: "1", Name: "m1.tiny", Disk: 1, RAM: 512, VCPUs: 1}, - Flavor{ID: "2", Name: "m2.small", Disk: 10, RAM: 1024, VCPUs: 2}, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, but was %#v", expected, actual) - } - - return true, nil - }) - if err != nil { - t.Fatal(err) - } - if pages != 1 { - t.Errorf("Expected one page, got %d", pages) - } -} - -func TestGetFlavor(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/flavors/12345", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "flavor": { - "id": "1", - "name": "m1.tiny", - "disk": 1, - "ram": 512, - "vcpus": 1, - "rxtx_factor": 1 - } - } - `) - }) - - actual, err := Get(fake.ServiceClient(), "12345").Extract() - if err != nil { - t.Fatalf("Unable to get flavor: %v", err) - } - - expected := &Flavor{ - ID: "1", - Name: "m1.tiny", - Disk: 1, - RAM: 512, - VCPUs: 1, - RxTxFactor: 1, - } - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, but was %#v", expected, actual) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls_test.go deleted file mode 100644 index 069da2496e0..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/flavors/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package flavors - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "flavors/foo" - th.CheckEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "flavors/detail" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests_test.go deleted file mode 100644 index 93a97bdc65b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/requests_test.go +++ /dev/null @@ -1,191 +0,0 @@ -package images - -import ( - "encoding/json" - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListImages(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/images/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ` - { - "images": [ - { - "status": "ACTIVE", - "updated": "2014-09-23T12:54:56Z", - "id": "f3e4a95d-1f4f-4989-97ce-f3a1fb8c04d7", - "OS-EXT-IMG-SIZE:size": 476704768, - "name": "F17-x86_64-cfntools", - "created": "2014-09-23T12:54:52Z", - "minDisk": 0, - "progress": 100, - "minRam": 0, - "metadata": {} - }, - { - "status": "ACTIVE", - "updated": "2014-09-23T12:51:43Z", - "id": "f90f6034-2570-4974-8351-6b49732ef2eb", - "OS-EXT-IMG-SIZE:size": 13167616, - "name": "cirros-0.3.2-x86_64-disk", - "created": "2014-09-23T12:51:42Z", - "minDisk": 0, - "progress": 100, - "minRam": 0, - "metadata": {} - } - ] - } - `) - case "2": - fmt.Fprintf(w, `{ "images": [] }`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) - - pages := 0 - options := &ListOpts{Limit: 2} - err := ListDetail(fake.ServiceClient(), options).EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractImages(page) - if err != nil { - return false, err - } - - expected := []Image{ - Image{ - ID: "f3e4a95d-1f4f-4989-97ce-f3a1fb8c04d7", - Name: "F17-x86_64-cfntools", - Created: "2014-09-23T12:54:52Z", - Updated: "2014-09-23T12:54:56Z", - MinDisk: 0, - MinRAM: 0, - Progress: 100, - Status: "ACTIVE", - }, - Image{ - ID: "f90f6034-2570-4974-8351-6b49732ef2eb", - Name: "cirros-0.3.2-x86_64-disk", - Created: "2014-09-23T12:51:42Z", - Updated: "2014-09-23T12:51:43Z", - MinDisk: 0, - MinRAM: 0, - Progress: 100, - Status: "ACTIVE", - }, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Unexpected page contents: expected %#v, got %#v", expected, actual) - } - - return false, nil - }) - - if err != nil { - t.Fatalf("EachPage error: %v", err) - } - if pages != 1 { - t.Errorf("Expected one page, got %d", pages) - } -} - -func TestGetImage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/images/12345678", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "image": { - "status": "ACTIVE", - "updated": "2014-09-23T12:54:56Z", - "id": "f3e4a95d-1f4f-4989-97ce-f3a1fb8c04d7", - "OS-EXT-IMG-SIZE:size": 476704768, - "name": "F17-x86_64-cfntools", - "created": "2014-09-23T12:54:52Z", - "minDisk": 0, - "progress": 100, - "minRam": 0, - "metadata": {} - } - } - `) - }) - - actual, err := Get(fake.ServiceClient(), "12345678").Extract() - if err != nil { - t.Fatalf("Unexpected error from Get: %v", err) - } - - expected := &Image{ - Status: "ACTIVE", - Updated: "2014-09-23T12:54:56Z", - ID: "f3e4a95d-1f4f-4989-97ce-f3a1fb8c04d7", - Name: "F17-x86_64-cfntools", - Created: "2014-09-23T12:54:52Z", - MinDisk: 0, - Progress: 100, - MinRAM: 0, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, but got %#v", expected, actual) - } -} - -func TestNextPageURL(t *testing.T) { - var page ImagePage - var body map[string]interface{} - bodyString := []byte(`{"images":{"links":[{"href":"http://192.154.23.87/12345/images/image3","rel":"bookmark"}]}, "images_links":[{"href":"http://192.154.23.87/12345/images/image4","rel":"next"}]}`) - err := json.Unmarshal(bodyString, &body) - if err != nil { - t.Fatalf("Error unmarshaling data into page body: %v", err) - } - page.Body = body - - expected := "http://192.154.23.87/12345/images/image4" - actual, err := page.NextPageURL() - th.AssertNoErr(t, err) - th.CheckEquals(t, expected, actual) -} - -// Test Image delete -func TestDeleteImage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/images/12345678", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "12345678") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls_test.go deleted file mode 100644 index b1ab3d6790c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/images/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package images - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "images/foo" - th.CheckEquals(t, expected, actual) -} - -func TestListDetailURL(t *testing.T) { - actual := listDetailURL(endpointClient()) - expected := endpoint + "images/detail" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests_test.go deleted file mode 100644 index 88cb54dd7bd..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/requests_test.go +++ /dev/null @@ -1,373 +0,0 @@ -package servers - -import ( - "encoding/base64" - "encoding/json" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListServers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerListSuccessfully(t) - - pages := 0 - err := List(client.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractServers(page) - if err != nil { - return false, err - } - - if len(actual) != 2 { - t.Fatalf("Expected 2 servers, got %d", len(actual)) - } - th.CheckDeepEquals(t, ServerHerp, actual[0]) - th.CheckDeepEquals(t, ServerDerp, actual[1]) - - return true, nil - }) - - th.AssertNoErr(t, err) - - if pages != 1 { - t.Errorf("Expected 1 page, saw %d", pages) - } -} - -func TestListAllServers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerListSuccessfully(t) - - allPages, err := List(client.ServiceClient(), ListOpts{}).AllPages() - th.AssertNoErr(t, err) - actual, err := ExtractServers(allPages) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ServerHerp, actual[0]) - th.CheckDeepEquals(t, ServerDerp, actual[1]) -} - -func TestCreateServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerCreationSuccessfully(t, SingleServerBody) - - actual, err := Create(client.ServiceClient(), CreateOpts{ - Name: "derp", - ImageRef: "f90f6034-2570-4974-8351-6b49732ef2eb", - FlavorRef: "1", - }).Extract() - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ServerDerp, *actual) -} - -func TestDeleteServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerDeletionSuccessfully(t) - - res := Delete(client.ServiceClient(), "asdfasdfasdf") - th.AssertNoErr(t, res.Err) -} - -func TestGetServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerGetSuccessfully(t) - - client := client.ServiceClient() - actual, err := Get(client, "1234asdf").Extract() - if err != nil { - t.Fatalf("Unexpected Get error: %v", err) - } - - th.CheckDeepEquals(t, ServerDerp, *actual) -} - -func TestUpdateServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleServerUpdateSuccessfully(t) - - client := client.ServiceClient() - actual, err := Update(client, "1234asdf", UpdateOpts{Name: "new-name"}).Extract() - if err != nil { - t.Fatalf("Unexpected Update error: %v", err) - } - - th.CheckDeepEquals(t, ServerDerp, *actual) -} - -func TestChangeServerAdminPassword(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleAdminPasswordChangeSuccessfully(t) - - res := ChangeAdminPassword(client.ServiceClient(), "1234asdf", "new-password") - th.AssertNoErr(t, res.Err) -} - -func TestRebootServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleRebootSuccessfully(t) - - res := Reboot(client.ServiceClient(), "1234asdf", SoftReboot) - th.AssertNoErr(t, res.Err) -} - -func TestRebuildServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleRebuildSuccessfully(t, SingleServerBody) - - opts := RebuildOpts{ - Name: "new-name", - AdminPass: "swordfish", - ImageID: "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - AccessIPv4: "1.2.3.4", - } - - actual, err := Rebuild(client.ServiceClient(), "1234asdf", opts).Extract() - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ServerDerp, *actual) -} - -func TestResizeServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "resize": { "flavorRef": "2" } }`) - - w.WriteHeader(http.StatusAccepted) - }) - - res := Resize(client.ServiceClient(), "1234asdf", ResizeOpts{FlavorRef: "2"}) - th.AssertNoErr(t, res.Err) -} - -func TestConfirmResize(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "confirmResize": null }`) - - w.WriteHeader(http.StatusNoContent) - }) - - res := ConfirmResize(client.ServiceClient(), "1234asdf") - th.AssertNoErr(t, res.Err) -} - -func TestRevertResize(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/1234asdf/action", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "revertResize": null }`) - - w.WriteHeader(http.StatusAccepted) - }) - - res := RevertResize(client.ServiceClient(), "1234asdf") - th.AssertNoErr(t, res.Err) -} - -func TestRescue(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleServerRescueSuccessfully(t) - - res := Rescue(client.ServiceClient(), "1234asdf", RescueOpts{ - AdminPass: "1234567890", - }) - th.AssertNoErr(t, res.Err) - adminPass, _ := res.Extract() - th.AssertEquals(t, "1234567890", adminPass) -} - -func TestGetMetadatum(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadatumGetSuccessfully(t) - - expected := map[string]string{"foo": "bar"} - actual, err := Metadatum(client.ServiceClient(), "1234asdf", "foo").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestCreateMetadatum(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadatumCreateSuccessfully(t) - - expected := map[string]string{"foo": "bar"} - actual, err := CreateMetadatum(client.ServiceClient(), "1234asdf", MetadatumOpts{"foo": "bar"}).Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestDeleteMetadatum(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadatumDeleteSuccessfully(t) - - err := DeleteMetadatum(client.ServiceClient(), "1234asdf", "foo").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGetMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadataGetSuccessfully(t) - - expected := map[string]string{"foo": "bar", "this": "that"} - actual, err := Metadata(client.ServiceClient(), "1234asdf").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestResetMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadataResetSuccessfully(t) - - expected := map[string]string{"foo": "bar", "this": "that"} - actual, err := ResetMetadata(client.ServiceClient(), "1234asdf", MetadataOpts{ - "foo": "bar", - "this": "that", - }).Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestUpdateMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - HandleMetadataUpdateSuccessfully(t) - - expected := map[string]string{"foo": "baz", "this": "those"} - actual, err := UpdateMetadata(client.ServiceClient(), "1234asdf", MetadataOpts{ - "foo": "baz", - "this": "those", - }).Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestListAddresses(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleAddressListSuccessfully(t) - - expected := ListAddressesExpected - pages := 0 - err := ListAddresses(client.ServiceClient(), "asdfasdfasdf").EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractAddresses(page) - th.AssertNoErr(t, err) - - if len(actual) != 2 { - t.Fatalf("Expected 2 networks, got %d", len(actual)) - } - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, pages) -} - -func TestListAddressesByNetwork(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleNetworkAddressListSuccessfully(t) - - expected := ListNetworkAddressesExpected - pages := 0 - err := ListAddressesByNetwork(client.ServiceClient(), "asdfasdfasdf", "public").EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractNetworkAddresses(page) - th.AssertNoErr(t, err) - - if len(actual) != 2 { - t.Fatalf("Expected 2 addresses, got %d", len(actual)) - } - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, pages) -} - -func TestCreateServerImage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateServerImageSuccessfully(t) - - _, err := CreateImage(client.ServiceClient(), "serverimage", CreateImageOpts{Name: "test"}).ExtractImageID() - th.AssertNoErr(t, err) -} - -func TestMarshalPersonality(t *testing.T) { - name := "/etc/test" - contents := []byte("asdfasdf") - - personality := Personality{ - &File{ - Path: name, - Contents: contents, - }, - } - - data, err := json.Marshal(personality) - if err != nil { - t.Fatal(err) - } - - var actual []map[string]string - err = json.Unmarshal(data, &actual) - if err != nil { - t.Fatal(err) - } - - if len(actual) != 1 { - t.Fatal("expected personality length 1") - } - - if actual[0]["path"] != name { - t.Fatal("file path incorrect") - } - - if actual[0]["contents"] != base64.StdEncoding.EncodeToString(contents) { - t.Fatal("file contents incorrect") - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls_test.go deleted file mode 100644 index 17a1d287f25..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/compute/v2/servers/urls_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package servers - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "servers" - th.CheckEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "servers" - th.CheckEquals(t, expected, actual) -} - -func TestListDetailURL(t *testing.T) { - actual := listDetailURL(endpointClient()) - expected := endpoint + "servers/detail" - th.CheckEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "servers/foo" - th.CheckEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "servers/foo" - th.CheckEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "servers/foo" - th.CheckEquals(t, expected, actual) -} - -func TestActionURL(t *testing.T) { - actual := actionURL(endpointClient(), "foo") - expected := endpoint + "servers/foo/action" - th.CheckEquals(t, expected, actual) -} - -func TestMetadatumURL(t *testing.T) { - actual := metadatumURL(endpointClient(), "foo", "bar") - expected := endpoint + "servers/foo/metadata/bar" - th.CheckEquals(t, expected, actual) -} - -func TestMetadataURL(t *testing.T) { - actual := metadataURL(endpointClient(), "foo") - expected := endpoint + "servers/foo/metadata" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/endpoint_location_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/endpoint_location_test.go deleted file mode 100644 index 8e65918abfe..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/endpoint_location_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package openstack - -import ( - "strings" - "testing" - - "github.com/rackspace/gophercloud" - tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens" - tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens" - th "github.com/rackspace/gophercloud/testhelper" -) - -// Service catalog fixtures take too much vertical space! -var catalog2 = tokens2.ServiceCatalog{ - Entries: []tokens2.CatalogEntry{ - tokens2.CatalogEntry{ - Type: "same", - Name: "same", - Endpoints: []tokens2.Endpoint{ - tokens2.Endpoint{ - Region: "same", - PublicURL: "https://public.correct.com/", - InternalURL: "https://internal.correct.com/", - AdminURL: "https://admin.correct.com/", - }, - tokens2.Endpoint{ - Region: "different", - PublicURL: "https://badregion.com/", - }, - }, - }, - tokens2.CatalogEntry{ - Type: "same", - Name: "different", - Endpoints: []tokens2.Endpoint{ - tokens2.Endpoint{ - Region: "same", - PublicURL: "https://badname.com/", - }, - tokens2.Endpoint{ - Region: "different", - PublicURL: "https://badname.com/+badregion", - }, - }, - }, - tokens2.CatalogEntry{ - Type: "different", - Name: "different", - Endpoints: []tokens2.Endpoint{ - tokens2.Endpoint{ - Region: "same", - PublicURL: "https://badtype.com/+badname", - }, - tokens2.Endpoint{ - Region: "different", - PublicURL: "https://badtype.com/+badregion+badname", - }, - }, - }, - }, -} - -func TestV2EndpointExact(t *testing.T) { - expectedURLs := map[gophercloud.Availability]string{ - gophercloud.AvailabilityPublic: "https://public.correct.com/", - gophercloud.AvailabilityAdmin: "https://admin.correct.com/", - gophercloud.AvailabilityInternal: "https://internal.correct.com/", - } - - for availability, expected := range expectedURLs { - actual, err := V2EndpointURL(&catalog2, gophercloud.EndpointOpts{ - Type: "same", - Name: "same", - Region: "same", - Availability: availability, - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, expected, actual) - } -} - -func TestV2EndpointNone(t *testing.T) { - _, err := V2EndpointURL(&catalog2, gophercloud.EndpointOpts{ - Type: "nope", - Availability: gophercloud.AvailabilityPublic, - }) - th.CheckEquals(t, gophercloud.ErrEndpointNotFound, err) -} - -func TestV2EndpointMultiple(t *testing.T) { - _, err := V2EndpointURL(&catalog2, gophercloud.EndpointOpts{ - Type: "same", - Region: "same", - Availability: gophercloud.AvailabilityPublic, - }) - if !strings.HasPrefix(err.Error(), "Discovered 2 matching endpoints:") { - t.Errorf("Received unexpected error: %v", err) - } -} - -func TestV2EndpointBadAvailability(t *testing.T) { - _, err := V2EndpointURL(&catalog2, gophercloud.EndpointOpts{ - Type: "same", - Name: "same", - Region: "same", - Availability: "wat", - }) - th.CheckEquals(t, "Unexpected availability in endpoint query: wat", err.Error()) -} - -var catalog3 = tokens3.ServiceCatalog{ - Entries: []tokens3.CatalogEntry{ - tokens3.CatalogEntry{ - Type: "same", - Name: "same", - Endpoints: []tokens3.Endpoint{ - tokens3.Endpoint{ - ID: "1", - Region: "same", - Interface: "public", - URL: "https://public.correct.com/", - }, - tokens3.Endpoint{ - ID: "2", - Region: "same", - Interface: "admin", - URL: "https://admin.correct.com/", - }, - tokens3.Endpoint{ - ID: "3", - Region: "same", - Interface: "internal", - URL: "https://internal.correct.com/", - }, - tokens3.Endpoint{ - ID: "4", - Region: "different", - Interface: "public", - URL: "https://badregion.com/", - }, - }, - }, - tokens3.CatalogEntry{ - Type: "same", - Name: "different", - Endpoints: []tokens3.Endpoint{ - tokens3.Endpoint{ - ID: "5", - Region: "same", - Interface: "public", - URL: "https://badname.com/", - }, - tokens3.Endpoint{ - ID: "6", - Region: "different", - Interface: "public", - URL: "https://badname.com/+badregion", - }, - }, - }, - tokens3.CatalogEntry{ - Type: "different", - Name: "different", - Endpoints: []tokens3.Endpoint{ - tokens3.Endpoint{ - ID: "7", - Region: "same", - Interface: "public", - URL: "https://badtype.com/+badname", - }, - tokens3.Endpoint{ - ID: "8", - Region: "different", - Interface: "public", - URL: "https://badtype.com/+badregion+badname", - }, - }, - }, - }, -} - -func TestV3EndpointExact(t *testing.T) { - expectedURLs := map[gophercloud.Availability]string{ - gophercloud.AvailabilityPublic: "https://public.correct.com/", - gophercloud.AvailabilityAdmin: "https://admin.correct.com/", - gophercloud.AvailabilityInternal: "https://internal.correct.com/", - } - - for availability, expected := range expectedURLs { - actual, err := V3EndpointURL(&catalog3, gophercloud.EndpointOpts{ - Type: "same", - Name: "same", - Region: "same", - Availability: availability, - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, expected, actual) - } -} - -func TestV3EndpointNone(t *testing.T) { - _, err := V3EndpointURL(&catalog3, gophercloud.EndpointOpts{ - Type: "nope", - Availability: gophercloud.AvailabilityPublic, - }) - th.CheckEquals(t, gophercloud.ErrEndpointNotFound, err) -} - -func TestV3EndpointMultiple(t *testing.T) { - _, err := V3EndpointURL(&catalog3, gophercloud.EndpointOpts{ - Type: "same", - Region: "same", - Availability: gophercloud.AvailabilityPublic, - }) - if !strings.HasPrefix(err.Error(), "Discovered 2 matching endpoints:") { - t.Errorf("Received unexpected error: %v", err) - } -} - -func TestV3EndpointBadAvailability(t *testing.T) { - _, err := V3EndpointURL(&catalog3, gophercloud.EndpointOpts{ - Type: "same", - Name: "same", - Region: "same", - Availability: "wat", - }) - th.CheckEquals(t, "Unexpected availability in endpoint query: wat", err.Error()) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles/requests_test.go deleted file mode 100644 index 7bfeea44a81..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles/requests_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package roles - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockListRoleResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractRoles(page) - if err != nil { - t.Errorf("Failed to extract users: %v", err) - return false, err - } - - expected := []Role{ - Role{ - ID: "123", - Name: "compute:admin", - Description: "Nova Administrator", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestAddUserRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockAddUserRoleResponse(t) - - err := AddUserRole(client.ServiceClient(), "{tenant_id}", "{user_id}", "{role_id}").ExtractErr() - - th.AssertNoErr(t, err) -} - -func TestDeleteUserRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockDeleteUserRoleResponse(t) - - err := DeleteUserRole(client.ServiceClient(), "{tenant_id}", "{user_id}", "{role_id}").ExtractErr() - - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/delegate_test.go deleted file mode 100644 index 504118a825b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/extensions/delegate_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package extensions - -import ( - "testing" - - common "github.com/rackspace/gophercloud/openstack/common/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListExtensionsSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractExtensions(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, common.ExpectedExtensions, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - common.HandleGetExtensionSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "agent").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, common.SingleExtension, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests_test.go deleted file mode 100644 index e8f172dd183..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tenants/requests_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package tenants - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListTenants(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListTenantsSuccessfully(t) - - count := 0 - err := List(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - - actual, err := ExtractTenants(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ExpectedTenantSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests_test.go deleted file mode 100644 index 8b78c855048..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/tokens/requests_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package tokens - -import ( - "fmt" - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func tokenPost(t *testing.T, options gophercloud.AuthOptions, requestJSON string) CreateResult { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleTokenPost(t, requestJSON) - - return Create(client.ServiceClient(), AuthOptions{options}) -} - -func tokenPostErr(t *testing.T, options gophercloud.AuthOptions, expectedErr error) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleTokenPost(t, "") - - actualErr := Create(client.ServiceClient(), AuthOptions{options}).Err - th.CheckDeepEquals(t, expectedErr, actualErr) -} - -func TestCreateWithPassword(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "swordfish", - } - - IsSuccessful(t, tokenPost(t, options, ` - { - "auth": { - "passwordCredentials": { - "username": "me", - "password": "swordfish" - } - } - } - `)) -} - -func TestCreateTokenWithTenantID(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "opensesame", - TenantID: "fc394f2ab2df4114bde39905f800dc57", - } - - IsSuccessful(t, tokenPost(t, options, ` - { - "auth": { - "tenantId": "fc394f2ab2df4114bde39905f800dc57", - "passwordCredentials": { - "username": "me", - "password": "opensesame" - } - } - } - `)) -} - -func TestCreateTokenWithTenantName(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "opensesame", - TenantName: "demo", - } - - IsSuccessful(t, tokenPost(t, options, ` - { - "auth": { - "tenantName": "demo", - "passwordCredentials": { - "username": "me", - "password": "opensesame" - } - } - } - `)) -} - -func TestProhibitUserID(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - UserID: "1234", - Password: "thing", - } - - tokenPostErr(t, options, ErrUserIDProvided) -} - -func TestProhibitAPIKey(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "thing", - APIKey: "123412341234", - } - - tokenPostErr(t, options, ErrAPIKeyProvided) -} - -func TestProhibitDomainID(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "thing", - DomainID: "1234", - } - - tokenPostErr(t, options, ErrDomainIDProvided) -} - -func TestProhibitDomainName(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - Password: "thing", - DomainName: "wat", - } - - tokenPostErr(t, options, ErrDomainNameProvided) -} - -func TestRequireUsername(t *testing.T) { - options := gophercloud.AuthOptions{ - Password: "thing", - } - - tokenPostErr(t, options, fmt.Errorf("You must provide either username/password or tenantID/token values.")) -} - -func TestRequirePassword(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - } - - tokenPostErr(t, options, ErrPasswordRequired) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/users/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/users/requests_test.go deleted file mode 100644 index 04f837163ab..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v2/users/requests_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package users - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockListUserResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractUsers(page) - if err != nil { - t.Errorf("Failed to extract users: %v", err) - return false, err - } - - expected := []User{ - User{ - ID: "u1000", - Name: "John Smith", - Username: "jqsmith", - Email: "john.smith@example.org", - Enabled: true, - TenantID: "12345", - }, - User{ - ID: "u1001", - Name: "Jane Smith", - Username: "jqsmith", - Email: "jane.smith@example.org", - Enabled: true, - TenantID: "12345", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreateUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateUserResponse(t) - - opts := CreateOpts{ - Name: "new_user", - TenantID: "12345", - Enabled: Disabled, - Email: "new_user@foo.com", - } - - user, err := Create(client.ServiceClient(), opts).Extract() - - th.AssertNoErr(t, err) - - expected := &User{ - Name: "new_user", - ID: "c39e3de9be2d4c779f1dfd6abacc176d", - Email: "new_user@foo.com", - Enabled: false, - TenantID: "12345", - } - - th.AssertDeepEquals(t, expected, user) -} - -func TestGetUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetUserResponse(t) - - user, err := Get(client.ServiceClient(), "new_user").Extract() - th.AssertNoErr(t, err) - - expected := &User{ - Name: "new_user", - ID: "c39e3de9be2d4c779f1dfd6abacc176d", - Email: "new_user@foo.com", - Enabled: false, - TenantID: "12345", - } - - th.AssertDeepEquals(t, expected, user) -} - -func TestUpdateUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateUserResponse(t) - - id := "c39e3de9be2d4c779f1dfd6abacc176d" - opts := UpdateOpts{ - Name: "new_name", - Enabled: Enabled, - Email: "new_email@foo.com", - } - - user, err := Update(client.ServiceClient(), id, opts).Extract() - - th.AssertNoErr(t, err) - - expected := &User{ - Name: "new_name", - ID: id, - Email: "new_email@foo.com", - Enabled: true, - TenantID: "12345", - } - - th.AssertDeepEquals(t, expected, user) -} - -func TestDeleteUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteUserResponse(t) - - res := Delete(client.ServiceClient(), "c39e3de9be2d4c779f1dfd6abacc176d") - th.AssertNoErr(t, res.Err) -} - -func TestListingUserRoles(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListRolesResponse(t) - - tenantID := "1d8b6120dcc640fda4fc9194ffc80273" - userID := "c39e3de9be2d4c779f1dfd6abacc176d" - - err := ListRoles(client.ServiceClient(), tenantID, userID).EachPage(func(page pagination.Page) (bool, error) { - actual, err := ExtractRoles(page) - th.AssertNoErr(t, err) - - expected := []Role{ - Role{ID: "9fe2ff9ee4384b1894a90878d3e92bab", Name: "foo_role"}, - Role{ID: "1ea3d56793574b668e85960fbf651e13", Name: "admin"}, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/requests_test.go deleted file mode 100644 index 80687c4cb70..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/requests_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package endpoints - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestCreateSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/endpoints", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "POST") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - testhelper.TestJSONRequest(t, r, ` - { - "endpoint": { - "interface": "public", - "name": "the-endiest-of-points", - "region": "underground", - "url": "https://1.2.3.4:9000/", - "service_id": "asdfasdfasdfasdf" - } - } - `) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, ` - { - "endpoint": { - "id": "12", - "interface": "public", - "links": { - "self": "https://localhost:5000/v3/endpoints/12" - }, - "name": "the-endiest-of-points", - "region": "underground", - "service_id": "asdfasdfasdfasdf", - "url": "https://1.2.3.4:9000/" - } - } - `) - }) - - actual, err := Create(client.ServiceClient(), EndpointOpts{ - Availability: gophercloud.AvailabilityPublic, - Name: "the-endiest-of-points", - Region: "underground", - URL: "https://1.2.3.4:9000/", - ServiceID: "asdfasdfasdfasdf", - }).Extract() - if err != nil { - t.Fatalf("Unable to create an endpoint: %v", err) - } - - expected := &Endpoint{ - ID: "12", - Availability: gophercloud.AvailabilityPublic, - Name: "the-endiest-of-points", - Region: "underground", - ServiceID: "asdfasdfasdfasdf", - URL: "https://1.2.3.4:9000/", - } - - if !reflect.DeepEqual(actual, expected) { - t.Errorf("Expected %#v, was %#v", expected, actual) - } -} - -func TestListEndpoints(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/endpoints", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "GET") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "endpoints": [ - { - "id": "12", - "interface": "public", - "links": { - "self": "https://localhost:5000/v3/endpoints/12" - }, - "name": "the-endiest-of-points", - "region": "underground", - "service_id": "asdfasdfasdfasdf", - "url": "https://1.2.3.4:9000/" - }, - { - "id": "13", - "interface": "internal", - "links": { - "self": "https://localhost:5000/v3/endpoints/13" - }, - "name": "shhhh", - "region": "underground", - "service_id": "asdfasdfasdfasdf", - "url": "https://1.2.3.4:9001/" - } - ], - "links": { - "next": null, - "previous": null - } - } - `) - }) - - count := 0 - List(client.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractEndpoints(page) - if err != nil { - t.Errorf("Failed to extract endpoints: %v", err) - return false, err - } - - expected := []Endpoint{ - Endpoint{ - ID: "12", - Availability: gophercloud.AvailabilityPublic, - Name: "the-endiest-of-points", - Region: "underground", - ServiceID: "asdfasdfasdfasdf", - URL: "https://1.2.3.4:9000/", - }, - Endpoint{ - ID: "13", - Availability: gophercloud.AvailabilityInternal, - Name: "shhhh", - Region: "underground", - ServiceID: "asdfasdfasdfasdf", - URL: "https://1.2.3.4:9001/", - }, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, got %#v", expected, actual) - } - - return true, nil - }) - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestUpdateEndpoint(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/endpoints/12", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "PATCH") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - testhelper.TestJSONRequest(t, r, ` - { - "endpoint": { - "name": "renamed", - "region": "somewhere-else" - } - } - `) - - fmt.Fprintf(w, ` - { - "endpoint": { - "id": "12", - "interface": "public", - "links": { - "self": "https://localhost:5000/v3/endpoints/12" - }, - "name": "renamed", - "region": "somewhere-else", - "service_id": "asdfasdfasdfasdf", - "url": "https://1.2.3.4:9000/" - } - } - `) - }) - - actual, err := Update(client.ServiceClient(), "12", EndpointOpts{ - Name: "renamed", - Region: "somewhere-else", - }).Extract() - if err != nil { - t.Fatalf("Unexpected error from Update: %v", err) - } - - expected := &Endpoint{ - ID: "12", - Availability: gophercloud.AvailabilityPublic, - Name: "renamed", - Region: "somewhere-else", - ServiceID: "asdfasdfasdfasdf", - URL: "https://1.2.3.4:9000/", - } - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, was %#v", expected, actual) - } -} - -func TestDeleteEndpoint(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/endpoints/34", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "DELETE") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(client.ServiceClient(), "34") - testhelper.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/urls_test.go deleted file mode 100644 index 0b183b7434a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/endpoints/urls_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package endpoints - -import ( - "testing" - - "github.com/rackspace/gophercloud" -) - -func TestGetListURL(t *testing.T) { - client := gophercloud.ServiceClient{Endpoint: "http://localhost:5000/v3/"} - url := listURL(&client) - if url != "http://localhost:5000/v3/endpoints" { - t.Errorf("Unexpected list URL generated: [%s]", url) - } -} - -func TestGetEndpointURL(t *testing.T) { - client := gophercloud.ServiceClient{Endpoint: "http://localhost:5000/v3/"} - url := endpointURL(&client, "1234") - if url != "http://localhost:5000/v3/endpoints/1234" { - t.Errorf("Unexpected service URL generated: [%s]", url) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/requests_test.go deleted file mode 100644 index d62dbff9a2f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/requests_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package roles - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListSinglePage(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/role_assignments", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "GET") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "role_assignments": [ - { - "links": { - "assignment": "http://identity:35357/v3/domains/161718/users/313233/roles/123456" - }, - "role": { - "id": "123456" - }, - "scope": { - "domain": { - "id": "161718" - } - }, - "user": { - "id": "313233" - } - }, - { - "links": { - "assignment": "http://identity:35357/v3/projects/456789/groups/101112/roles/123456", - "membership": "http://identity:35357/v3/groups/101112/users/313233" - }, - "role": { - "id": "123456" - }, - "scope": { - "project": { - "id": "456789" - } - }, - "user": { - "id": "313233" - } - } - ], - "links": { - "self": "http://identity:35357/v3/role_assignments?effective", - "previous": null, - "next": null - } - } - `) - }) - - count := 0 - err := ListAssignments(client.ServiceClient(), ListAssignmentsOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractRoleAssignments(page) - if err != nil { - return false, err - } - - expected := []RoleAssignment{ - RoleAssignment{ - Role: Role{ID: "123456"}, - Scope: Scope{Domain: Domain{ID: "161718"}}, - User: User{ID: "313233"}, - Group: Group{}, - }, - RoleAssignment{ - Role: Role{ID: "123456"}, - Scope: Scope{Project: Project{ID: "456789"}}, - User: User{ID: "313233"}, - Group: Group{}, - }, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, got %#v", expected, actual) - } - - return true, nil - }) - if err != nil { - t.Errorf("Unexpected error while paging: %v", err) - } - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/urls_test.go deleted file mode 100644 index 04679dae403..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/roles/urls_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package roles - -import ( - "testing" - - "github.com/rackspace/gophercloud" -) - -func TestListAssignmentsURL(t *testing.T) { - client := gophercloud.ServiceClient{Endpoint: "http://localhost:5000/v3/"} - url := listAssignmentsURL(&client) - if url != "http://localhost:5000/v3/role_assignments" { - t.Errorf("Unexpected list URL generated: [%s]", url) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/requests_test.go deleted file mode 100644 index 42f05d365a5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/requests_test.go +++ /dev/null @@ -1,209 +0,0 @@ -package services - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestCreateSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/services", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "POST") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - testhelper.TestJSONRequest(t, r, `{ "type": "compute" }`) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ - "service": { - "description": "Here's your service", - "id": "1234", - "name": "InscrutableOpenStackProjectName", - "type": "compute" - } - }`) - }) - - result, err := Create(client.ServiceClient(), "compute").Extract() - if err != nil { - t.Fatalf("Unexpected error from Create: %v", err) - } - - if result.Description == nil || *result.Description != "Here's your service" { - t.Errorf("Service description was unexpected [%s]", *result.Description) - } - if result.ID != "1234" { - t.Errorf("Service ID was unexpected [%s]", result.ID) - } - if result.Name != "InscrutableOpenStackProjectName" { - t.Errorf("Service name was unexpected [%s]", result.Name) - } - if result.Type != "compute" { - t.Errorf("Service type was unexpected [%s]", result.Type) - } -} - -func TestListSinglePage(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/services", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "GET") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "links": { - "next": null, - "previous": null - }, - "services": [ - { - "description": "Service One", - "id": "1234", - "name": "service-one", - "type": "identity" - }, - { - "description": "Service Two", - "id": "9876", - "name": "service-two", - "type": "compute" - } - ] - } - `) - }) - - count := 0 - err := List(client.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractServices(page) - if err != nil { - return false, err - } - - desc0 := "Service One" - desc1 := "Service Two" - expected := []Service{ - Service{ - Description: &desc0, - ID: "1234", - Name: "service-one", - Type: "identity", - }, - Service{ - Description: &desc1, - ID: "9876", - Name: "service-two", - Type: "compute", - }, - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Expected %#v, got %#v", expected, actual) - } - - return true, nil - }) - if err != nil { - t.Errorf("Unexpected error while paging: %v", err) - } - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGetSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/services/12345", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "GET") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "service": { - "description": "Service One", - "id": "12345", - "name": "service-one", - "type": "identity" - } - } - `) - }) - - result, err := Get(client.ServiceClient(), "12345").Extract() - if err != nil { - t.Fatalf("Error fetching service information: %v", err) - } - - if result.ID != "12345" { - t.Errorf("Unexpected service ID: %s", result.ID) - } - if *result.Description != "Service One" { - t.Errorf("Unexpected service description: [%s]", *result.Description) - } - if result.Name != "service-one" { - t.Errorf("Unexpected service name: [%s]", result.Name) - } - if result.Type != "identity" { - t.Errorf("Unexpected service type: [%s]", result.Type) - } -} - -func TestUpdateSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/services/12345", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "PATCH") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - testhelper.TestJSONRequest(t, r, `{ "type": "lasermagic" }`) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "service": { - "id": "12345", - "type": "lasermagic" - } - } - `) - }) - - result, err := Update(client.ServiceClient(), "12345", "lasermagic").Extract() - if err != nil { - t.Fatalf("Unable to update service: %v", err) - } - - if result.ID != "12345" { - t.Fatalf("Expected ID 12345, was %s", result.ID) - } -} - -func TestDeleteSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - testhelper.Mux.HandleFunc("/services/12345", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "DELETE") - testhelper.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(client.ServiceClient(), "12345") - testhelper.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/urls_test.go deleted file mode 100644 index 5a31b32316c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/services/urls_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package services - -import ( - "testing" - - "github.com/rackspace/gophercloud" -) - -func TestListURL(t *testing.T) { - client := gophercloud.ServiceClient{Endpoint: "http://localhost:5000/v3/"} - url := listURL(&client) - if url != "http://localhost:5000/v3/services" { - t.Errorf("Unexpected list URL generated: [%s]", url) - } -} - -func TestServiceURL(t *testing.T) { - client := gophercloud.ServiceClient{Endpoint: "http://localhost:5000/v3/"} - url := serviceURL(&client, "1234") - if url != "http://localhost:5000/v3/services/1234" { - t.Errorf("Unexpected service URL generated: [%s]", url) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests_test.go deleted file mode 100644 index 2b26e4ad368..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/requests_test.go +++ /dev/null @@ -1,514 +0,0 @@ -package tokens - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/testhelper" -) - -// authTokenPost verifies that providing certain AuthOptions and Scope results in an expected JSON structure. -func authTokenPost(t *testing.T, options gophercloud.AuthOptions, scope *Scope, requestJSON string) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - client := gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{ - TokenID: "12345abcdef", - }, - Endpoint: testhelper.Endpoint(), - } - - testhelper.Mux.HandleFunc("/auth/tokens", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "POST") - testhelper.TestHeader(t, r, "Content-Type", "application/json") - testhelper.TestHeader(t, r, "Accept", "application/json") - testhelper.TestJSONRequest(t, r, requestJSON) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ - "token": { - "expires_at": "2014-10-02T13:45:00.000000Z" - } - }`) - }) - - _, err := Create(&client, options, scope).Extract() - if err != nil { - t.Errorf("Create returned an error: %v", err) - } -} - -func authTokenPostErr(t *testing.T, options gophercloud.AuthOptions, scope *Scope, includeToken bool, expectedErr error) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - client := gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{}, - Endpoint: testhelper.Endpoint(), - } - if includeToken { - client.TokenID = "abcdef123456" - } - - _, err := Create(&client, options, scope).Extract() - if err == nil { - t.Errorf("Create did NOT return an error") - } - if err != expectedErr { - t.Errorf("Create returned an unexpected error: wanted %v, got %v", expectedErr, err) - } -} - -func TestCreateUserIDAndPassword(t *testing.T) { - authTokenPost(t, gophercloud.AuthOptions{UserID: "me", Password: "squirrel!"}, nil, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { "id": "me", "password": "squirrel!" } - } - } - } - } - `) -} - -func TestCreateUsernameDomainIDPassword(t *testing.T) { - authTokenPost(t, gophercloud.AuthOptions{Username: "fakey", Password: "notpassword", DomainID: "abc123"}, nil, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "domain": { - "id": "abc123" - }, - "name": "fakey", - "password": "notpassword" - } - } - } - } - } - `) -} - -func TestCreateUsernameDomainNamePassword(t *testing.T) { - authTokenPost(t, gophercloud.AuthOptions{Username: "frank", Password: "swordfish", DomainName: "spork.net"}, nil, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "domain": { - "name": "spork.net" - }, - "name": "frank", - "password": "swordfish" - } - } - } - } - } - `) -} - -func TestCreateTokenID(t *testing.T) { - authTokenPost(t, gophercloud.AuthOptions{}, nil, ` - { - "auth": { - "identity": { - "methods": ["token"], - "token": { - "id": "12345abcdef" - } - } - } - } - `) -} - -func TestCreateProjectIDScope(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "fenris", Password: "g0t0h311"} - scope := &Scope{ProjectID: "123456"} - authTokenPost(t, options, scope, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "id": "fenris", - "password": "g0t0h311" - } - } - }, - "scope": { - "project": { - "id": "123456" - } - } - } - } - `) -} - -func TestCreateDomainIDScope(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "fenris", Password: "g0t0h311"} - scope := &Scope{DomainID: "1000"} - authTokenPost(t, options, scope, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "id": "fenris", - "password": "g0t0h311" - } - } - }, - "scope": { - "domain": { - "id": "1000" - } - } - } - } - `) -} - -func TestCreateProjectNameAndDomainIDScope(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "fenris", Password: "g0t0h311"} - scope := &Scope{ProjectName: "world-domination", DomainID: "1000"} - authTokenPost(t, options, scope, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "id": "fenris", - "password": "g0t0h311" - } - } - }, - "scope": { - "project": { - "domain": { - "id": "1000" - }, - "name": "world-domination" - } - } - } - } - `) -} - -func TestCreateProjectNameAndDomainNameScope(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "fenris", Password: "g0t0h311"} - scope := &Scope{ProjectName: "world-domination", DomainName: "evil-plans"} - authTokenPost(t, options, scope, ` - { - "auth": { - "identity": { - "methods": ["password"], - "password": { - "user": { - "id": "fenris", - "password": "g0t0h311" - } - } - }, - "scope": { - "project": { - "domain": { - "name": "evil-plans" - }, - "name": "world-domination" - } - } - } - } - `) -} - -func TestCreateExtractsTokenFromResponse(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - client := gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{}, - Endpoint: testhelper.Endpoint(), - } - - testhelper.Mux.HandleFunc("/auth/tokens", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("X-Subject-Token", "aaa111") - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{ - "token": { - "expires_at": "2014-10-02T13:45:00.000000Z" - } - }`) - }) - - options := gophercloud.AuthOptions{UserID: "me", Password: "shhh"} - token, err := Create(&client, options, nil).Extract() - if err != nil { - t.Fatalf("Create returned an error: %v", err) - } - - if token.ID != "aaa111" { - t.Errorf("Expected token to be aaa111, but was %s", token.ID) - } -} - -func TestCreateFailureEmptyAuth(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{}, nil, false, ErrMissingPassword) -} - -func TestCreateFailureAPIKey(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{APIKey: "something"}, nil, false, ErrAPIKeyProvided) -} - -func TestCreateFailureTenantID(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{TenantID: "something"}, nil, false, ErrTenantIDProvided) -} - -func TestCreateFailureTenantName(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{TenantName: "something"}, nil, false, ErrTenantNameProvided) -} - -func TestCreateFailureTokenIDUsername(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{Username: "something"}, nil, true, ErrUsernameWithToken) -} - -func TestCreateFailureTokenIDUserID(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{UserID: "something"}, nil, true, ErrUserIDWithToken) -} - -func TestCreateFailureTokenIDDomainID(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{DomainID: "something"}, nil, true, ErrDomainIDWithToken) -} - -func TestCreateFailureTokenIDDomainName(t *testing.T) { - authTokenPostErr(t, gophercloud.AuthOptions{DomainName: "something"}, nil, true, ErrDomainNameWithToken) -} - -func TestCreateFailureMissingUser(t *testing.T) { - options := gophercloud.AuthOptions{Password: "supersecure"} - authTokenPostErr(t, options, nil, false, ErrUsernameOrUserID) -} - -func TestCreateFailureBothUser(t *testing.T) { - options := gophercloud.AuthOptions{ - Password: "supersecure", - Username: "oops", - UserID: "redundancy", - } - authTokenPostErr(t, options, nil, false, ErrUsernameOrUserID) -} - -func TestCreateFailureMissingDomain(t *testing.T) { - options := gophercloud.AuthOptions{ - Password: "supersecure", - Username: "notuniqueenough", - } - authTokenPostErr(t, options, nil, false, ErrDomainIDOrDomainName) -} - -func TestCreateFailureBothDomain(t *testing.T) { - options := gophercloud.AuthOptions{ - Password: "supersecure", - Username: "someone", - DomainID: "hurf", - DomainName: "durf", - } - authTokenPostErr(t, options, nil, false, ErrDomainIDOrDomainName) -} - -func TestCreateFailureUserIDDomainID(t *testing.T) { - options := gophercloud.AuthOptions{ - UserID: "100", - Password: "stuff", - DomainID: "oops", - } - authTokenPostErr(t, options, nil, false, ErrDomainIDWithUserID) -} - -func TestCreateFailureUserIDDomainName(t *testing.T) { - options := gophercloud.AuthOptions{ - UserID: "100", - Password: "sssh", - DomainName: "oops", - } - authTokenPostErr(t, options, nil, false, ErrDomainNameWithUserID) -} - -func TestCreateFailureScopeProjectNameAlone(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{ProjectName: "notenough"} - authTokenPostErr(t, options, scope, false, ErrScopeDomainIDOrDomainName) -} - -func TestCreateFailureScopeProjectNameAndID(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{ProjectName: "whoops", ProjectID: "toomuch", DomainID: "1234"} - authTokenPostErr(t, options, scope, false, ErrScopeProjectIDOrProjectName) -} - -func TestCreateFailureScopeProjectIDAndDomainID(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{ProjectID: "toomuch", DomainID: "notneeded"} - authTokenPostErr(t, options, scope, false, ErrScopeProjectIDAlone) -} - -func TestCreateFailureScopeProjectIDAndDomainNAme(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{ProjectID: "toomuch", DomainName: "notneeded"} - authTokenPostErr(t, options, scope, false, ErrScopeProjectIDAlone) -} - -func TestCreateFailureScopeDomainIDAndDomainName(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{DomainID: "toomuch", DomainName: "notneeded"} - authTokenPostErr(t, options, scope, false, ErrScopeDomainIDOrDomainName) -} - -func TestCreateFailureScopeDomainNameAlone(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{DomainName: "notenough"} - authTokenPostErr(t, options, scope, false, ErrScopeDomainName) -} - -func TestCreateFailureEmptyScope(t *testing.T) { - options := gophercloud.AuthOptions{UserID: "myself", Password: "swordfish"} - scope := &Scope{} - authTokenPostErr(t, options, scope, false, ErrScopeEmpty) -} - -func TestGetRequest(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - client := gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{ - TokenID: "12345abcdef", - }, - Endpoint: testhelper.Endpoint(), - } - - testhelper.Mux.HandleFunc("/auth/tokens", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, "GET") - testhelper.TestHeader(t, r, "Content-Type", "") - testhelper.TestHeader(t, r, "Accept", "application/json") - testhelper.TestHeader(t, r, "X-Auth-Token", "12345abcdef") - testhelper.TestHeader(t, r, "X-Subject-Token", "abcdef12345") - - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` - { "token": { "expires_at": "2014-08-29T13:10:01.000000Z" } } - `) - }) - - token, err := Get(&client, "abcdef12345").Extract() - if err != nil { - t.Errorf("Info returned an error: %v", err) - } - - expected, _ := time.Parse(time.UnixDate, "Fri Aug 29 13:10:01 UTC 2014") - if token.ExpiresAt != expected { - t.Errorf("Expected expiration time %s, but was %s", expected.Format(time.UnixDate), token.ExpiresAt.Format(time.UnixDate)) - } -} - -func prepareAuthTokenHandler(t *testing.T, expectedMethod string, status int) gophercloud.ServiceClient { - client := gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{ - TokenID: "12345abcdef", - }, - Endpoint: testhelper.Endpoint(), - } - - testhelper.Mux.HandleFunc("/auth/tokens", func(w http.ResponseWriter, r *http.Request) { - testhelper.TestMethod(t, r, expectedMethod) - testhelper.TestHeader(t, r, "Content-Type", "") - testhelper.TestHeader(t, r, "Accept", "application/json") - testhelper.TestHeader(t, r, "X-Auth-Token", "12345abcdef") - testhelper.TestHeader(t, r, "X-Subject-Token", "abcdef12345") - - w.WriteHeader(status) - }) - - return client -} - -func TestValidateRequestSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - client := prepareAuthTokenHandler(t, "HEAD", http.StatusNoContent) - - ok, err := Validate(&client, "abcdef12345") - if err != nil { - t.Errorf("Unexpected error from Validate: %v", err) - } - - if !ok { - t.Errorf("Validate returned false for a valid token") - } -} - -func TestValidateRequestFailure(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - client := prepareAuthTokenHandler(t, "HEAD", http.StatusNotFound) - - ok, err := Validate(&client, "abcdef12345") - if err != nil { - t.Errorf("Unexpected error from Validate: %v", err) - } - - if ok { - t.Errorf("Validate returned true for an invalid token") - } -} - -func TestValidateRequestError(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - client := prepareAuthTokenHandler(t, "HEAD", http.StatusUnauthorized) - - _, err := Validate(&client, "abcdef12345") - if err == nil { - t.Errorf("Missing expected error from Validate") - } -} - -func TestRevokeRequestSuccessful(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - client := prepareAuthTokenHandler(t, "DELETE", http.StatusNoContent) - - res := Revoke(&client, "abcdef12345") - testhelper.AssertNoErr(t, res.Err) -} - -func TestRevokeRequestError(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - client := prepareAuthTokenHandler(t, "DELETE", http.StatusNotFound) - - res := Revoke(&client, "abcdef12345") - if res.Err == nil { - t.Errorf("Missing expected error from Revoke") - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls_test.go deleted file mode 100644 index 549c398620a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/identity/v3/tokens/urls_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package tokens - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/testhelper" -) - -func TestTokenURL(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - client := gophercloud.ServiceClient{Endpoint: testhelper.Endpoint()} - - expected := testhelper.Endpoint() + "auth/tokens" - actual := tokenURL(&client) - if actual != expected { - t.Errorf("Expected URL %s, but was %s", expected, actual) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/requests_test.go deleted file mode 100644 index d35af9f0c6b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/requests_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package apiversions - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListVersions(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "versions": [ - { - "status": "CURRENT", - "id": "v2.0", - "links": [ - { - "href": "http://23.253.228.211:9696/v2.0", - "rel": "self" - } - ] - } - ] -}`) - }) - - count := 0 - - ListVersions(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractAPIVersions(page) - if err != nil { - t.Errorf("Failed to extract API versions: %v", err) - return false, err - } - - expected := []APIVersion{ - APIVersion{ - Status: "CURRENT", - ID: "v2.0", - }, - } - - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestNonJSONCannotBeExtractedIntoAPIVersions(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - - ListVersions(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - if _, err := ExtractAPIVersions(page); err == nil { - t.Fatalf("Expected error, got nil") - } - return true, nil - }) -} - -func TestAPIInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "resources": [ - { - "links": [ - { - "href": "http://23.253.228.211:9696/v2.0/subnets", - "rel": "self" - } - ], - "name": "subnet", - "collection": "subnets" - }, - { - "links": [ - { - "href": "http://23.253.228.211:9696/v2.0/networks", - "rel": "self" - } - ], - "name": "network", - "collection": "networks" - }, - { - "links": [ - { - "href": "http://23.253.228.211:9696/v2.0/ports", - "rel": "self" - } - ], - "name": "port", - "collection": "ports" - } - ] -} - `) - }) - - count := 0 - - ListVersionResources(fake.ServiceClient(), "v2.0").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVersionResources(page) - if err != nil { - t.Errorf("Failed to extract version resources: %v", err) - return false, err - } - - expected := []APIVersionResource{ - APIVersionResource{ - Name: "subnet", - Collection: "subnets", - }, - APIVersionResource{ - Name: "network", - Collection: "networks", - }, - APIVersionResource{ - Name: "port", - Collection: "ports", - }, - } - - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestNonJSONCannotBeExtractedIntoAPIVersionResources(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - - ListVersionResources(fake.ServiceClient(), "v2.0").EachPage(func(page pagination.Page) (bool, error) { - if _, err := ExtractVersionResources(page); err == nil { - t.Fatalf("Expected error, got nil") - } - return true, nil - }) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/urls_test.go deleted file mode 100644 index 7dd069c94f5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/apiversions/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package apiversions - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestAPIVersionsURL(t *testing.T) { - actual := apiVersionsURL(endpointClient()) - expected := endpoint - th.AssertEquals(t, expected, actual) -} - -func TestAPIInfoURL(t *testing.T) { - actual := apiInfoURL(endpointClient(), "v2.0") - expected := endpoint + "v2.0/" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/delegate_test.go deleted file mode 100644 index 3d2ac78d482..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/delegate_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package extensions - -import ( - "fmt" - "net/http" - "testing" - - common "github.com/rackspace/gophercloud/openstack/common/extensions" - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/extensions", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - - fmt.Fprintf(w, ` -{ - "extensions": [ - { - "updated": "2013-01-20T00:00:00-00:00", - "name": "Neutron Service Type Management", - "links": [], - "namespace": "http://docs.openstack.org/ext/neutron/service-type/api/v1.0", - "alias": "service-type", - "description": "API for retrieving service providers for Neutron advanced services" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractExtensions(page) - if err != nil { - t.Errorf("Failed to extract extensions: %v", err) - } - - expected := []Extension{ - Extension{ - common.Extension{ - Updated: "2013-01-20T00:00:00-00:00", - Name: "Neutron Service Type Management", - Links: []interface{}{}, - Namespace: "http://docs.openstack.org/ext/neutron/service-type/api/v1.0", - Alias: "service-type", - Description: "API for retrieving service providers for Neutron advanced services", - }, - }, - } - - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/extensions/agent", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "extension": { - "updated": "2013-02-03T10:00:00-00:00", - "name": "agent", - "links": [], - "namespace": "http://docs.openstack.org/ext/agent/api/v2.0", - "alias": "agent", - "description": "The agent management extension." - } -} - `) - }) - - ext, err := Get(fake.ServiceClient(), "agent").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, ext.Updated, "2013-02-03T10:00:00-00:00") - th.AssertEquals(t, ext.Name, "agent") - th.AssertEquals(t, ext.Namespace, "http://docs.openstack.org/ext/agent/api/v2.0") - th.AssertEquals(t, ext.Alias, "agent") - th.AssertEquals(t, ext.Description, "The agent management extension.") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external/results_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external/results_test.go deleted file mode 100644 index 916cd2cfd03..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/external/results_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package external - -import ( - "errors" - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "networks": [ - { - "admin_state_up": true, - "id": "0f38d5ad-10a6-428f-a5fc-825cfe0f1970", - "name": "net1", - "router:external": false, - "shared": false, - "status": "ACTIVE", - "subnets": [ - "25778974-48a8-46e7-8998-9dc8c70d2f06" - ], - "tenant_id": "b575417a6c444a6eb5cc3a58eb4f714a" - }, - { - "admin_state_up": true, - "id": "8d05a1b1-297a-46ca-8974-17debf51ca3c", - "name": "ext_net", - "router:external": true, - "shared": false, - "status": "ACTIVE", - "subnets": [ - "2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5" - ], - "tenant_id": "5eb8995cf717462c9df8d1edfa498010" - } - ] -} - `) - }) - - count := 0 - - networks.List(fake.ServiceClient(), networks.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractList(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []NetworkExternal{ - NetworkExternal{ - Status: "ACTIVE", - Subnets: []string{"25778974-48a8-46e7-8998-9dc8c70d2f06"}, - Name: "net1", - AdminStateUp: true, - TenantID: "b575417a6c444a6eb5cc3a58eb4f714a", - Shared: false, - ID: "0f38d5ad-10a6-428f-a5fc-825cfe0f1970", - External: false, - }, - NetworkExternal{ - Status: "ACTIVE", - Subnets: []string{"2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5"}, - Name: "ext_net", - AdminStateUp: true, - TenantID: "5eb8995cf717462c9df8d1edfa498010", - Shared: false, - ID: "8d05a1b1-297a-46ca-8974-17debf51ca3c", - External: true, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "admin_state_up": true, - "id": "8d05a1b1-297a-46ca-8974-17debf51ca3c", - "name": "ext_net", - "router:external": true, - "shared": false, - "status": "ACTIVE", - "subnets": [ - "2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5" - ], - "tenant_id": "5eb8995cf717462c9df8d1edfa498010" - } -} - `) - }) - - res := networks.Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - n, err := ExtractGet(res) - - th.AssertNoErr(t, err) - th.AssertEquals(t, true, n.External) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "admin_state_up": true, - "name": "ext_net", - "router:external": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "network": { - "admin_state_up": true, - "id": "8d05a1b1-297a-46ca-8974-17debf51ca3c", - "name": "ext_net", - "router:external": true, - "shared": false, - "status": "ACTIVE", - "subnets": [ - "2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5" - ], - "tenant_id": "5eb8995cf717462c9df8d1edfa498010" - } -} - `) - }) - - options := CreateOpts{networks.CreateOpts{Name: "ext_net", AdminStateUp: Up}, true} - res := networks.Create(fake.ServiceClient(), options) - - n, err := ExtractCreate(res) - - th.AssertNoErr(t, err) - th.AssertEquals(t, true, n.External) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "router:external": true, - "name": "new_name" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "admin_state_up": true, - "id": "8d05a1b1-297a-46ca-8974-17debf51ca3c", - "name": "new_name", - "router:external": true, - "shared": false, - "status": "ACTIVE", - "subnets": [ - "2f1fb918-9b0e-4bf9-9a50-6cebbb4db2c5" - ], - "tenant_id": "5eb8995cf717462c9df8d1edfa498010" - } -} - `) - }) - - options := UpdateOpts{networks.UpdateOpts{Name: "new_name"}, true} - res := networks.Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options) - n, err := ExtractUpdate(res) - - th.AssertNoErr(t, err) - th.AssertEquals(t, true, n.External) -} - -func TestExtractFnsReturnsErrWhenResultContainsErr(t *testing.T) { - gr := networks.GetResult{} - gr.Err = errors.New("") - - if _, err := ExtractGet(gr); err == nil { - t.Fatalf("Expected error, got one") - } - - ur := networks.UpdateResult{} - ur.Err = errors.New("") - - if _, err := ExtractUpdate(ur); err == nil { - t.Fatalf("Expected error, got one") - } - - cr := networks.CreateResult{} - cr.Err = errors.New("") - - if _, err := ExtractCreate(cr); err == nil { - t.Fatalf("Expected error, got one") - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests_test.go deleted file mode 100644 index 19d32c5ac30..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls/requests_test.go +++ /dev/null @@ -1,246 +0,0 @@ -package firewalls - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/fw/firewalls", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewalls", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewalls":[ - { - "status": "ACTIVE", - "name": "fw1", - "admin_state_up": false, - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b", - "firewall_policy_id": "34be8c83-4d42-4dca-a74e-b77fffb8e28a", - "id": "fb5b5315-64f6-4ea3-8e58-981cc37c6f61", - "description": "OpenStack firewall 1" - }, - { - "status": "PENDING_UPDATE", - "name": "fw2", - "admin_state_up": true, - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b", - "firewall_policy_id": "34be8c83-4d42-4dca-a74e-b77fffb8e299", - "id": "fb5b5315-64f6-4ea3-8e58-981cc37c6f99", - "description": "OpenStack firewall 2" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractFirewalls(page) - if err != nil { - t.Errorf("Failed to extract members: %v", err) - return false, err - } - - expected := []Firewall{ - Firewall{ - Status: "ACTIVE", - Name: "fw1", - AdminStateUp: false, - TenantID: "b4eedccc6fb74fa8a7ad6b08382b852b", - PolicyID: "34be8c83-4d42-4dca-a74e-b77fffb8e28a", - ID: "fb5b5315-64f6-4ea3-8e58-981cc37c6f61", - Description: "OpenStack firewall 1", - }, - Firewall{ - Status: "PENDING_UPDATE", - Name: "fw2", - AdminStateUp: true, - TenantID: "b4eedccc6fb74fa8a7ad6b08382b852b", - PolicyID: "34be8c83-4d42-4dca-a74e-b77fffb8e299", - ID: "fb5b5315-64f6-4ea3-8e58-981cc37c6f99", - Description: "OpenStack firewall 2", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewalls", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall":{ - "name": "fw", - "description": "OpenStack firewall", - "admin_state_up": true, - "firewall_policy_id": "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c", - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "firewall":{ - "status": "PENDING_CREATE", - "name": "fw", - "description": "OpenStack firewall", - "admin_state_up": true, - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b", - "firewall_policy_id": "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c" - } -} - `) - }) - - options := CreateOpts{ - TenantID: "b4eedccc6fb74fa8a7ad6b08382b852b", - Name: "fw", - Description: "OpenStack firewall", - AdminStateUp: Up, - PolicyID: "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c", - } - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewalls/fb5b5315-64f6-4ea3-8e58-981cc37c6f61", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall": { - "status": "ACTIVE", - "name": "fw", - "admin_state_up": true, - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b", - "firewall_policy_id": "34be8c83-4d42-4dca-a74e-b77fffb8e28a", - "id": "fb5b5315-64f6-4ea3-8e58-981cc37c6f61", - "description": "OpenStack firewall" - } -} - `) - }) - - fw, err := Get(fake.ServiceClient(), "fb5b5315-64f6-4ea3-8e58-981cc37c6f61").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "ACTIVE", fw.Status) - th.AssertEquals(t, "fw", fw.Name) - th.AssertEquals(t, "OpenStack firewall", fw.Description) - th.AssertEquals(t, true, fw.AdminStateUp) - th.AssertEquals(t, "34be8c83-4d42-4dca-a74e-b77fffb8e28a", fw.PolicyID) - th.AssertEquals(t, "fb5b5315-64f6-4ea3-8e58-981cc37c6f61", fw.ID) - th.AssertEquals(t, "b4eedccc6fb74fa8a7ad6b08382b852b", fw.TenantID) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewalls/ea5b5315-64f6-4ea3-8e58-981cc37c6576", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall":{ - "name": "fw", - "description": "updated fw", - "admin_state_up":false, - "firewall_policy_id": "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall": { - "status": "ACTIVE", - "name": "fw", - "admin_state_up": false, - "tenant_id": "b4eedccc6fb74fa8a7ad6b08382b852b", - "firewall_policy_id": "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c", - "id": "ea5b5315-64f6-4ea3-8e58-981cc37c6576", - "description": "OpenStack firewall" - } -} - `) - }) - - options := UpdateOpts{ - Name: "fw", - Description: "updated fw", - AdminStateUp: Down, - PolicyID: "19ab8c87-4a32-4e6a-a74e-b77fffb89a0c", - } - - _, err := Update(fake.ServiceClient(), "ea5b5315-64f6-4ea3-8e58-981cc37c6576", options).Extract() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewalls/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests_test.go deleted file mode 100644 index b9d78652c32..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies/requests_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package policies - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/fw/firewall_policies", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_policies", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_policies": [ - { - "name": "policy1", - "firewall_rules": [ - "75452b36-268e-4e75-aaf4-f0e7ed50bc97", - "c9e77ca0-1bc8-497d-904d-948107873dc6" - ], - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": true, - "shared": false, - "id": "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", - "description": "Firewall policy 1" - }, - { - "name": "policy2", - "firewall_rules": [ - "03d2a6ad-633f-431a-8463-4370d06a22c8" - ], - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": false, - "shared": true, - "id": "c854fab5-bdaf-4a86-9359-78de93e5df01", - "description": "Firewall policy 2" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPolicies(page) - if err != nil { - t.Errorf("Failed to extract members: %v", err) - return false, err - } - - expected := []Policy{ - Policy{ - Name: "policy1", - Rules: []string{ - "75452b36-268e-4e75-aaf4-f0e7ed50bc97", - "c9e77ca0-1bc8-497d-904d-948107873dc6", - }, - TenantID: "9145d91459d248b1b02fdaca97c6a75d", - Audited: true, - Shared: false, - ID: "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", - Description: "Firewall policy 1", - }, - Policy{ - Name: "policy2", - Rules: []string{ - "03d2a6ad-633f-431a-8463-4370d06a22c8", - }, - TenantID: "9145d91459d248b1b02fdaca97c6a75d", - Audited: false, - Shared: true, - ID: "c854fab5-bdaf-4a86-9359-78de93e5df01", - Description: "Firewall policy 2", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_policies", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall_policy":{ - "name": "policy", - "firewall_rules": [ - "98a58c87-76be-ae7c-a74e-b77fffb88d95", - "11a58c87-76be-ae7c-a74e-b77fffb88a32" - ], - "description": "Firewall policy", - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": true, - "shared": false - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "firewall_policy":{ - "name": "policy", - "firewall_rules": [ - "98a58c87-76be-ae7c-a74e-b77fffb88d95", - "11a58c87-76be-ae7c-a74e-b77fffb88a32" - ], - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": false, - "id": "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", - "description": "Firewall policy" - } -} - `) - }) - - options := CreateOpts{ - TenantID: "9145d91459d248b1b02fdaca97c6a75d", - Name: "policy", - Description: "Firewall policy", - Shared: No, - Audited: Yes, - Rules: []string{ - "98a58c87-76be-ae7c-a74e-b77fffb88d95", - "11a58c87-76be-ae7c-a74e-b77fffb88a32", - }, - } - - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_policies/bcab5315-64f6-4ea3-8e58-981cc37c6f61", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_policy":{ - "name": "www", - "firewall_rules": [ - "75452b36-268e-4e75-aaf4-f0e7ed50bc97", - "c9e77ca0-1bc8-497d-904d-948107873dc6", - "03d2a6ad-633f-431a-8463-4370d06a22c8" - ], - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": false, - "id": "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", - "description": "Firewall policy web" - } -} - `) - }) - - policy, err := Get(fake.ServiceClient(), "bcab5315-64f6-4ea3-8e58-981cc37c6f61").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "www", policy.Name) - th.AssertEquals(t, "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", policy.ID) - th.AssertEquals(t, "Firewall policy web", policy.Description) - th.AssertEquals(t, 3, len(policy.Rules)) - th.AssertEquals(t, "75452b36-268e-4e75-aaf4-f0e7ed50bc97", policy.Rules[0]) - th.AssertEquals(t, "c9e77ca0-1bc8-497d-904d-948107873dc6", policy.Rules[1]) - th.AssertEquals(t, "03d2a6ad-633f-431a-8463-4370d06a22c8", policy.Rules[2]) - th.AssertEquals(t, "9145d91459d248b1b02fdaca97c6a75d", policy.TenantID) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_policies/f2b08c1e-aa81-4668-8ae1-1401bcb0576c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall_policy":{ - "name": "policy", - "firewall_rules": [ - "98a58c87-76be-ae7c-a74e-b77fffb88d95", - "11a58c87-76be-ae7c-a74e-b77fffb88a32" - ], - "description": "Firewall policy" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_policy":{ - "name": "policy", - "firewall_rules": [ - "75452b36-268e-4e75-aaf4-f0e7ed50bc97", - "c9e77ca0-1bc8-497d-904d-948107873dc6", - "03d2a6ad-633f-431a-8463-4370d06a22c8" - ], - "tenant_id": "9145d91459d248b1b02fdaca97c6a75d", - "audited": false, - "id": "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", - "description": "Firewall policy" - } -} - `) - }) - - options := UpdateOpts{ - Name: "policy", - Description: "Firewall policy", - Rules: []string{ - "98a58c87-76be-ae7c-a74e-b77fffb88d95", - "11a58c87-76be-ae7c-a74e-b77fffb88a32", - }, - } - - _, err := Update(fake.ServiceClient(), "f2b08c1e-aa81-4668-8ae1-1401bcb0576c", options).Extract() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_policies/4ec89077-d057-4a2b-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89077-d057-4a2b-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests_test.go deleted file mode 100644 index 36f89fa5c49..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules/requests_test.go +++ /dev/null @@ -1,328 +0,0 @@ -package rules - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/fw/firewall_rules", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_rules": [ - { - "protocol": "tcp", - "description": "ssh rule", - "source_port": null, - "source_ip_address": null, - "destination_ip_address": "192.168.1.0/24", - "firewall_policy_id": "e2a5fb51-698c-4898-87e8-f1eee6b50919", - "position": 2, - "destination_port": "22", - "id": "f03bd950-6c56-4f5e-a307-45967078f507", - "name": "ssh_form_any", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61", - "enabled": true, - "action": "allow", - "ip_version": 4, - "shared": false - }, - { - "protocol": "udp", - "description": "udp rule", - "source_port": null, - "source_ip_address": null, - "destination_ip_address": null, - "firewall_policy_id": "98d7fb51-698c-4123-87e8-f1eee6b5ab7e", - "position": 1, - "destination_port": null, - "id": "ab7bd950-6c56-4f5e-a307-45967078f890", - "name": "deny_all_udp", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61", - "enabled": true, - "action": "deny", - "ip_version": 4, - "shared": false - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract members: %v", err) - return false, err - } - - expected := []Rule{ - Rule{ - Protocol: "tcp", - Description: "ssh rule", - SourcePort: "", - SourceIPAddress: "", - DestinationIPAddress: "192.168.1.0/24", - PolicyID: "e2a5fb51-698c-4898-87e8-f1eee6b50919", - Position: 2, - DestinationPort: "22", - ID: "f03bd950-6c56-4f5e-a307-45967078f507", - Name: "ssh_form_any", - TenantID: "80cf934d6ffb4ef5b244f1c512ad1e61", - Enabled: true, - Action: "allow", - IPVersion: 4, - Shared: false, - }, - Rule{ - Protocol: "udp", - Description: "udp rule", - SourcePort: "", - SourceIPAddress: "", - DestinationIPAddress: "", - PolicyID: "98d7fb51-698c-4123-87e8-f1eee6b5ab7e", - Position: 1, - DestinationPort: "", - ID: "ab7bd950-6c56-4f5e-a307-45967078f890", - Name: "deny_all_udp", - TenantID: "80cf934d6ffb4ef5b244f1c512ad1e61", - Enabled: true, - Action: "deny", - IPVersion: 4, - Shared: false, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall_rule": { - "protocol": "tcp", - "description": "ssh rule", - "destination_ip_address": "192.168.1.0/24", - "destination_port": "22", - "name": "ssh_form_any", - "action": "allow", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "firewall_rule":{ - "protocol": "tcp", - "description": "ssh rule", - "source_port": null, - "source_ip_address": null, - "destination_ip_address": "192.168.1.0/24", - "firewall_policy_id": "e2a5fb51-698c-4898-87e8-f1eee6b50919", - "position": 2, - "destination_port": "22", - "id": "f03bd950-6c56-4f5e-a307-45967078f507", - "name": "ssh_form_any", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61", - "enabled": true, - "action": "allow", - "ip_version": 4, - "shared": false - } -} - `) - }) - - options := CreateOpts{ - TenantID: "80cf934d6ffb4ef5b244f1c512ad1e61", - Protocol: "tcp", - Description: "ssh rule", - DestinationIPAddress: "192.168.1.0/24", - DestinationPort: "22", - Name: "ssh_form_any", - Action: "allow", - } - - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_rules/f03bd950-6c56-4f5e-a307-45967078f507", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_rule":{ - "protocol": "tcp", - "description": "ssh rule", - "source_port": null, - "source_ip_address": null, - "destination_ip_address": "192.168.1.0/24", - "firewall_policy_id": "e2a5fb51-698c-4898-87e8-f1eee6b50919", - "position": 2, - "destination_port": "22", - "id": "f03bd950-6c56-4f5e-a307-45967078f507", - "name": "ssh_form_any", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61", - "enabled": true, - "action": "allow", - "ip_version": 4, - "shared": false - } -} - `) - }) - - rule, err := Get(fake.ServiceClient(), "f03bd950-6c56-4f5e-a307-45967078f507").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "tcp", rule.Protocol) - th.AssertEquals(t, "ssh rule", rule.Description) - th.AssertEquals(t, "192.168.1.0/24", rule.DestinationIPAddress) - th.AssertEquals(t, "e2a5fb51-698c-4898-87e8-f1eee6b50919", rule.PolicyID) - th.AssertEquals(t, 2, rule.Position) - th.AssertEquals(t, "22", rule.DestinationPort) - th.AssertEquals(t, "f03bd950-6c56-4f5e-a307-45967078f507", rule.ID) - th.AssertEquals(t, "ssh_form_any", rule.Name) - th.AssertEquals(t, "80cf934d6ffb4ef5b244f1c512ad1e61", rule.TenantID) - th.AssertEquals(t, true, rule.Enabled) - th.AssertEquals(t, "allow", rule.Action) - th.AssertEquals(t, 4, rule.IPVersion) - th.AssertEquals(t, false, rule.Shared) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_rules/f03bd950-6c56-4f5e-a307-45967078f507", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "firewall_rule":{ - "protocol": "tcp", - "description": "ssh rule", - "destination_ip_address": "192.168.1.0/24", - "destination_port": "22", - "source_ip_address": null, - "source_port": null, - "name": "ssh_form_any", - "action": "allow", - "enabled": false - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "firewall_rule":{ - "protocol": "tcp", - "description": "ssh rule", - "source_port": null, - "source_ip_address": null, - "destination_ip_address": "192.168.1.0/24", - "firewall_policy_id": "e2a5fb51-698c-4898-87e8-f1eee6b50919", - "position": 2, - "destination_port": "22", - "id": "f03bd950-6c56-4f5e-a307-45967078f507", - "name": "ssh_form_any", - "tenant_id": "80cf934d6ffb4ef5b244f1c512ad1e61", - "enabled": false, - "action": "allow", - "ip_version": 4, - "shared": false - } -} - `) - }) - - destinationIPAddress := "192.168.1.0/24" - destinationPort := "22" - empty := "" - - options := UpdateOpts{ - Protocol: "tcp", - Description: "ssh rule", - DestinationIPAddress: &destinationIPAddress, - DestinationPort: &destinationPort, - Name: "ssh_form_any", - SourceIPAddress: &empty, - SourcePort: &empty, - Action: "allow", - Enabled: No, - } - - _, err := Update(fake.ServiceClient(), "f03bd950-6c56-4f5e-a307-45967078f507", options).Extract() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/fw/firewall_rules/4ec89077-d057-4a2b-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89077-d057-4a2b-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests_test.go deleted file mode 100644 index d914a799bfc..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/floatingips/requests_test.go +++ /dev/null @@ -1,355 +0,0 @@ -package floatingips - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "floatingips": [ - { - "floating_network_id": "6d67c30a-ddb4-49a1-bec3-a65b286b4170", - "router_id": null, - "fixed_ip_address": null, - "floating_ip_address": "192.0.0.4", - "tenant_id": "017d8de156df4177889f31a9bd6edc00", - "status": "DOWN", - "port_id": null, - "id": "2f95fd2b-9f6a-4e8e-9e9a-2cbe286cbf9e" - }, - { - "floating_network_id": "90f742b1-6d17-487b-ba95-71881dbc0b64", - "router_id": "0a24cb83-faf5-4d7f-b723-3144ed8a2167", - "fixed_ip_address": "192.0.0.2", - "floating_ip_address": "10.0.0.3", - "tenant_id": "017d8de156df4177889f31a9bd6edc00", - "status": "DOWN", - "port_id": "74a342ce-8e07-4e91-880c-9f834b68fa25", - "id": "ada25a95-f321-4f59-b0e0-f3a970dd3d63" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractFloatingIPs(page) - if err != nil { - t.Errorf("Failed to extract floating IPs: %v", err) - return false, err - } - - expected := []FloatingIP{ - FloatingIP{ - FloatingNetworkID: "6d67c30a-ddb4-49a1-bec3-a65b286b4170", - FixedIP: "", - FloatingIP: "192.0.0.4", - TenantID: "017d8de156df4177889f31a9bd6edc00", - Status: "DOWN", - PortID: "", - ID: "2f95fd2b-9f6a-4e8e-9e9a-2cbe286cbf9e", - }, - FloatingIP{ - FloatingNetworkID: "90f742b1-6d17-487b-ba95-71881dbc0b64", - FixedIP: "192.0.0.2", - FloatingIP: "10.0.0.3", - TenantID: "017d8de156df4177889f31a9bd6edc00", - Status: "DOWN", - PortID: "74a342ce-8e07-4e91-880c-9f834b68fa25", - ID: "ada25a95-f321-4f59-b0e0-f3a970dd3d63", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestInvalidNextPageURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, `{"floatingips": [{}], "floatingips_links": {}}`) - }) - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - ExtractFloatingIPs(page) - return true, nil - }) -} - -func TestRequiredFieldsForCreate(t *testing.T) { - res1 := Create(fake.ServiceClient(), CreateOpts{FloatingNetworkID: ""}) - if res1.Err == nil { - t.Fatalf("Expected error, got none") - } - - res2 := Create(fake.ServiceClient(), CreateOpts{FloatingNetworkID: "foo", PortID: ""}) - if res2.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "floatingip": { - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57", - "port_id": "ce705c24-c1ef-408a-bda3-7bbd946164ab" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "floatingip": { - "router_id": "d23abc8d-2991-4a55-ba98-2aaea84cc72f", - "tenant_id": "4969c491a3c74ee4af974e6d800c62de", - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57", - "fixed_ip_address": "10.0.0.3", - "floating_ip_address": "", - "port_id": "ce705c24-c1ef-408a-bda3-7bbd946164ab", - "id": "2f245a7b-796b-4f26-9cf9-9e82d248fda7" - } -} - `) - }) - - options := CreateOpts{ - FloatingNetworkID: "376da547-b977-4cfe-9cba-275c80debf57", - PortID: "ce705c24-c1ef-408a-bda3-7bbd946164ab", - } - - ip, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "2f245a7b-796b-4f26-9cf9-9e82d248fda7", ip.ID) - th.AssertEquals(t, "4969c491a3c74ee4af974e6d800c62de", ip.TenantID) - th.AssertEquals(t, "376da547-b977-4cfe-9cba-275c80debf57", ip.FloatingNetworkID) - th.AssertEquals(t, "", ip.FloatingIP) - th.AssertEquals(t, "ce705c24-c1ef-408a-bda3-7bbd946164ab", ip.PortID) - th.AssertEquals(t, "10.0.0.3", ip.FixedIP) -} - -func TestCreateEmptyPort(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - { - "floatingip": { - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57" - } - } - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` - { - "floatingip": { - "router_id": "d23abc8d-2991-4a55-ba98-2aaea84cc72f", - "tenant_id": "4969c491a3c74ee4af974e6d800c62de", - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57", - "fixed_ip_address": "10.0.0.3", - "floating_ip_address": "", - "id": "2f245a7b-796b-4f26-9cf9-9e82d248fda7" - } - } - `) - }) - - options := CreateOpts{ - FloatingNetworkID: "376da547-b977-4cfe-9cba-275c80debf57", - } - - ip, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "2f245a7b-796b-4f26-9cf9-9e82d248fda7", ip.ID) - th.AssertEquals(t, "4969c491a3c74ee4af974e6d800c62de", ip.TenantID) - th.AssertEquals(t, "376da547-b977-4cfe-9cba-275c80debf57", ip.FloatingNetworkID) - th.AssertEquals(t, "", ip.FloatingIP) - th.AssertEquals(t, "", ip.PortID) - th.AssertEquals(t, "10.0.0.3", ip.FixedIP) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips/2f245a7b-796b-4f26-9cf9-9e82d248fda7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "floatingip": { - "floating_network_id": "90f742b1-6d17-487b-ba95-71881dbc0b64", - "fixed_ip_address": "192.0.0.2", - "floating_ip_address": "10.0.0.3", - "tenant_id": "017d8de156df4177889f31a9bd6edc00", - "status": "DOWN", - "port_id": "74a342ce-8e07-4e91-880c-9f834b68fa25", - "id": "2f245a7b-796b-4f26-9cf9-9e82d248fda7" - } -} - `) - }) - - ip, err := Get(fake.ServiceClient(), "2f245a7b-796b-4f26-9cf9-9e82d248fda7").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "90f742b1-6d17-487b-ba95-71881dbc0b64", ip.FloatingNetworkID) - th.AssertEquals(t, "10.0.0.3", ip.FloatingIP) - th.AssertEquals(t, "74a342ce-8e07-4e91-880c-9f834b68fa25", ip.PortID) - th.AssertEquals(t, "192.0.0.2", ip.FixedIP) - th.AssertEquals(t, "017d8de156df4177889f31a9bd6edc00", ip.TenantID) - th.AssertEquals(t, "DOWN", ip.Status) - th.AssertEquals(t, "2f245a7b-796b-4f26-9cf9-9e82d248fda7", ip.ID) -} - -func TestAssociate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips/2f245a7b-796b-4f26-9cf9-9e82d248fda7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "floatingip": { - "port_id": "423abc8d-2991-4a55-ba98-2aaea84cc72e" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "floatingip": { - "router_id": "d23abc8d-2991-4a55-ba98-2aaea84cc72f", - "tenant_id": "4969c491a3c74ee4af974e6d800c62de", - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57", - "fixed_ip_address": null, - "floating_ip_address": "172.24.4.228", - "port_id": "423abc8d-2991-4a55-ba98-2aaea84cc72e", - "id": "2f245a7b-796b-4f26-9cf9-9e82d248fda7" - } -} - `) - }) - - ip, err := Update(fake.ServiceClient(), "2f245a7b-796b-4f26-9cf9-9e82d248fda7", UpdateOpts{PortID: "423abc8d-2991-4a55-ba98-2aaea84cc72e"}).Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, "423abc8d-2991-4a55-ba98-2aaea84cc72e", ip.PortID) -} - -func TestDisassociate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips/2f245a7b-796b-4f26-9cf9-9e82d248fda7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "floatingip": { - "port_id": null - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "floatingip": { - "router_id": "d23abc8d-2991-4a55-ba98-2aaea84cc72f", - "tenant_id": "4969c491a3c74ee4af974e6d800c62de", - "floating_network_id": "376da547-b977-4cfe-9cba-275c80debf57", - "fixed_ip_address": null, - "floating_ip_address": "172.24.4.228", - "port_id": null, - "id": "2f245a7b-796b-4f26-9cf9-9e82d248fda7" - } -} - `) - }) - - ip, err := Update(fake.ServiceClient(), "2f245a7b-796b-4f26-9cf9-9e82d248fda7", UpdateOpts{}).Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, "", ip.FixedIP) - th.AssertDeepEquals(t, "", ip.PortID) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/floatingips/2f245a7b-796b-4f26-9cf9-9e82d248fda7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "2f245a7b-796b-4f26-9cf9-9e82d248fda7") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests_test.go deleted file mode 100644 index c34264daee5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/layer3/routers/requests_test.go +++ /dev/null @@ -1,338 +0,0 @@ -package routers - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/routers", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "routers": [ - { - "status": "ACTIVE", - "external_gateway_info": null, - "name": "second_routers", - "admin_state_up": true, - "tenant_id": "6b96ff0cb17a4b859e1e575d221683d3", - "id": "7177abc4-5ae9-4bb7-b0d4-89e94a4abf3b" - }, - { - "status": "ACTIVE", - "external_gateway_info": { - "network_id": "3c5bcddd-6af9-4e6b-9c3e-c153e521cab8" - }, - "name": "router1", - "admin_state_up": true, - "tenant_id": "33a40233088643acb66ff6eb0ebea679", - "id": "a9254bdb-2613-4a13-ac4c-adc581fba50d" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractRouters(page) - if err != nil { - t.Errorf("Failed to extract routers: %v", err) - return false, err - } - - expected := []Router{ - Router{ - Status: "ACTIVE", - GatewayInfo: GatewayInfo{NetworkID: ""}, - AdminStateUp: true, - Name: "second_routers", - ID: "7177abc4-5ae9-4bb7-b0d4-89e94a4abf3b", - TenantID: "6b96ff0cb17a4b859e1e575d221683d3", - }, - Router{ - Status: "ACTIVE", - GatewayInfo: GatewayInfo{NetworkID: "3c5bcddd-6af9-4e6b-9c3e-c153e521cab8"}, - AdminStateUp: true, - Name: "router1", - ID: "a9254bdb-2613-4a13-ac4c-adc581fba50d", - TenantID: "33a40233088643acb66ff6eb0ebea679", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "router":{ - "name": "foo_router", - "admin_state_up": false, - "external_gateway_info":{ - "network_id":"8ca37218-28ff-41cb-9b10-039601ea7e6b" - } - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "router": { - "status": "ACTIVE", - "external_gateway_info": { - "network_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b" - }, - "name": "foo_router", - "admin_state_up": false, - "tenant_id": "6b96ff0cb17a4b859e1e575d221683d3", - "id": "8604a0de-7f6b-409a-a47c-a1cc7bc77b2e" - } -} - `) - }) - - asu := false - gwi := GatewayInfo{NetworkID: "8ca37218-28ff-41cb-9b10-039601ea7e6b"} - - options := CreateOpts{ - Name: "foo_router", - AdminStateUp: &asu, - GatewayInfo: &gwi, - } - r, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "foo_router", r.Name) - th.AssertEquals(t, false, r.AdminStateUp) - th.AssertDeepEquals(t, GatewayInfo{NetworkID: "8ca37218-28ff-41cb-9b10-039601ea7e6b"}, r.GatewayInfo) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers/a07eea83-7710-4860-931b-5fe220fae533", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "router": { - "status": "ACTIVE", - "external_gateway_info": { - "network_id": "85d76829-6415-48ff-9c63-5c5ca8c61ac6" - }, - "name": "router1", - "admin_state_up": true, - "tenant_id": "d6554fe62e2f41efbb6e026fad5c1542", - "id": "a07eea83-7710-4860-931b-5fe220fae533" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "a07eea83-7710-4860-931b-5fe220fae533").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.GatewayInfo, GatewayInfo{NetworkID: "85d76829-6415-48ff-9c63-5c5ca8c61ac6"}) - th.AssertEquals(t, n.Name, "router1") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.TenantID, "d6554fe62e2f41efbb6e026fad5c1542") - th.AssertEquals(t, n.ID, "a07eea83-7710-4860-931b-5fe220fae533") -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "router": { - "name": "new_name", - "external_gateway_info": { - "network_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b" - } - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "router": { - "status": "ACTIVE", - "external_gateway_info": { - "network_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b" - }, - "name": "new_name", - "admin_state_up": true, - "tenant_id": "6b96ff0cb17a4b859e1e575d221683d3", - "id": "8604a0de-7f6b-409a-a47c-a1cc7bc77b2e" - } -} - `) - }) - - gwi := GatewayInfo{NetworkID: "8ca37218-28ff-41cb-9b10-039601ea7e6b"} - options := UpdateOpts{Name: "new_name", GatewayInfo: &gwi} - - n, err := Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Name, "new_name") - th.AssertDeepEquals(t, n.GatewayInfo, GatewayInfo{NetworkID: "8ca37218-28ff-41cb-9b10-039601ea7e6b"}) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c") - th.AssertNoErr(t, res.Err) -} - -func TestAddInterface(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers/4e8e5957-649f-477b-9e5b-f1f75b21c03c/add_router_interface", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet_id": "a2f1f29d-571b-4533-907f-5803ab96ead1" -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnet_id": "0d32a837-8069-4ec3-84c4-3eef3e10b188", - "tenant_id": "017d8de156df4177889f31a9bd6edc00", - "port_id": "3f990102-4485-4df1-97a0-2c35bdb85b31", - "id": "9a83fa11-8da5-436e-9afe-3d3ac5ce7770" -} -`) - }) - - opts := InterfaceOpts{SubnetID: "a2f1f29d-571b-4533-907f-5803ab96ead1"} - res, err := AddInterface(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "0d32a837-8069-4ec3-84c4-3eef3e10b188", res.SubnetID) - th.AssertEquals(t, "017d8de156df4177889f31a9bd6edc00", res.TenantID) - th.AssertEquals(t, "3f990102-4485-4df1-97a0-2c35bdb85b31", res.PortID) - th.AssertEquals(t, "9a83fa11-8da5-436e-9afe-3d3ac5ce7770", res.ID) -} - -func TestAddInterfaceRequiredOpts(t *testing.T) { - _, err := AddInterface(fake.ServiceClient(), "foo", InterfaceOpts{}).Extract() - if err == nil { - t.Fatalf("Expected error, got none") - } - _, err = AddInterface(fake.ServiceClient(), "foo", InterfaceOpts{SubnetID: "bar", PortID: "baz"}).Extract() - if err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestRemoveInterface(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/routers/4e8e5957-649f-477b-9e5b-f1f75b21c03c/remove_router_interface", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet_id": "a2f1f29d-571b-4533-907f-5803ab96ead1" -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnet_id": "0d32a837-8069-4ec3-84c4-3eef3e10b188", - "tenant_id": "017d8de156df4177889f31a9bd6edc00", - "port_id": "3f990102-4485-4df1-97a0-2c35bdb85b31", - "id": "9a83fa11-8da5-436e-9afe-3d3ac5ce7770" -} -`) - }) - - opts := InterfaceOpts{SubnetID: "a2f1f29d-571b-4533-907f-5803ab96ead1"} - res, err := RemoveInterface(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "0d32a837-8069-4ec3-84c4-3eef3e10b188", res.SubnetID) - th.AssertEquals(t, "017d8de156df4177889f31a9bd6edc00", res.TenantID) - th.AssertEquals(t, "3f990102-4485-4df1-97a0-2c35bdb85b31", res.PortID) - th.AssertEquals(t, "9a83fa11-8da5-436e-9afe-3d3ac5ce7770", res.ID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests_test.go deleted file mode 100644 index dc1ece321ff..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/members/requests_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package members - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/lb/members", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/members", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "members":[ - { - "status":"ACTIVE", - "weight":1, - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "pool_id":"72741b06-df4d-4715-b142-276b6bce75ab", - "address":"10.0.0.4", - "protocol_port":80, - "id":"701b531b-111a-4f21-ad85-4795b7b12af6" - }, - { - "status":"ACTIVE", - "weight":1, - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "pool_id":"72741b06-df4d-4715-b142-276b6bce75ab", - "address":"10.0.0.3", - "protocol_port":80, - "id":"beb53b4d-230b-4abd-8118-575b8fa006ef" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractMembers(page) - if err != nil { - t.Errorf("Failed to extract members: %v", err) - return false, err - } - - expected := []Member{ - Member{ - Status: "ACTIVE", - Weight: 1, - AdminStateUp: true, - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - PoolID: "72741b06-df4d-4715-b142-276b6bce75ab", - Address: "10.0.0.4", - ProtocolPort: 80, - ID: "701b531b-111a-4f21-ad85-4795b7b12af6", - }, - Member{ - Status: "ACTIVE", - Weight: 1, - AdminStateUp: true, - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - PoolID: "72741b06-df4d-4715-b142-276b6bce75ab", - Address: "10.0.0.3", - ProtocolPort: 80, - ID: "beb53b4d-230b-4abd-8118-575b8fa006ef", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/members", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "member": { - "tenant_id": "453105b9-1754-413f-aab1-55f1af620750", - "pool_id": "foo", - "address": "192.0.2.14", - "protocol_port":8080 - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "member": { - "id": "975592ca-e308-48ad-8298-731935ee9f45", - "address": "192.0.2.14", - "protocol_port": 8080, - "tenant_id": "453105b9-1754-413f-aab1-55f1af620750", - "admin_state_up":true, - "weight": 1, - "status": "DOWN" - } -} - `) - }) - - options := CreateOpts{ - TenantID: "453105b9-1754-413f-aab1-55f1af620750", - Address: "192.0.2.14", - ProtocolPort: 8080, - PoolID: "foo", - } - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/members/975592ca-e308-48ad-8298-731935ee9f45", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "member":{ - "id":"975592ca-e308-48ad-8298-731935ee9f45", - "address":"192.0.2.14", - "protocol_port":8080, - "tenant_id":"453105b9-1754-413f-aab1-55f1af620750", - "admin_state_up":true, - "weight":1, - "status":"DOWN" - } -} - `) - }) - - m, err := Get(fake.ServiceClient(), "975592ca-e308-48ad-8298-731935ee9f45").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "975592ca-e308-48ad-8298-731935ee9f45", m.ID) - th.AssertEquals(t, "192.0.2.14", m.Address) - th.AssertEquals(t, 8080, m.ProtocolPort) - th.AssertEquals(t, "453105b9-1754-413f-aab1-55f1af620750", m.TenantID) - th.AssertEquals(t, true, m.AdminStateUp) - th.AssertEquals(t, 1, m.Weight) - th.AssertEquals(t, "DOWN", m.Status) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/members/332abe93-f488-41ba-870b-2ac66be7f853", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "member":{ - "admin_state_up":false - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "member":{ - "status":"PENDING_UPDATE", - "protocol_port":8080, - "weight":1, - "admin_state_up":false, - "tenant_id":"4fd44f30292945e481c7b8a0c8908869", - "pool_id":"7803631d-f181-4500-b3a2-1b68ba2a75fd", - "address":"10.0.0.5", - "status_description":null, - "id":"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f" - } -} - `) - }) - - options := UpdateOpts{AdminStateUp: false} - - _, err := Update(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853", options).Extract() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/members/332abe93-f488-41ba-870b-2ac66be7f853", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests_test.go deleted file mode 100644 index 79a99bf8a25..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/monitors/requests_test.go +++ /dev/null @@ -1,312 +0,0 @@ -package monitors - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.AssertEquals(t, th.Endpoint()+"v2.0/lb/health_monitors", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/health_monitors", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "health_monitors":[ - { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":10, - "max_retries":1, - "timeout":1, - "type":"PING", - "id":"466c8345-28d8-4f84-a246-e04380b0461d" - }, - { - "admin_state_up":true, - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "delay":5, - "expected_codes":"200", - "max_retries":2, - "http_method":"GET", - "timeout":2, - "url_path":"/", - "type":"HTTP", - "id":"5d4b5228-33b0-4e60-b225-9b727c1a20e7" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractMonitors(page) - if err != nil { - t.Errorf("Failed to extract monitors: %v", err) - return false, err - } - - expected := []Monitor{ - Monitor{ - AdminStateUp: true, - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - Delay: 10, - MaxRetries: 1, - Timeout: 1, - Type: "PING", - ID: "466c8345-28d8-4f84-a246-e04380b0461d", - }, - Monitor{ - AdminStateUp: true, - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - Delay: 5, - ExpectedCodes: "200", - MaxRetries: 2, - Timeout: 2, - URLPath: "/", - Type: "HTTP", - HTTPMethod: "GET", - ID: "5d4b5228-33b0-4e60-b225-9b727c1a20e7", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestDelayMustBeGreaterOrEqualThanTimeout(t *testing.T) { - _, err := Create(fake.ServiceClient(), CreateOpts{ - Type: "HTTP", - Delay: 1, - Timeout: 10, - MaxRetries: 5, - URLPath: "/check", - ExpectedCodes: "200-299", - }).Extract() - - if err == nil { - t.Fatalf("Expected error, got none") - } - - _, err = Update(fake.ServiceClient(), "453105b9-1754-413f-aab1-55f1af620750", UpdateOpts{ - Delay: 1, - Timeout: 10, - }).Extract() - - if err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/health_monitors", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "health_monitor":{ - "type":"HTTP", - "tenant_id":"453105b9-1754-413f-aab1-55f1af620750", - "delay":20, - "timeout":10, - "max_retries":5, - "url_path":"/check", - "expected_codes":"200-299" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "health_monitor":{ - "id":"f3eeab00-8367-4524-b662-55e64d4cacb5", - "tenant_id":"453105b9-1754-413f-aab1-55f1af620750", - "type":"HTTP", - "delay":20, - "timeout":10, - "max_retries":5, - "http_method":"GET", - "url_path":"/check", - "expected_codes":"200-299", - "admin_state_up":true, - "status":"ACTIVE" - } -} - `) - }) - - _, err := Create(fake.ServiceClient(), CreateOpts{ - Type: "HTTP", - TenantID: "453105b9-1754-413f-aab1-55f1af620750", - Delay: 20, - Timeout: 10, - MaxRetries: 5, - URLPath: "/check", - ExpectedCodes: "200-299", - }).Extract() - - th.AssertNoErr(t, err) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Type: TypeHTTP}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/health_monitors/f3eeab00-8367-4524-b662-55e64d4cacb5", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "health_monitor":{ - "id":"f3eeab00-8367-4524-b662-55e64d4cacb5", - "tenant_id":"453105b9-1754-413f-aab1-55f1af620750", - "type":"HTTP", - "delay":20, - "timeout":10, - "max_retries":5, - "http_method":"GET", - "url_path":"/check", - "expected_codes":"200-299", - "admin_state_up":true, - "status":"ACTIVE" - } -} - `) - }) - - hm, err := Get(fake.ServiceClient(), "f3eeab00-8367-4524-b662-55e64d4cacb5").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "f3eeab00-8367-4524-b662-55e64d4cacb5", hm.ID) - th.AssertEquals(t, "453105b9-1754-413f-aab1-55f1af620750", hm.TenantID) - th.AssertEquals(t, "HTTP", hm.Type) - th.AssertEquals(t, 20, hm.Delay) - th.AssertEquals(t, 10, hm.Timeout) - th.AssertEquals(t, 5, hm.MaxRetries) - th.AssertEquals(t, "GET", hm.HTTPMethod) - th.AssertEquals(t, "/check", hm.URLPath) - th.AssertEquals(t, "200-299", hm.ExpectedCodes) - th.AssertEquals(t, true, hm.AdminStateUp) - th.AssertEquals(t, "ACTIVE", hm.Status) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/health_monitors/b05e44b5-81f9-4551-b474-711a722698f7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "health_monitor":{ - "delay": 3, - "timeout": 20, - "max_retries": 10, - "url_path": "/another_check", - "expected_codes": "301" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - - fmt.Fprintf(w, ` -{ - "health_monitor": { - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "delay": 3, - "max_retries": 10, - "http_method": "GET", - "timeout": 20, - "pools": [ - { - "status": "PENDING_CREATE", - "status_description": null, - "pool_id": "6e55751f-6ad4-4e53-b8d4-02e442cd21df" - } - ], - "type": "PING", - "id": "b05e44b5-81f9-4551-b474-711a722698f7" - } -} - `) - }) - - _, err := Update(fake.ServiceClient(), "b05e44b5-81f9-4551-b474-711a722698f7", UpdateOpts{ - Delay: 3, - Timeout: 20, - MaxRetries: 10, - URLPath: "/another_check", - ExpectedCodes: "301", - }).Extract() - - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/health_monitors/b05e44b5-81f9-4551-b474-711a722698f7", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "b05e44b5-81f9-4551-b474-711a722698f7") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests_test.go deleted file mode 100644 index 3b5c7c7105b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/pools/requests_test.go +++ /dev/null @@ -1,318 +0,0 @@ -package pools - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/lb/pools", rootURL(fake.ServiceClient())) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "pools":[ - { - "status":"ACTIVE", - "lb_method":"ROUND_ROBIN", - "protocol":"HTTP", - "description":"", - "health_monitors":[ - "466c8345-28d8-4f84-a246-e04380b0461d", - "5d4b5228-33b0-4e60-b225-9b727c1a20e7" - ], - "members":[ - "701b531b-111a-4f21-ad85-4795b7b12af6", - "beb53b4d-230b-4abd-8118-575b8fa006ef" - ], - "status_description": null, - "id":"72741b06-df4d-4715-b142-276b6bce75ab", - "vip_id":"4ec89087-d057-4e2c-911f-60a3b47ee304", - "name":"app_pool", - "admin_state_up":true, - "subnet_id":"8032909d-47a1-4715-90af-5153ffe39861", - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "health_monitors_status": [], - "provider": "haproxy" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPools(page) - if err != nil { - t.Errorf("Failed to extract pools: %v", err) - return false, err - } - - expected := []Pool{ - Pool{ - Status: "ACTIVE", - LBMethod: "ROUND_ROBIN", - Protocol: "HTTP", - Description: "", - MonitorIDs: []string{ - "466c8345-28d8-4f84-a246-e04380b0461d", - "5d4b5228-33b0-4e60-b225-9b727c1a20e7", - }, - SubnetID: "8032909d-47a1-4715-90af-5153ffe39861", - TenantID: "83657cfcdfe44cd5920adaf26c48ceea", - AdminStateUp: true, - Name: "app_pool", - MemberIDs: []string{ - "701b531b-111a-4f21-ad85-4795b7b12af6", - "beb53b4d-230b-4abd-8118-575b8fa006ef", - }, - ID: "72741b06-df4d-4715-b142-276b6bce75ab", - VIPID: "4ec89087-d057-4e2c-911f-60a3b47ee304", - Provider: "haproxy", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "pool": { - "lb_method": "ROUND_ROBIN", - "protocol": "HTTP", - "name": "Example pool", - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "pool": { - "status": "PENDING_CREATE", - "lb_method": "ROUND_ROBIN", - "protocol": "HTTP", - "description": "", - "health_monitors": [], - "members": [], - "status_description": null, - "id": "69055154-f603-4a28-8951-7cc2d9e54a9a", - "vip_id": null, - "name": "Example pool", - "admin_state_up": true, - "subnet_id": "1981f108-3c48-48d2-b908-30f7d28532c9", - "tenant_id": "2ffc6e22aae24e4795f87155d24c896f", - "health_monitors_status": [] - } -} - `) - }) - - options := CreateOpts{ - LBMethod: LBMethodRoundRobin, - Protocol: "HTTP", - Name: "Example pool", - SubnetID: "1981f108-3c48-48d2-b908-30f7d28532c9", - TenantID: "2ffc6e22aae24e4795f87155d24c896f", - } - p, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "PENDING_CREATE", p.Status) - th.AssertEquals(t, "ROUND_ROBIN", p.LBMethod) - th.AssertEquals(t, "HTTP", p.Protocol) - th.AssertEquals(t, "", p.Description) - th.AssertDeepEquals(t, []string{}, p.MonitorIDs) - th.AssertDeepEquals(t, []string{}, p.MemberIDs) - th.AssertEquals(t, "69055154-f603-4a28-8951-7cc2d9e54a9a", p.ID) - th.AssertEquals(t, "Example pool", p.Name) - th.AssertEquals(t, "1981f108-3c48-48d2-b908-30f7d28532c9", p.SubnetID) - th.AssertEquals(t, "2ffc6e22aae24e4795f87155d24c896f", p.TenantID) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools/332abe93-f488-41ba-870b-2ac66be7f853", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "pool":{ - "id":"332abe93-f488-41ba-870b-2ac66be7f853", - "tenant_id":"19eaa775-cf5d-49bc-902e-2f85f668d995", - "name":"Example pool", - "description":"", - "protocol":"tcp", - "lb_algorithm":"ROUND_ROBIN", - "session_persistence":{ - }, - "healthmonitor_id":null, - "members":[ - ], - "admin_state_up":true, - "status":"ACTIVE" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.ID, "332abe93-f488-41ba-870b-2ac66be7f853") -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools/332abe93-f488-41ba-870b-2ac66be7f853", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "pool":{ - "name":"SuperPool", - "lb_method": "LEAST_CONNECTIONS" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "pool":{ - "status":"PENDING_UPDATE", - "lb_method":"LEAST_CONNECTIONS", - "protocol":"TCP", - "description":"", - "health_monitors":[ - - ], - "subnet_id":"8032909d-47a1-4715-90af-5153ffe39861", - "tenant_id":"83657cfcdfe44cd5920adaf26c48ceea", - "admin_state_up":true, - "name":"SuperPool", - "members":[ - - ], - "id":"61b1f87a-7a21-4ad3-9dda-7f81d249944f", - "vip_id":null - } -} - `) - }) - - options := UpdateOpts{Name: "SuperPool", LBMethod: LBMethodLeastConnections} - - n, err := Update(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "SuperPool", n.Name) - th.AssertDeepEquals(t, "LEAST_CONNECTIONS", n.LBMethod) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools/332abe93-f488-41ba-870b-2ac66be7f853", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853") - th.AssertNoErr(t, res.Err) -} - -func TestAssociateHealthMonitor(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools/332abe93-f488-41ba-870b-2ac66be7f853/health_monitors", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "health_monitor":{ - "id":"b624decf-d5d3-4c66-9a3d-f047e7786181" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{}`) - }) - - _, err := AssociateMonitor(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853", "b624decf-d5d3-4c66-9a3d-f047e7786181").Extract() - th.AssertNoErr(t, err) -} - -func TestDisassociateHealthMonitor(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/pools/332abe93-f488-41ba-870b-2ac66be7f853/health_monitors/b624decf-d5d3-4c66-9a3d-f047e7786181", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := DisassociateMonitor(fake.ServiceClient(), "332abe93-f488-41ba-870b-2ac66be7f853", "b624decf-d5d3-4c66-9a3d-f047e7786181") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests_test.go deleted file mode 100644 index 430f1a1eebf..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/lbaas/vips/requests_test.go +++ /dev/null @@ -1,336 +0,0 @@ -package vips - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/lb/vips", rootURL(fake.ServiceClient())) - th.AssertEquals(t, th.Endpoint()+"v2.0/lb/vips/foo", resourceURL(fake.ServiceClient(), "foo")) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/vips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "vips":[ - { - "id": "db902c0c-d5ff-4753-b465-668ad9656918", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "web_vip", - "description": "lb config for the web tier", - "subnet_id": "96a4386a-f8c3-42ed-afce-d7954eee77b3", - "address" : "10.30.176.47", - "port_id" : "cd1f7a47-4fa6-449c-9ee7-632838aedfea", - "protocol": "HTTP", - "protocol_port": 80, - "pool_id" : "cfc6589d-f949-4c66-99d2-c2da56ef3764", - "admin_state_up": true, - "status": "ACTIVE" - }, - { - "id": "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - "tenant_id": "310df60f-2a10-4ee5-9554-98393092194c", - "name": "db_vip", - "description": "lb config for the db tier", - "subnet_id": "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - "address" : "10.30.176.48", - "port_id" : "cd1f7a47-4fa6-449c-9ee7-632838aedfea", - "protocol": "TCP", - "protocol_port": 3306, - "pool_id" : "41efe233-7591-43c5-9cf7-923964759f9e", - "session_persistence" : {"type" : "SOURCE_IP"}, - "connection_limit" : 2000, - "admin_state_up": true, - "status": "INACTIVE" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVIPs(page) - if err != nil { - t.Errorf("Failed to extract LBs: %v", err) - return false, err - } - - expected := []VirtualIP{ - VirtualIP{ - ID: "db902c0c-d5ff-4753-b465-668ad9656918", - TenantID: "310df60f-2a10-4ee5-9554-98393092194c", - Name: "web_vip", - Description: "lb config for the web tier", - SubnetID: "96a4386a-f8c3-42ed-afce-d7954eee77b3", - Address: "10.30.176.47", - PortID: "cd1f7a47-4fa6-449c-9ee7-632838aedfea", - Protocol: "HTTP", - ProtocolPort: 80, - PoolID: "cfc6589d-f949-4c66-99d2-c2da56ef3764", - Persistence: SessionPersistence{}, - ConnLimit: 0, - AdminStateUp: true, - Status: "ACTIVE", - }, - VirtualIP{ - ID: "36e08a3e-a78f-4b40-a229-1e7e23eee1ab", - TenantID: "310df60f-2a10-4ee5-9554-98393092194c", - Name: "db_vip", - Description: "lb config for the db tier", - SubnetID: "9cedb85d-0759-4898-8a4b-fa5a5ea10086", - Address: "10.30.176.48", - PortID: "cd1f7a47-4fa6-449c-9ee7-632838aedfea", - Protocol: "TCP", - ProtocolPort: 3306, - PoolID: "41efe233-7591-43c5-9cf7-923964759f9e", - Persistence: SessionPersistence{Type: "SOURCE_IP"}, - ConnLimit: 2000, - AdminStateUp: true, - Status: "INACTIVE", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/vips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "vip": { - "protocol": "HTTP", - "name": "NewVip", - "admin_state_up": true, - "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", - "pool_id": "61b1f87a-7a21-4ad3-9dda-7f81d249944f", - "protocol_port": 80, - "session_persistence": {"type": "SOURCE_IP"} - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "vip": { - "status": "PENDING_CREATE", - "protocol": "HTTP", - "description": "", - "admin_state_up": true, - "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", - "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", - "connection_limit": -1, - "pool_id": "61b1f87a-7a21-4ad3-9dda-7f81d249944f", - "address": "10.0.0.11", - "protocol_port": 80, - "port_id": "f7e6fe6a-b8b5-43a8-8215-73456b32e0f5", - "id": "c987d2be-9a3c-4ac9-a046-e8716b1350e2", - "name": "NewVip" - } -} - `) - }) - - opts := CreateOpts{ - Protocol: "HTTP", - Name: "NewVip", - AdminStateUp: Up, - SubnetID: "8032909d-47a1-4715-90af-5153ffe39861", - PoolID: "61b1f87a-7a21-4ad3-9dda-7f81d249944f", - ProtocolPort: 80, - Persistence: &SessionPersistence{Type: "SOURCE_IP"}, - } - - r, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "PENDING_CREATE", r.Status) - th.AssertEquals(t, "HTTP", r.Protocol) - th.AssertEquals(t, "", r.Description) - th.AssertEquals(t, true, r.AdminStateUp) - th.AssertEquals(t, "8032909d-47a1-4715-90af-5153ffe39861", r.SubnetID) - th.AssertEquals(t, "83657cfcdfe44cd5920adaf26c48ceea", r.TenantID) - th.AssertEquals(t, -1, r.ConnLimit) - th.AssertEquals(t, "61b1f87a-7a21-4ad3-9dda-7f81d249944f", r.PoolID) - th.AssertEquals(t, "10.0.0.11", r.Address) - th.AssertEquals(t, 80, r.ProtocolPort) - th.AssertEquals(t, "f7e6fe6a-b8b5-43a8-8215-73456b32e0f5", r.PortID) - th.AssertEquals(t, "c987d2be-9a3c-4ac9-a046-e8716b1350e2", r.ID) - th.AssertEquals(t, "NewVip", r.Name) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Name: "foo"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Name: "foo", SubnetID: "bar"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Name: "foo", SubnetID: "bar", Protocol: "bar"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Name: "foo", SubnetID: "bar", Protocol: "bar", ProtocolPort: 80}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/vips/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "vip": { - "status": "ACTIVE", - "protocol": "HTTP", - "description": "", - "admin_state_up": true, - "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", - "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", - "connection_limit": 1000, - "pool_id": "72741b06-df4d-4715-b142-276b6bce75ab", - "session_persistence": { - "cookie_name": "MyAppCookie", - "type": "APP_COOKIE" - }, - "address": "10.0.0.10", - "protocol_port": 80, - "port_id": "b5a743d6-056b-468b-862d-fb13a9aa694e", - "id": "4ec89087-d057-4e2c-911f-60a3b47ee304", - "name": "my-vip" - } -} - `) - }) - - vip, err := Get(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "ACTIVE", vip.Status) - th.AssertEquals(t, "HTTP", vip.Protocol) - th.AssertEquals(t, "", vip.Description) - th.AssertEquals(t, true, vip.AdminStateUp) - th.AssertEquals(t, 1000, vip.ConnLimit) - th.AssertEquals(t, SessionPersistence{Type: "APP_COOKIE", CookieName: "MyAppCookie"}, vip.Persistence) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/vips/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "vip": { - "connection_limit": 1000, - "session_persistence": {"type": "SOURCE_IP"} - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusAccepted) - - fmt.Fprintf(w, ` -{ - "vip": { - "status": "PENDING_UPDATE", - "protocol": "HTTP", - "description": "", - "admin_state_up": true, - "subnet_id": "8032909d-47a1-4715-90af-5153ffe39861", - "tenant_id": "83657cfcdfe44cd5920adaf26c48ceea", - "connection_limit": 1000, - "pool_id": "61b1f87a-7a21-4ad3-9dda-7f81d249944f", - "address": "10.0.0.11", - "protocol_port": 80, - "port_id": "f7e6fe6a-b8b5-43a8-8215-73456b32e0f5", - "id": "c987d2be-9a3c-4ac9-a046-e8716b1350e2", - "name": "NewVip" - } -} - `) - }) - - i1000 := 1000 - options := UpdateOpts{ - ConnLimit: &i1000, - Persistence: &SessionPersistence{Type: "SOURCE_IP"}, - } - vip, err := Update(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "PENDING_UPDATE", vip.Status) - th.AssertEquals(t, 1000, vip.ConnLimit) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/lb/vips/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/provider/results_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/provider/results_test.go deleted file mode 100644 index 80816926da6..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/provider/results_test.go +++ /dev/null @@ -1,253 +0,0 @@ -package provider - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "networks": [ - { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "provider:segmentation_id": null, - "provider:physical_network": null, - "provider:network_type": "local" - }, - { - "status": "ACTIVE", - "subnets": [ - "08eae331-0402-425a-923c-34f7cfe39c1b" - ], - "name": "private", - "admin_state_up": true, - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "shared": true, - "id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - "provider:segmentation_id": 1234567890, - "provider:physical_network": null, - "provider:network_type": "local" - } - ] -} - `) - }) - - count := 0 - - networks.List(fake.ServiceClient(), networks.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractList(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []NetworkExtAttrs{ - NetworkExtAttrs{ - Status: "ACTIVE", - Subnets: []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"}, - Name: "private-network", - AdminStateUp: true, - TenantID: "4fd44f30292945e481c7b8a0c8908869", - Shared: true, - ID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - NetworkType: "local", - PhysicalNetwork: "", - SegmentationID: "", - }, - NetworkExtAttrs{ - Status: "ACTIVE", - Subnets: []string{"08eae331-0402-425a-923c-34f7cfe39c1b"}, - Name: "private", - AdminStateUp: true, - TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e", - Shared: true, - ID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - NetworkType: "local", - PhysicalNetwork: "", - SegmentationID: "1234567890", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "provider:physical_network": null, - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "provider:network_type": "local", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "provider:segmentation_id": null - } -} - `) - }) - - res := networks.Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - n, err := ExtractGet(res) - - th.AssertNoErr(t, err) - - th.AssertEquals(t, "", n.PhysicalNetwork) - th.AssertEquals(t, "local", n.NetworkType) - th.AssertEquals(t, "", n.SegmentationID) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "provider:physical_network": null, - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "provider:network_type": "local", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "provider:segmentation_id": null - } -} - `) - }) - - options := networks.CreateOpts{Name: "sample_network", AdminStateUp: Up} - res := networks.Create(fake.ServiceClient(), options) - n, err := ExtractCreate(res) - - th.AssertNoErr(t, err) - - th.AssertEquals(t, "", n.PhysicalNetwork) - th.AssertEquals(t, "local", n.NetworkType) - th.AssertEquals(t, "", n.SegmentationID) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "new_network_name", - "admin_state_up": false, - "shared": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "provider:physical_network": null, - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "provider:network_type": "local", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "provider:segmentation_id": null - } -} - `) - }) - - iTrue := true - options := networks.UpdateOpts{Name: "new_network_name", AdminStateUp: Down, Shared: &iTrue} - res := networks.Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options) - n, err := ExtractUpdate(res) - - th.AssertNoErr(t, err) - - th.AssertEquals(t, "", n.PhysicalNetwork) - th.AssertEquals(t, "local", n.NetworkType) - th.AssertEquals(t, "", n.SegmentationID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests_test.go deleted file mode 100644 index 5f074c72f39..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups/requests_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package groups - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/security-groups", rootURL(fake.ServiceClient())) - th.AssertEquals(t, th.Endpoint()+"v2.0/security-groups/foo", resourceURL(fake.ServiceClient(), "foo")) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_groups": [ - { - "description": "default", - "id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "name": "default", - "security_group_rules": [], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractGroups(page) - if err != nil { - t.Errorf("Failed to extract secgroups: %v", err) - return false, err - } - - expected := []SecGroup{ - SecGroup{ - Description: "default", - ID: "85cc3048-abc3-43cc-89b3-377341426ac5", - Name: "default", - Rules: []rules.SecGroupRule{}, - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "security_group": { - "name": "new-webservers", - "description": "security group for webservers" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "security_group": { - "description": "security group for webservers", - "id": "2076db17-a522-4506-91de-c6dd8e837028", - "name": "new-webservers", - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv4", - "id": "38ce2d8e-e8f1-48bd-83c2-d33cb9f50c3d", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "2076db17-a522-4506-91de-c6dd8e837028", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv6", - "id": "565b9502-12de-4ffd-91e9-68885cff6ae1", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "2076db17-a522-4506-91de-c6dd8e837028", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } -} - `) - }) - - opts := CreateOpts{Name: "new-webservers", Description: "security group for webservers"} - _, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups/85cc3048-abc3-43cc-89b3-377341426ac5", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group": { - "description": "default", - "id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "name": "default", - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv4", - "id": "93aa42e5-80db-4581-9391-3a608bd0e448", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } -} - `) - }) - - sg, err := Get(fake.ServiceClient(), "85cc3048-abc3-43cc-89b3-377341426ac5").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "default", sg.Description) - th.AssertEquals(t, "85cc3048-abc3-43cc-89b3-377341426ac5", sg.ID) - th.AssertEquals(t, "default", sg.Name) - th.AssertEquals(t, 2, len(sg.Rules)) - th.AssertEquals(t, "e4f50856753b4dc6afee5fa6b9b6c550", sg.TenantID) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests_test.go deleted file mode 100644 index b5afef31ed8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules/requests_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package rules - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestURLs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.AssertEquals(t, th.Endpoint()+"v2.0/security-group-rules", rootURL(fake.ServiceClient())) - th.AssertEquals(t, th.Endpoint()+"v2.0/security-group-rules/foo", resourceURL(fake.ServiceClient(), "foo")) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv4", - "id": "93aa42e5-80db-4581-9391-3a608bd0e448", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract secrules: %v", err) - return false, err - } - - expected := []SecGroupRule{ - SecGroupRule{ - Direction: "egress", - EtherType: "IPv6", - ID: "3c0e45ff-adaf-4124-b083-bf390e5482ff", - PortRangeMax: 0, - PortRangeMin: 0, - Protocol: "", - RemoteGroupID: "", - RemoteIPPrefix: "", - SecGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - SecGroupRule{ - Direction: "egress", - EtherType: "IPv4", - ID: "93aa42e5-80db-4581-9391-3a608bd0e448", - PortRangeMax: 0, - PortRangeMin: 0, - Protocol: "", - RemoteGroupID: "", - RemoteIPPrefix: "", - SecGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "security_group_rule": { - "direction": "ingress", - "port_range_min": 80, - "ethertype": "IPv4", - "port_range_max": 80, - "protocol": "tcp", - "remote_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "security_group_id": "a7734e61-b545-452d-a3cd-0189cbd9747a" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "security_group_rule": { - "direction": "ingress", - "ethertype": "IPv4", - "id": "2bc0accf-312e-429a-956e-e4407625eb62", - "port_range_max": 80, - "port_range_min": 80, - "protocol": "tcp", - "remote_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "remote_ip_prefix": null, - "security_group_id": "a7734e61-b545-452d-a3cd-0189cbd9747a", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } -} - `) - }) - - opts := CreateOpts{ - Direction: "ingress", - PortRangeMin: 80, - EtherType: "IPv4", - PortRangeMax: 80, - Protocol: "tcp", - RemoteGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - SecGroupID: "a7734e61-b545-452d-a3cd-0189cbd9747a", - } - _, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), CreateOpts{Direction: "something"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Direction: DirIngress, EtherType: "something"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Direction: DirIngress, EtherType: Ether4}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), CreateOpts{Direction: DirIngress, EtherType: Ether4, SecGroupID: "something", Protocol: "foo"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules/3c0e45ff-adaf-4124-b083-bf390e5482ff", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "security_group_rule": { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } -} - `) - }) - - sr, err := Get(fake.ServiceClient(), "3c0e45ff-adaf-4124-b083-bf390e5482ff").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "egress", sr.Direction) - th.AssertEquals(t, "IPv6", sr.EtherType) - th.AssertEquals(t, "3c0e45ff-adaf-4124-b083-bf390e5482ff", sr.ID) - th.AssertEquals(t, 0, sr.PortRangeMax) - th.AssertEquals(t, 0, sr.PortRangeMin) - th.AssertEquals(t, "", sr.Protocol) - th.AssertEquals(t, "", sr.RemoteGroupID) - th.AssertEquals(t, "", sr.RemoteIPPrefix) - th.AssertEquals(t, "85cc3048-abc3-43cc-89b3-377341426ac5", sr.SecGroupID) - th.AssertEquals(t, "e4f50856753b4dc6afee5fa6b9b6c550", sr.TenantID) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests_test.go deleted file mode 100644 index 81eb79cb541..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/requests_test.go +++ /dev/null @@ -1,276 +0,0 @@ -package networks - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "networks": [ - { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - }, - { - "status": "ACTIVE", - "subnets": [ - "08eae331-0402-425a-923c-34f7cfe39c1b" - ], - "name": "private", - "admin_state_up": true, - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "shared": true, - "id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324" - } - ] -} - `) - }) - - client := fake.ServiceClient() - count := 0 - - List(client, ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNetworks(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []Network{ - Network{ - Status: "ACTIVE", - Subnets: []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"}, - Name: "private-network", - AdminStateUp: true, - TenantID: "4fd44f30292945e481c7b8a0c8908869", - Shared: true, - ID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - }, - Network{ - Status: "ACTIVE", - Subnets: []string{"08eae331-0402-425a-923c-34f7cfe39c1b"}, - Name: "private", - AdminStateUp: true, - TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e", - Shared: true, - ID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"}) - th.AssertEquals(t, n.Name, "private-network") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertEquals(t, n.Shared, true) - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [], - "name": "net1", - "admin_state_up": true, - "tenant_id": "9bacb3c5d39d41a79512987f338cf177", - "shared": false, - "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c" - } -} - `) - }) - - iTrue := true - options := CreateOpts{Name: "sample_network", AdminStateUp: &iTrue} - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{}) - th.AssertEquals(t, n.Name, "net1") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.TenantID, "9bacb3c5d39d41a79512987f338cf177") - th.AssertEquals(t, n.Shared, false) - th.AssertEquals(t, n.ID, "4e8e5957-649f-477b-9e5b-f1f75b21c03c") -} - -func TestCreateWithOptionalFields(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true, - "shared": true, - "tenant_id": "12345" - } -} - `) - - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, `{}`) - }) - - iTrue := true - options := CreateOpts{Name: "sample_network", AdminStateUp: &iTrue, Shared: &iTrue, TenantID: "12345"} - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "new_network_name", - "admin_state_up": false, - "shared": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [], - "name": "new_network_name", - "admin_state_up": false, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c" - } -} - `) - }) - - iTrue, iFalse := true, false - options := UpdateOpts{Name: "new_network_name", AdminStateUp: &iFalse, Shared: &iTrue} - n, err := Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Name, "new_network_name") - th.AssertEquals(t, n.AdminStateUp, false) - th.AssertEquals(t, n.Shared, true) - th.AssertEquals(t, n.ID, "4e8e5957-649f-477b-9e5b-f1f75b21c03c") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls_test.go deleted file mode 100644 index caf77dbe041..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/networks/urls_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package networks - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint, ResourceBase: endpoint + "v2.0/"} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "v2.0/networks/foo" - th.AssertEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "v2.0/networks" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "v2.0/networks" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "v2.0/networks/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests_test.go deleted file mode 100644 index 9e323efa3a9..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/requests_test.go +++ /dev/null @@ -1,321 +0,0 @@ -package ports - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/ports", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "ports": [ - { - "status": "ACTIVE", - "binding:host_id": "devstack", - "name": "", - "admin_state_up": true, - "network_id": "70c1db1f-b701-45bd-96e0-a313ee3430b3", - "tenant_id": "", - "device_owner": "network:router_gateway", - "mac_address": "fa:16:3e:58:42:ed", - "fixed_ips": [ - { - "subnet_id": "008ba151-0b8c-4a67-98b5-0d2b87666062", - "ip_address": "172.24.4.2" - } - ], - "id": "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b", - "security_groups": [], - "device_id": "9ae135f4-b6e0-4dad-9e91-3c223e385824" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPorts(page) - if err != nil { - t.Errorf("Failed to extract subnets: %v", err) - return false, nil - } - - expected := []Port{ - Port{ - Status: "ACTIVE", - Name: "", - AdminStateUp: true, - NetworkID: "70c1db1f-b701-45bd-96e0-a313ee3430b3", - TenantID: "", - DeviceOwner: "network:router_gateway", - MACAddress: "fa:16:3e:58:42:ed", - FixedIPs: []IP{ - IP{ - SubnetID: "008ba151-0b8c-4a67-98b5-0d2b87666062", - IPAddress: "172.24.4.2", - }, - }, - ID: "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b", - SecurityGroups: []string{}, - DeviceID: "9ae135f4-b6e0-4dad-9e91-3c223e385824", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/ports/46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "ACTIVE", - "name": "", - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "7e02058126cc4950b75f9970368ba177", - "device_owner": "network:router_interface", - "mac_address": "fa:16:3e:23:fd:d7", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.1" - } - ], - "id": "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2", - "security_groups": [], - "device_id": "5e3898d7-11be-483e-9732-b2f5eccd2b2e" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertEquals(t, n.Name, "") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.NetworkID, "a87cc70a-3e15-4acf-8205-9b711a3531b7") - th.AssertEquals(t, n.TenantID, "7e02058126cc4950b75f9970368ba177") - th.AssertEquals(t, n.DeviceOwner, "network:router_interface") - th.AssertEquals(t, n.MACAddress, "fa:16:3e:23:fd:d7") - th.AssertDeepEquals(t, n.FixedIPs, []IP{ - IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.1"}, - }) - th.AssertEquals(t, n.ID, "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2") - th.AssertDeepEquals(t, n.SecurityGroups, []string{}) - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertEquals(t, n.DeviceID, "5e3898d7-11be-483e-9732-b2f5eccd2b2e") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/ports", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "port": { - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "name": "private-port", - "admin_state_up": true, - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.2" - } - ], - "security_groups": ["foo"] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "DOWN", - "name": "private-port", - "allowed_address_pairs": [], - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "d6700c0c9ffa4f1cb322cd4a1f3906fa", - "device_owner": "", - "mac_address": "fa:16:3e:c9:cb:f0", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.2" - } - ], - "id": "65c0ee9f-d634-4522-8954-51021b570b0d", - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ], - "device_id": "" - } -} - `) - }) - - asu := true - options := CreateOpts{ - Name: "private-port", - AdminStateUp: &asu, - NetworkID: "a87cc70a-3e15-4acf-8205-9b711a3531b7", - FixedIPs: []IP{ - IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.2"}, - }, - SecurityGroups: []string{"foo"}, - } - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "DOWN") - th.AssertEquals(t, n.Name, "private-port") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.NetworkID, "a87cc70a-3e15-4acf-8205-9b711a3531b7") - th.AssertEquals(t, n.TenantID, "d6700c0c9ffa4f1cb322cd4a1f3906fa") - th.AssertEquals(t, n.DeviceOwner, "") - th.AssertEquals(t, n.MACAddress, "fa:16:3e:c9:cb:f0") - th.AssertDeepEquals(t, n.FixedIPs, []IP{ - IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.2"}, - }) - th.AssertEquals(t, n.ID, "65c0ee9f-d634-4522-8954-51021b570b0d") - th.AssertDeepEquals(t, n.SecurityGroups, []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/ports/65c0ee9f-d634-4522-8954-51021b570b0d", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "port": { - "name": "new_port_name", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.3" - } - ], - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "DOWN", - "name": "new_port_name", - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "d6700c0c9ffa4f1cb322cd4a1f3906fa", - "device_owner": "", - "mac_address": "fa:16:3e:c9:cb:f0", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.3" - } - ], - "id": "65c0ee9f-d634-4522-8954-51021b570b0d", - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ], - "device_id": "" - } -} - `) - }) - - options := UpdateOpts{ - Name: "new_port_name", - FixedIPs: []IP{ - IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.3"}, - }, - SecurityGroups: []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}, - } - - s, err := Update(fake.ServiceClient(), "65c0ee9f-d634-4522-8954-51021b570b0d", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "new_port_name") - th.AssertDeepEquals(t, s.FixedIPs, []IP{ - IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.3"}, - }) - th.AssertDeepEquals(t, s.SecurityGroups, []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/ports/65c0ee9f-d634-4522-8954-51021b570b0d", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "65c0ee9f-d634-4522-8954-51021b570b0d") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls_test.go deleted file mode 100644 index 7fadd4dcb70..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/ports/urls_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package ports - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint, ResourceBase: endpoint + "v2.0/"} -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "v2.0/ports" - th.AssertEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "v2.0/ports/foo" - th.AssertEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "v2.0/ports" - th.AssertEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "v2.0/ports/foo" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "v2.0/ports/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests_test.go deleted file mode 100644 index 987064ada64..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/requests_test.go +++ /dev/null @@ -1,362 +0,0 @@ -package subnets - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/subnets", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnets": [ - { - "name": "private-subnet", - "enable_dhcp": true, - "network_id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "10.0.0.2", - "end": "10.0.0.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "10.0.0.1", - "cidr": "10.0.0.0/24", - "id": "08eae331-0402-425a-923c-34f7cfe39c1b" - }, - { - "name": "my_subnet", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.0.0.2", - "end": "192.255.255.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.0.0.1", - "cidr": "192.0.0.0/8", - "id": "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractSubnets(page) - if err != nil { - t.Errorf("Failed to extract subnets: %v", err) - return false, nil - } - - expected := []Subnet{ - Subnet{ - Name: "private-subnet", - EnableDHCP: true, - NetworkID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e", - DNSNameservers: []string{}, - AllocationPools: []AllocationPool{ - AllocationPool{ - Start: "10.0.0.2", - End: "10.0.0.254", - }, - }, - HostRoutes: []HostRoute{}, - IPVersion: 4, - GatewayIP: "10.0.0.1", - CIDR: "10.0.0.0/24", - ID: "08eae331-0402-425a-923c-34f7cfe39c1b", - }, - Subnet{ - Name: "my_subnet", - EnableDHCP: true, - NetworkID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - TenantID: "4fd44f30292945e481c7b8a0c8908869", - DNSNameservers: []string{}, - AllocationPools: []AllocationPool{ - AllocationPool{ - Start: "192.0.0.2", - End: "192.255.255.254", - }, - }, - HostRoutes: []HostRoute{}, - IPVersion: 4, - GatewayIP: "192.0.0.1", - CIDR: "192.0.0.0/8", - ID: "54d6f61d-db07-451c-9ab3-b9609b6b6f0b", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/subnets/54d6f61d-db07-451c-9ab3-b9609b6b6f0b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "my_subnet", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.0.0.2", - "end": "192.255.255.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.0.0.1", - "cidr": "192.0.0.0/8", - "id": "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - } -} - `) - }) - - s, err := Get(fake.ServiceClient(), "54d6f61d-db07-451c-9ab3-b9609b6b6f0b").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "my_subnet") - th.AssertEquals(t, s.EnableDHCP, true) - th.AssertEquals(t, s.NetworkID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertEquals(t, s.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertDeepEquals(t, s.DNSNameservers, []string{}) - th.AssertDeepEquals(t, s.AllocationPools, []AllocationPool{ - AllocationPool{ - Start: "192.0.0.2", - End: "192.255.255.254", - }, - }) - th.AssertDeepEquals(t, s.HostRoutes, []HostRoute{}) - th.AssertEquals(t, s.IPVersion, 4) - th.AssertEquals(t, s.GatewayIP, "192.0.0.1") - th.AssertEquals(t, s.CIDR, "192.0.0.0/8") - th.AssertEquals(t, s.ID, "54d6f61d-db07-451c-9ab3-b9609b6b6f0b") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/subnets", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet": { - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "ip_version": 4, - "cidr": "192.168.199.0/24", - "dns_nameservers": ["foo"], - "allocation_pools": [ - { - "start": "192.168.199.2", - "end": "192.168.199.254" - } - ], - "host_routes": [{"destination":"","nexthop": "bar"}] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.168.199.2", - "end": "192.168.199.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.168.199.1", - "cidr": "192.168.199.0/24", - "id": "3b80198d-4f7b-4f77-9ef5-774d54e17126" - } -} - `) - }) - - opts := CreateOpts{ - NetworkID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - IPVersion: 4, - CIDR: "192.168.199.0/24", - AllocationPools: []AllocationPool{ - AllocationPool{ - Start: "192.168.199.2", - End: "192.168.199.254", - }, - }, - DNSNameservers: []string{"foo"}, - HostRoutes: []HostRoute{ - HostRoute{NextHop: "bar"}, - }, - } - s, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "") - th.AssertEquals(t, s.EnableDHCP, true) - th.AssertEquals(t, s.NetworkID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertEquals(t, s.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertDeepEquals(t, s.DNSNameservers, []string{}) - th.AssertDeepEquals(t, s.AllocationPools, []AllocationPool{ - AllocationPool{ - Start: "192.168.199.2", - End: "192.168.199.254", - }, - }) - th.AssertDeepEquals(t, s.HostRoutes, []HostRoute{}) - th.AssertEquals(t, s.IPVersion, 4) - th.AssertEquals(t, s.GatewayIP, "192.168.199.1") - th.AssertEquals(t, s.CIDR, "192.168.199.0/24") - th.AssertEquals(t, s.ID, "3b80198d-4f7b-4f77-9ef5-774d54e17126") -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - - res = Create(fake.ServiceClient(), CreateOpts{NetworkID: "foo"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - - res = Create(fake.ServiceClient(), CreateOpts{NetworkID: "foo", CIDR: "bar", IPVersion: 40}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/subnets/08eae331-0402-425a-923c-34f7cfe39c1b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet": { - "name": "my_new_subnet", - "dns_nameservers": ["foo"], - "host_routes": [{"destination":"","nexthop": "bar"}] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "my_new_subnet", - "enable_dhcp": true, - "network_id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "10.0.0.2", - "end": "10.0.0.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "10.0.0.1", - "cidr": "10.0.0.0/24", - "id": "08eae331-0402-425a-923c-34f7cfe39c1b" - } -} - `) - }) - - opts := UpdateOpts{ - Name: "my_new_subnet", - DNSNameservers: []string{"foo"}, - HostRoutes: []HostRoute{ - HostRoute{NextHop: "bar"}, - }, - } - s, err := Update(fake.ServiceClient(), "08eae331-0402-425a-923c-34f7cfe39c1b", opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "my_new_subnet") - th.AssertEquals(t, s.ID, "08eae331-0402-425a-923c-34f7cfe39c1b") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/subnets/08eae331-0402-425a-923c-34f7cfe39c1b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "08eae331-0402-425a-923c-34f7cfe39c1b") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results_test.go deleted file mode 100644 index d4048388cdb..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/results_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package subnets - -import ( - "encoding/json" - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" - "testing" -) - -func TestHostRoute(t *testing.T) { - sejson := []byte(` - {"subnet": { - "name": "test-subnet", - "enable_dhcp": false, - "network_id": "3e66c41e-cbbd-4019-9aab-740b7e4150a0", - "tenant_id": "f86e123198cf42d19c8854c5f80c2f06", - "dns_nameservers": [], - "gateway_ip": "172.16.0.1", - "ipv6_ra_mode": null, - "allocation_pools": [ - { - "start": "172.16.0.2", - "end": "172.16.255.254" - } - ], - "host_routes": [ - { - "destination": "172.20.1.0/24", - "nexthop": "172.16.0.2" - } - ], - "ip_version": 4, - "ipv6_address_mode": null, - "cidr": "172.16.0.0/16", - "id": "6dcaa873-7115-41af-9ef5-915f73636e43", - "subnetpool_id": null - }} -`) - - var dejson interface{} - err := json.Unmarshal(sejson, &dejson) - if err != nil { - t.Fatalf("%s", err) - } - - resp := commonResult{gophercloud.Result{Body: dejson}} - subnet, err := resp.Extract() - if err != nil { - t.Fatalf("%s", err) - } - route := subnet.HostRoutes[0] - th.AssertEquals(t, route.NextHop, "172.16.0.2") - th.AssertEquals(t, route.DestinationCIDR, "172.20.1.0/24") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls_test.go deleted file mode 100644 index aeeddf35495..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/networking/v2/subnets/urls_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package subnets - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint, ResourceBase: endpoint + "v2.0/"} -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint + "v2.0/subnets" - th.AssertEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "v2.0/subnets/foo" - th.AssertEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "v2.0/subnets" - th.AssertEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "v2.0/subnets/foo" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "v2.0/subnets/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests_test.go deleted file mode 100644 index 6454c0ac4ca..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/requests_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package accounts - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestUpdateAccount(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleUpdateAccountSuccessfully(t) - - options := &UpdateOpts{Metadata: map[string]string{"gophercloud-test": "accounts"}} - res := Update(fake.ServiceClient(), options) - th.AssertNoErr(t, res.Err) -} - -func TestGetAccount(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetAccountSuccessfully(t) - - expectedMetadata := map[string]string{"Subject": "books"} - res := Get(fake.ServiceClient(), &GetOpts{}) - th.AssertNoErr(t, res.Err) - actualMetadata, _ := res.ExtractMetadata() - th.CheckDeepEquals(t, expectedMetadata, actualMetadata) - //headers, err := res.Extract() - //th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls_test.go deleted file mode 100644 index 074d52dfd5c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package accounts - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient()) - expected := endpoint - th.CheckEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient()) - expected := endpoint - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests_test.go deleted file mode 100644 index 0ccd5a77868..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/requests_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package containers - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -var metadata = map[string]string{"gophercloud-test": "containers"} - -func TestListContainerInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListContainerInfoSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), &ListOpts{Full: true}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractInfo(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ExpectedListInfo, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListAllContainerInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListContainerInfoSuccessfully(t) - - allPages, err := List(fake.ServiceClient(), &ListOpts{Full: true}).AllPages() - th.AssertNoErr(t, err) - actual, err := ExtractInfo(allPages) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedListInfo, actual) -} - -func TestListContainerNames(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListContainerNamesSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), &ListOpts{Full: false}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNames(page) - if err != nil { - t.Errorf("Failed to extract container names: %v", err) - return false, err - } - - th.CheckDeepEquals(t, ExpectedListNames, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListAllContainerNames(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListContainerNamesSuccessfully(t) - - allPages, err := List(fake.ServiceClient(), &ListOpts{Full: false}).AllPages() - th.AssertNoErr(t, err) - actual, err := ExtractNames(allPages) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedListNames, actual) -} - -func TestCreateContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateContainerSuccessfully(t) - - options := CreateOpts{ContentType: "application/json", Metadata: map[string]string{"foo": "bar"}} - res := Create(fake.ServiceClient(), "testContainer", options) - c, err := res.Extract() - th.CheckNoErr(t, err) - th.CheckEquals(t, "bar", res.Header["X-Container-Meta-Foo"][0]) - th.CheckEquals(t, "1234567", c.TransID) -} - -func TestDeleteContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteContainerSuccessfully(t) - - res := Delete(fake.ServiceClient(), "testContainer") - th.CheckNoErr(t, res.Err) -} - -func TestUpateContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleUpdateContainerSuccessfully(t) - - options := &UpdateOpts{Metadata: map[string]string{"foo": "bar"}} - res := Update(fake.ServiceClient(), "testContainer", options) - th.CheckNoErr(t, res.Err) -} - -func TestGetContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetContainerSuccessfully(t) - - _, err := Get(fake.ServiceClient(), "testContainer").ExtractMetadata() - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls_test.go deleted file mode 100644 index d043a2aae50..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers/urls_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package containers - -import ( - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" - "testing" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient()) - expected := endpoint - th.CheckEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests_test.go deleted file mode 100644 index f7d6822913e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/requests_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package objects - -import ( - "bytes" - "fmt" - "io" - "net/http" - "strings" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestDownloadReader(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDownloadObjectSuccessfully(t) - - response := Download(fake.ServiceClient(), "testContainer", "testObject", nil) - defer response.Body.Close() - - // Check reader - buf := bytes.NewBuffer(make([]byte, 0)) - io.CopyN(buf, response.Body, 10) - th.CheckEquals(t, "Successful", string(buf.Bytes())) -} - -func TestDownloadExtraction(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDownloadObjectSuccessfully(t) - - response := Download(fake.ServiceClient(), "testContainer", "testObject", nil) - - // Check []byte extraction - bytes, err := response.ExtractContent() - th.AssertNoErr(t, err) - th.CheckEquals(t, "Successful download with Gophercloud", string(bytes)) -} - -func TestListObjectInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListObjectsInfoSuccessfully(t) - - count := 0 - options := &ListOpts{Full: true} - err := List(fake.ServiceClient(), "testContainer", options).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractInfo(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ExpectedListInfo, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListObjectNames(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListObjectNamesSuccessfully(t) - - count := 0 - options := &ListOpts{Full: false} - err := List(fake.ServiceClient(), "testContainer", options).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNames(page) - if err != nil { - t.Errorf("Failed to extract container names: %v", err) - return false, err - } - - th.CheckDeepEquals(t, ExpectedListNames, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestCreateObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - content := "Did gyre and gimble in the wabe" - - HandleCreateTextObjectSuccessfully(t, content) - - options := &CreateOpts{ContentType: "text/plain"} - res := Create(fake.ServiceClient(), "testContainer", "testObject", strings.NewReader(content), options) - th.AssertNoErr(t, res.Err) -} - -func TestCreateObjectWithoutContentType(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - content := "The sky was the color of television, tuned to a dead channel." - - HandleCreateTypelessObjectSuccessfully(t, content) - - res := Create(fake.ServiceClient(), "testContainer", "testObject", strings.NewReader(content), &CreateOpts{}) - th.AssertNoErr(t, res.Err) -} - -func TestErrorIsRaisedForChecksumMismatch(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/testContainer/testObject", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("ETag", "acbd18db4cc2f85cedef654fccc4a4d8") - w.WriteHeader(http.StatusCreated) - }) - - content := strings.NewReader("The sky was the color of television, tuned to a dead channel.") - res := Create(fake.ServiceClient(), "testContainer", "testObject", content, &CreateOpts{}) - - err := fmt.Errorf("Local checksum does not match API ETag header") - th.AssertDeepEquals(t, err, res.Err) -} - -func TestCopyObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCopyObjectSuccessfully(t) - - options := &CopyOpts{Destination: "/newTestContainer/newTestObject"} - res := Copy(fake.ServiceClient(), "testContainer", "testObject", options) - th.AssertNoErr(t, res.Err) -} - -func TestDeleteObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteObjectSuccessfully(t) - - res := Delete(fake.ServiceClient(), "testContainer", "testObject", nil) - th.AssertNoErr(t, res.Err) -} - -func TestUpateObjectMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleUpdateObjectSuccessfully(t) - - options := &UpdateOpts{Metadata: map[string]string{"Gophercloud-Test": "objects"}} - res := Update(fake.ServiceClient(), "testContainer", "testObject", options) - th.AssertNoErr(t, res.Err) -} - -func TestGetObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetObjectSuccessfully(t) - - expected := map[string]string{"Gophercloud-Test": "objects"} - actual, err := Get(fake.ServiceClient(), "testContainer", "testObject", nil).ExtractMetadata() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls_test.go deleted file mode 100644 index 1dcfe3543c7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects/urls_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package objects - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestListURL(t *testing.T) { - actual := listURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} - -func TestCopyURL(t *testing.T) { - actual := copyURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} - -func TestDownloadURL(t *testing.T) { - actual := downloadURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo", "bar") - expected := endpoint + "foo/bar" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/apiversions/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/apiversions/requests_test.go deleted file mode 100644 index a2fc980d358..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/apiversions/requests_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package apiversions - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListVersions(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "versions": [ - { - "status": "CURRENT", - "id": "v1.0", - "links": [ - { - "href": "http://23.253.228.211:8000/v1", - "rel": "self" - } - ] - } - ] -}`) - }) - - count := 0 - - ListVersions(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractAPIVersions(page) - if err != nil { - t.Errorf("Failed to extract API versions: %v", err) - return false, err - } - - expected := []APIVersion{ - APIVersion{ - Status: "CURRENT", - ID: "v1.0", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "http://23.253.228.211:8000/v1", - Rel: "self", - }, - }, - }, - } - - th.AssertDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestNonJSONCannotBeExtractedIntoAPIVersions(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - - ListVersions(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - if _, err := ExtractAPIVersions(page); err == nil { - t.Fatalf("Expected error, got nil") - } - return true, nil - }) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo/requests_test.go deleted file mode 100644 index 1e0fe230d66..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo/requests_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package buildinfo - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t, GetOutput) - - actual, err := Get(fake.ServiceClient()).Extract() - th.AssertNoErr(t, err) - - expected := GetExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents/requests_test.go deleted file mode 100644 index a4da4d04e61..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents/requests_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package stackevents - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestFindEvents(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleFindSuccessfully(t, FindOutput) - - actual, err := Find(fake.ServiceClient(), "postman_stack").Extract() - th.AssertNoErr(t, err) - - expected := FindExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t, ListOutput) - - count := 0 - err := List(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractEvents(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListResourceEvents(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListResourceEventsSuccessfully(t, ListResourceEventsOutput) - - count := 0 - err := ListResourceEvents(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", "my_resource", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractEvents(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ListResourceEventsExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetEvent(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t, GetOutput) - - actual, err := Get(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", "my_resource", "93940999-7d40-44ae-8de4-19624e7b8d18").Extract() - th.AssertNoErr(t, err) - - expected := GetExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/requests_test.go deleted file mode 100644 index f1378785f89..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources/requests_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package stackresources - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestFindResources(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleFindSuccessfully(t, FindOutput) - - actual, err := Find(fake.ServiceClient(), "hello_world").Extract() - th.AssertNoErr(t, err) - - expected := FindExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListResources(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t, ListOutput) - - count := 0 - err := List(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractResources(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetResource(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t, GetOutput) - - actual, err := Get(fake.ServiceClient(), "teststack", "0b1771bd-9336-4f2b-ae86-a80f971faf1e", "wordpress_instance").Extract() - th.AssertNoErr(t, err) - - expected := GetExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestResourceMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleMetadataSuccessfully(t, MetadataOutput) - - actual, err := Metadata(fake.ServiceClient(), "teststack", "0b1771bd-9336-4f2b-ae86-a80f971faf1e", "wordpress_instance").Extract() - th.AssertNoErr(t, err) - - expected := MetadataExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListResourceTypes(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListTypesSuccessfully(t, ListTypesOutput) - - count := 0 - err := ListTypes(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractResourceTypes(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ListTypesExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGetResourceSchema(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSchemaSuccessfully(t, GetSchemaOutput) - - actual, err := Schema(fake.ServiceClient(), "OS::Heat::AResourceName").Extract() - th.AssertNoErr(t, err) - - expected := GetSchemaExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestGetResourceTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetTemplateSuccessfully(t, GetTemplateOutput) - - actual, err := Template(fake.ServiceClient(), "OS::Heat::AResourceName").Extract() - th.AssertNoErr(t, err) - - expected := GetTemplateExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks/requests_test.go deleted file mode 100644 index 1e32ca2a9e6..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks/requests_test.go +++ /dev/null @@ -1,217 +0,0 @@ -package stacks - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestCreateStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateSuccessfully(t, CreateOutput) - - createOpts := CreateOpts{ - Name: "stackcreated", - Timeout: 60, - Template: ` - { - "stack_name": "postman_stack", - "template": { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - } - }`, - DisableRollback: Disable, - } - actual, err := Create(fake.ServiceClient(), createOpts).Extract() - th.AssertNoErr(t, err) - - expected := CreateExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestAdoptStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleCreateSuccessfully(t, CreateOutput) - - adoptOpts := AdoptOpts{ - AdoptStackData: `{environment{parameters{}}}`, - Name: "stackcreated", - Timeout: 60, - Template: ` - { - "stack_name": "postman_stack", - "template": { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - } - }`, - DisableRollback: Disable, - } - actual, err := Adopt(fake.ServiceClient(), adoptOpts).Extract() - th.AssertNoErr(t, err) - - expected := CreateExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleListSuccessfully(t, FullListOutput) - - count := 0 - err := List(fake.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractStacks(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t, GetOutput) - - actual, err := Get(fake.ServiceClient(), "postman_stack", "16ef0584-4458-41eb-87c8-0dc8d5f66c87").Extract() - th.AssertNoErr(t, err) - - expected := GetExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestUpdateStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleUpdateSuccessfully(t) - - updateOpts := UpdateOpts{ - Template: ` - { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - }`, - } - err := Update(fake.ServiceClient(), "gophercloud-test-stack-2", "db6977b2-27aa-4775-9ae7-6213212d4ada", updateOpts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDeleteStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleDeleteSuccessfully(t) - - err := Delete(fake.ServiceClient(), "gophercloud-test-stack-2", "db6977b2-27aa-4775-9ae7-6213212d4ada").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestPreviewStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandlePreviewSuccessfully(t, GetOutput) - - previewOpts := PreviewOpts{ - Name: "stackcreated", - Timeout: 60, - Template: ` - { - "stack_name": "postman_stack", - "template": { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - } - }`, - DisableRollback: Disable, - } - actual, err := Preview(fake.ServiceClient(), previewOpts).Extract() - th.AssertNoErr(t, err) - - expected := PreviewExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates/requests_test.go deleted file mode 100644 index d31c4ac9a2d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates/requests_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package stacktemplates - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleGetSuccessfully(t, GetOutput) - - actual, err := Get(fake.ServiceClient(), "postman_stack", "16ef0584-4458-41eb-87c8-0dc8d5f66c87").Extract() - th.AssertNoErr(t, err) - - expected := GetExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestValidateTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - HandleValidateSuccessfully(t, ValidateOutput) - - opts := ValidateOpts{ - Template: map[string]interface{}{ - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": map[string]interface{}{ - "flavor": map[string]interface{}{ - "default": "m1.tiny", - "type": "string", - }, - }, - "resources": map[string]interface{}{ - "hello_world": map[string]interface{}{ - "type": "OS::Nova::Server", - "properties": map[string]interface{}{ - "key_name": "heat_key", - "flavor": map[string]interface{}{ - "get_param": "flavor", - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n", - }, - }, - }, - }, - } - actual, err := Validate(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := ValidateExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/utils/choose_version_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/utils/choose_version_test.go deleted file mode 100644 index 388d6892cf4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/openstack/utils/choose_version_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package utils - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/testhelper" -) - -func setupVersionHandler() { - testhelper.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, ` - { - "versions": { - "values": [ - { - "status": "stable", - "id": "v3.0", - "links": [ - { "href": "%s/v3.0", "rel": "self" } - ] - }, - { - "status": "stable", - "id": "v2.0", - "links": [ - { "href": "%s/v2.0", "rel": "self" } - ] - } - ] - } - } - `, testhelper.Server.URL, testhelper.Server.URL) - }) -} - -func TestChooseVersion(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - setupVersionHandler() - - v2 := &Version{ID: "v2.0", Priority: 2, Suffix: "blarg"} - v3 := &Version{ID: "v3.0", Priority: 3, Suffix: "hargl"} - - c := &gophercloud.ProviderClient{ - IdentityBase: testhelper.Endpoint(), - IdentityEndpoint: "", - } - v, endpoint, err := ChooseVersion(c, []*Version{v2, v3}) - - if err != nil { - t.Fatalf("Unexpected error from ChooseVersion: %v", err) - } - - if v != v3 { - t.Errorf("Expected %#v to win, but %#v did instead", v3, v) - } - - expected := testhelper.Endpoint() + "v3.0/" - if endpoint != expected { - t.Errorf("Expected endpoint [%s], but was [%s] instead", expected, endpoint) - } -} - -func TestChooseVersionOpinionatedLink(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - setupVersionHandler() - - v2 := &Version{ID: "v2.0", Priority: 2, Suffix: "nope"} - v3 := &Version{ID: "v3.0", Priority: 3, Suffix: "northis"} - - c := &gophercloud.ProviderClient{ - IdentityBase: testhelper.Endpoint(), - IdentityEndpoint: testhelper.Endpoint() + "v2.0/", - } - v, endpoint, err := ChooseVersion(c, []*Version{v2, v3}) - if err != nil { - t.Fatalf("Unexpected error from ChooseVersion: %v", err) - } - - if v != v2 { - t.Errorf("Expected %#v to win, but %#v did instead", v2, v) - } - - expected := testhelper.Endpoint() + "v2.0/" - if endpoint != expected { - t.Errorf("Expected endpoint [%s], but was [%s] instead", expected, endpoint) - } -} - -func TestChooseVersionFromSuffix(t *testing.T) { - testhelper.SetupHTTP() - defer testhelper.TeardownHTTP() - - v2 := &Version{ID: "v2.0", Priority: 2, Suffix: "/v2.0/"} - v3 := &Version{ID: "v3.0", Priority: 3, Suffix: "/v3.0/"} - - c := &gophercloud.ProviderClient{ - IdentityBase: testhelper.Endpoint(), - IdentityEndpoint: testhelper.Endpoint() + "v2.0/", - } - v, endpoint, err := ChooseVersion(c, []*Version{v2, v3}) - if err != nil { - t.Fatalf("Unexpected error from ChooseVersion: %v", err) - } - - if v != v2 { - t.Errorf("Expected %#v to win, but %#v did instead", v2, v) - } - - expected := testhelper.Endpoint() + "v2.0/" - if endpoint != expected { - t.Errorf("Expected endpoint [%s], but was [%s] instead", expected, endpoint) - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/linked_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/linked_test.go deleted file mode 100644 index 1ac0f73164f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/linked_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package pagination - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud/testhelper" -) - -// LinkedPager sample and test cases. - -type LinkedPageResult struct { - LinkedPageBase -} - -func (r LinkedPageResult) IsEmpty() (bool, error) { - is, err := ExtractLinkedInts(r) - if err != nil { - return true, nil - } - return len(is) == 0, nil -} - -func ExtractLinkedInts(page Page) ([]int, error) { - var response struct { - Ints []int `mapstructure:"ints"` - } - - err := mapstructure.Decode(page.(LinkedPageResult).Body, &response) - if err != nil { - return nil, err - } - - return response.Ints, nil -} - -func createLinked(t *testing.T) Pager { - testhelper.SetupHTTP() - - testhelper.Mux.HandleFunc("/page1", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ "ints": [1, 2, 3], "links": { "next": "%s/page2" } }`, testhelper.Server.URL) - }) - - testhelper.Mux.HandleFunc("/page2", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ "ints": [4, 5, 6], "links": { "next": "%s/page3" } }`, testhelper.Server.URL) - }) - - testhelper.Mux.HandleFunc("/page3", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ "ints": [7, 8, 9], "links": { "next": null } }`) - }) - - client := createClient() - - createPage := func(r PageResult) Page { - return LinkedPageResult{LinkedPageBase{PageResult: r}} - } - - return NewPager(client, testhelper.Server.URL+"/page1", createPage) -} - -func TestEnumerateLinked(t *testing.T) { - pager := createLinked(t) - defer testhelper.TeardownHTTP() - - callCount := 0 - err := pager.EachPage(func(page Page) (bool, error) { - actual, err := ExtractLinkedInts(page) - if err != nil { - return false, err - } - - t.Logf("Handler invoked with %v", actual) - - var expected []int - switch callCount { - case 0: - expected = []int{1, 2, 3} - case 1: - expected = []int{4, 5, 6} - case 2: - expected = []int{7, 8, 9} - default: - t.Fatalf("Unexpected call count: %d", callCount) - return false, nil - } - - if !reflect.DeepEqual(expected, actual) { - t.Errorf("Call %d: Expected %#v, but was %#v", callCount, expected, actual) - } - - callCount++ - return true, nil - }) - if err != nil { - t.Errorf("Unexpected error for page iteration: %v", err) - } - - if callCount != 3 { - t.Errorf("Expected 3 calls, but was %d", callCount) - } -} - -func TestAllPagesLinked(t *testing.T) { - pager := createLinked(t) - defer testhelper.TeardownHTTP() - - page, err := pager.AllPages() - testhelper.AssertNoErr(t, err) - - expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} - actual, err := ExtractLinkedInts(page) - testhelper.AssertNoErr(t, err) - testhelper.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/marker_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/marker_test.go deleted file mode 100644 index f4d55be810b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/marker_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package pagination - -import ( - "fmt" - "net/http" - "strings" - "testing" - - "github.com/rackspace/gophercloud/testhelper" -) - -// MarkerPager sample and test cases. - -type MarkerPageResult struct { - MarkerPageBase -} - -func (r MarkerPageResult) IsEmpty() (bool, error) { - results, err := ExtractMarkerStrings(r) - if err != nil { - return true, err - } - return len(results) == 0, err -} - -func (r MarkerPageResult) LastMarker() (string, error) { - results, err := ExtractMarkerStrings(r) - if err != nil { - return "", err - } - if len(results) == 0 { - return "", nil - } - return results[len(results)-1], nil -} - -func createMarkerPaged(t *testing.T) Pager { - testhelper.SetupHTTP() - - testhelper.Mux.HandleFunc("/page", func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - ms := r.Form["marker"] - switch { - case len(ms) == 0: - fmt.Fprintf(w, "aaa\nbbb\nccc") - case len(ms) == 1 && ms[0] == "ccc": - fmt.Fprintf(w, "ddd\neee\nfff") - case len(ms) == 1 && ms[0] == "fff": - fmt.Fprintf(w, "ggg\nhhh\niii") - case len(ms) == 1 && ms[0] == "iii": - w.WriteHeader(http.StatusNoContent) - default: - t.Errorf("Request with unexpected marker: [%v]", ms) - } - }) - - client := createClient() - - createPage := func(r PageResult) Page { - p := MarkerPageResult{MarkerPageBase{PageResult: r}} - p.MarkerPageBase.Owner = p - return p - } - - return NewPager(client, testhelper.Server.URL+"/page", createPage) -} - -func ExtractMarkerStrings(page Page) ([]string, error) { - content := page.(MarkerPageResult).Body.([]uint8) - parts := strings.Split(string(content), "\n") - results := make([]string, 0, len(parts)) - for _, part := range parts { - if len(part) > 0 { - results = append(results, part) - } - } - return results, nil -} - -func TestEnumerateMarker(t *testing.T) { - pager := createMarkerPaged(t) - defer testhelper.TeardownHTTP() - - callCount := 0 - err := pager.EachPage(func(page Page) (bool, error) { - actual, err := ExtractMarkerStrings(page) - if err != nil { - return false, err - } - - t.Logf("Handler invoked with %v", actual) - - var expected []string - switch callCount { - case 0: - expected = []string{"aaa", "bbb", "ccc"} - case 1: - expected = []string{"ddd", "eee", "fff"} - case 2: - expected = []string{"ggg", "hhh", "iii"} - default: - t.Fatalf("Unexpected call count: %d", callCount) - return false, nil - } - - testhelper.CheckDeepEquals(t, expected, actual) - - callCount++ - return true, nil - }) - testhelper.AssertNoErr(t, err) - testhelper.AssertEquals(t, callCount, 3) -} - -func TestAllPagesMarker(t *testing.T) { - pager := createMarkerPaged(t) - defer testhelper.TeardownHTTP() - - page, err := pager.AllPages() - testhelper.AssertNoErr(t, err) - - expected := []string{"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii"} - actual, err := ExtractMarkerStrings(page) - testhelper.AssertNoErr(t, err) - testhelper.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/pagination_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/pagination_test.go deleted file mode 100644 index f3e4de1b042..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/pagination_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package pagination - -import ( - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/testhelper" -) - -func createClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{ - ProviderClient: &gophercloud.ProviderClient{TokenID: "abc123"}, - Endpoint: testhelper.Endpoint(), - } -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/single_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/single_test.go deleted file mode 100644 index 4af0fee69ab..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/pagination/single_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package pagination - -import ( - "fmt" - "net/http" - "testing" - - "github.com/mitchellh/mapstructure" - "github.com/rackspace/gophercloud/testhelper" -) - -// SinglePage sample and test cases. - -type SinglePageResult struct { - SinglePageBase -} - -func (r SinglePageResult) IsEmpty() (bool, error) { - is, err := ExtractSingleInts(r) - if err != nil { - return true, err - } - return len(is) == 0, nil -} - -func ExtractSingleInts(page Page) ([]int, error) { - var response struct { - Ints []int `mapstructure:"ints"` - } - - err := mapstructure.Decode(page.(SinglePageResult).Body, &response) - if err != nil { - return nil, err - } - - return response.Ints, nil -} - -func setupSinglePaged() Pager { - testhelper.SetupHTTP() - client := createClient() - - testhelper.Mux.HandleFunc("/only", func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, `{ "ints": [1, 2, 3] }`) - }) - - createPage := func(r PageResult) Page { - return SinglePageResult{SinglePageBase(r)} - } - - return NewPager(client, testhelper.Server.URL+"/only", createPage) -} - -func TestEnumerateSinglePaged(t *testing.T) { - callCount := 0 - pager := setupSinglePaged() - defer testhelper.TeardownHTTP() - - err := pager.EachPage(func(page Page) (bool, error) { - callCount++ - - expected := []int{1, 2, 3} - actual, err := ExtractSingleInts(page) - testhelper.AssertNoErr(t, err) - testhelper.CheckDeepEquals(t, expected, actual) - return true, nil - }) - testhelper.CheckNoErr(t, err) - testhelper.CheckEquals(t, 1, callCount) -} - -func TestAllPagesSingle(t *testing.T) { - pager := setupSinglePaged() - defer testhelper.TeardownHTTP() - - page, err := pager.AllPages() - testhelper.AssertNoErr(t, err) - - expected := []int{1, 2, 3} - actual, err := ExtractSingleInts(page) - testhelper.AssertNoErr(t, err) - testhelper.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/params_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/params_test.go deleted file mode 100644 index 2f40eec8122..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/params_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package gophercloud - -import ( - "net/url" - "reflect" - "testing" - "time" - - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestMaybeString(t *testing.T) { - testString := "" - var expected *string - actual := MaybeString(testString) - th.CheckDeepEquals(t, expected, actual) - - testString = "carol" - expected = &testString - actual = MaybeString(testString) - th.CheckDeepEquals(t, expected, actual) -} - -func TestMaybeInt(t *testing.T) { - testInt := 0 - var expected *int - actual := MaybeInt(testInt) - th.CheckDeepEquals(t, expected, actual) - - testInt = 4 - expected = &testInt - actual = MaybeInt(testInt) - th.CheckDeepEquals(t, expected, actual) -} - -func TestBuildQueryString(t *testing.T) { - type testVar string - opts := struct { - J int `q:"j"` - R string `q:"r,required"` - C bool `q:"c"` - S []string `q:"s"` - TS []testVar `q:"ts"` - TI []int `q:"ti"` - }{ - J: 2, - R: "red", - C: true, - S: []string{"one", "two", "three"}, - TS: []testVar{"a", "b"}, - TI: []int{1, 2}, - } - expected := &url.URL{RawQuery: "c=true&j=2&r=red&s=one&s=two&s=three&ti=1&ti=2&ts=a&ts=b"} - actual, err := BuildQueryString(&opts) - if err != nil { - t.Errorf("Error building query string: %v", err) - } - th.CheckDeepEquals(t, expected, actual) - - opts = struct { - J int `q:"j"` - R string `q:"r,required"` - C bool `q:"c"` - S []string `q:"s"` - TS []testVar `q:"ts"` - TI []int `q:"ti"` - }{ - J: 2, - C: true, - } - _, err = BuildQueryString(&opts) - if err == nil { - t.Errorf("Expected error: 'Required field not set'") - } - th.CheckDeepEquals(t, expected, actual) - - _, err = BuildQueryString(map[string]interface{}{"Number": 4}) - if err == nil { - t.Errorf("Expected error: 'Options type is not a struct'") - } -} - -func TestBuildHeaders(t *testing.T) { - testStruct := struct { - Accept string `h:"Accept"` - Num int `h:"Number,required"` - Style bool `h:"Style"` - }{ - Accept: "application/json", - Num: 4, - Style: true, - } - expected := map[string]string{"Accept": "application/json", "Number": "4", "Style": "true"} - actual, err := BuildHeaders(&testStruct) - th.CheckNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) - - testStruct.Num = 0 - _, err = BuildHeaders(&testStruct) - if err == nil { - t.Errorf("Expected error: 'Required header not set'") - } - - _, err = BuildHeaders(map[string]interface{}{"Number": 4}) - if err == nil { - t.Errorf("Expected error: 'Options type is not a struct'") - } -} - -func TestIsZero(t *testing.T) { - var testMap map[string]interface{} - testMapValue := reflect.ValueOf(testMap) - expected := true - actual := isZero(testMapValue) - th.CheckEquals(t, expected, actual) - testMap = map[string]interface{}{"empty": false} - testMapValue = reflect.ValueOf(testMap) - expected = false - actual = isZero(testMapValue) - th.CheckEquals(t, expected, actual) - - var testArray [2]string - testArrayValue := reflect.ValueOf(testArray) - expected = true - actual = isZero(testArrayValue) - th.CheckEquals(t, expected, actual) - testArray = [2]string{"one", "two"} - testArrayValue = reflect.ValueOf(testArray) - expected = false - actual = isZero(testArrayValue) - th.CheckEquals(t, expected, actual) - - var testStruct struct { - A string - B time.Time - } - testStructValue := reflect.ValueOf(testStruct) - expected = true - actual = isZero(testStructValue) - th.CheckEquals(t, expected, actual) - testStruct = struct { - A string - B time.Time - }{ - B: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), - } - testStructValue = reflect.ValueOf(testStruct) - expected = false - actual = isZero(testStructValue) - th.CheckEquals(t, expected, actual) -} - -func TestQueriesAreEscaped(t *testing.T) { - type foo struct { - Name string `q:"something"` - Shape string `q:"else"` - } - - expected := &url.URL{RawQuery: "else=Triangl+e&something=blah%2B%3F%21%21foo"} - - actual, err := BuildQueryString(foo{Name: "blah+?!!foo", Shape: "Triangl e"}) - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/provider_client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/provider_client_test.go deleted file mode 100644 index d79d862b2cf..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/provider_client_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package gophercloud - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAuthenticatedHeaders(t *testing.T) { - p := &ProviderClient{ - TokenID: "1234", - } - expected := map[string]string{"X-Auth-Token": "1234"} - actual := p.AuthenticatedHeaders() - th.CheckDeepEquals(t, expected, actual) -} - -func TestUserAgent(t *testing.T) { - p := &ProviderClient{} - - p.UserAgent.Prepend("custom-user-agent/2.4.0") - expected := "custom-user-agent/2.4.0 gophercloud/1.0.0" - actual := p.UserAgent.Join() - th.CheckEquals(t, expected, actual) - - p.UserAgent.Prepend("another-custom-user-agent/0.3.0", "a-third-ua/5.9.0") - expected = "another-custom-user-agent/0.3.0 a-third-ua/5.9.0 custom-user-agent/2.4.0 gophercloud/1.0.0" - actual = p.UserAgent.Join() - th.CheckEquals(t, expected, actual) - - p.UserAgent = UserAgent{} - expected = "gophercloud/1.0.0" - actual = p.UserAgent.Join() - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/snapshots/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/snapshots/delegate_test.go deleted file mode 100644 index 1a02b465279..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/snapshots/delegate_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package snapshots - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/blockstorage/v1/snapshots" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -const endpoint = "http://localhost:57909/v1/12345" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestUpdateURL(t *testing.T) { - actual := updateURL(endpointClient(), "foo") - expected := endpoint + "snapshots/foo" - th.AssertEquals(t, expected, actual) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockListResponse(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractSnapshots(page) - if err != nil { - t.Errorf("Failed to extract snapshots: %v", err) - return false, err - } - - expected := []Snapshot{ - Snapshot{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "snapshot-001", - }, - Snapshot{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "snapshot-002", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertEquals(t, 1, count) - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockGetResponse(t) - - v, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, v.Name, "snapshot-001") - th.AssertEquals(t, v.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockCreateResponse(t) - - options := &CreateOpts{VolumeID: "1234", Name: "snapshot-001"} - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.VolumeID, "1234") - th.AssertEquals(t, n.Name, "snapshot-001") - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockDeleteResponse(t) - - res := Delete(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes/delegate_test.go deleted file mode 100644 index b6831f21148..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes/delegate_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package volumes - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes" - os "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes/testing" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockListResponse(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVolumes(page) - if err != nil { - t.Errorf("Failed to extract volumes: %v", err) - return false, err - } - - expected := []Volume{ - Volume{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "vol-001", - }, - Volume{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "vol-002", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertEquals(t, 1, count) - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockGetResponse(t) - - v, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, v.Name, "vol-001") - th.AssertEquals(t, v.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockCreateResponse(t) - - n, err := Create(fake.ServiceClient(), CreateOpts{volumes.CreateOpts{Size: 75}}).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Size, 4) - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestSizeRange(t *testing.T) { - _, err := Create(fake.ServiceClient(), CreateOpts{volumes.CreateOpts{Size: 1}}).Extract() - if err == nil { - t.Fatalf("Expected error, got none") - } - - _, err = Create(fake.ServiceClient(), CreateOpts{volumes.CreateOpts{Size: 2000}}).Extract() - if err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockDeleteResponse(t) - - res := Delete(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertNoErr(t, res.Err) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockUpdateResponse(t) - - options := &UpdateOpts{Name: "vol-002"} - v, err := Update(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22", options).Extract() - th.AssertNoErr(t, err) - th.CheckEquals(t, "vol-002", v.Name) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumetypes/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumetypes/delegate_test.go deleted file mode 100644 index 6e65c904b52..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumetypes/delegate_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package volumetypes - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumetypes" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockListResponse(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVolumeTypes(page) - if err != nil { - t.Errorf("Failed to extract volume types: %v", err) - return false, err - } - - expected := []VolumeType{ - VolumeType{ - ID: "289da7f8-6440-407c-9fb4-7db01ec49164", - Name: "vol-type-001", - ExtraSpecs: map[string]interface{}{ - "capabilities": "gpu", - }, - }, - VolumeType{ - ID: "96c3bda7-c82a-4f50-be73-ca7621794835", - Name: "vol-type-002", - ExtraSpecs: map[string]interface{}{}, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertEquals(t, 1, count) - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.MockGetResponse(t) - - vt, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, vt.ExtraSpecs, map[string]interface{}{"serverNumber": "2"}) - th.AssertEquals(t, vt.Name, "vol-type-001") - th.AssertEquals(t, vt.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/base/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/base/delegate_test.go deleted file mode 100644 index 731fc6dd00c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/base/delegate_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package base - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/cdn/v1/base" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetHomeDocument(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t) - - actual, err := Get(fake.ServiceClient()).Extract() - th.CheckNoErr(t, err) - - expected := os.HomeDocument{ - "rel/cdn": map[string]interface{}{ - "href-template": "services{?marker,limit}", - "href-vars": map[string]interface{}{ - "marker": "param/marker", - "limit": "param/limit", - }, - "hints": map[string]interface{}{ - "allow": []string{"GET"}, - "formats": map[string]interface{}{ - "application/json": map[string]interface{}{}, - }, - }, - }, - } - th.CheckDeepEquals(t, expected, *actual) -} - -func TestPing(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandlePingSuccessfully(t) - - err := Ping(fake.ServiceClient()).ExtractErr() - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/flavors/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/flavors/delegate_test.go deleted file mode 100644 index d6d299df8ed..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/flavors/delegate_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package flavors - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/cdn/v1/flavors" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleListCDNFlavorsSuccessfully(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractFlavors(page) - if err != nil { - t.Errorf("Failed to extract flavors: %v", err) - return false, err - } - - expected := []os.Flavor{ - os.Flavor{ - ID: "europe", - Providers: []os.Provider{ - os.Provider{ - Provider: "Fastly", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "http://www.fastly.com", - Rel: "provider_url", - }, - }, - }, - }, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/europe", - Rel: "self", - }, - }, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleGetCDNFlavorSuccessfully(t) - - expected := &os.Flavor{ - ID: "asia", - Providers: []os.Provider{ - os.Provider{ - Provider: "ChinaCache", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "http://www.chinacache.com", - Rel: "provider_url", - }, - }, - }, - }, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/asia", - Rel: "self", - }, - }, - } - - actual, err := Get(fake.ServiceClient(), "asia").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/serviceassets/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/serviceassets/delegate_test.go deleted file mode 100644 index 328e1682d33..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/serviceassets/delegate_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package serviceassets - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/cdn/v1/serviceassets" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleDeleteCDNAssetSuccessfully(t) - - err := Delete(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", nil).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/services/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/services/delegate_test.go deleted file mode 100644 index 6c48365e4ed..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/cdn/v1/services/delegate_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package services - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/cdn/v1/services" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleListCDNServiceSuccessfully(t) - - count := 0 - - err := List(fake.ServiceClient(), &os.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractServices(page) - if err != nil { - t.Errorf("Failed to extract services: %v", err) - return false, err - } - - expected := []os.Service{ - os.Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Name: "mywebsite.com", - Domains: []os.Domain{ - os.Domain{ - Domain: "www.mywebsite.com", - }, - }, - Origins: []os.Origin{ - os.Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Caching: []os.CacheRule{ - os.CacheRule{ - Name: "default", - TTL: 3600, - }, - os.CacheRule{ - Name: "home", - TTL: 17200, - Rules: []os.TTLRule{ - os.TTLRule{ - Name: "index", - RequestURL: "/index.htm", - }, - }, - }, - os.CacheRule{ - Name: "images", - TTL: 12800, - Rules: []os.TTLRule{ - os.TTLRule{ - Name: "images", - RequestURL: "*.png", - }, - }, - }, - }, - Restrictions: []os.Restriction{ - os.Restriction{ - Name: "website only", - Rules: []os.RestrictionRule{ - os.RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - FlavorID: "asia", - Status: "deployed", - Errors: []os.Error{}, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Rel: "self", - }, - gophercloud.Link{ - Href: "mywebsite.com.cdn123.poppycdn.net", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/asia", - Rel: "flavor", - }, - }, - }, - os.Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1", - Name: "myothersite.com", - Domains: []os.Domain{ - os.Domain{ - Domain: "www.myothersite.com", - }, - }, - Origins: []os.Origin{ - os.Origin{ - Origin: "44.33.22.11", - Port: 80, - SSL: false, - }, - os.Origin{ - Origin: "77.66.55.44", - Port: 80, - SSL: false, - Rules: []os.OriginRule{ - os.OriginRule{ - Name: "videos", - RequestURL: "^/videos/*.m3u", - }, - }, - }, - }, - Caching: []os.CacheRule{ - os.CacheRule{ - Name: "default", - TTL: 3600, - }, - }, - Restrictions: []os.Restriction{}, - FlavorID: "europe", - Status: "deployed", - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f1", - Rel: "self", - }, - gophercloud.Link{ - Href: "myothersite.com.poppycdn.net", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://www.poppycdn.io/v1.0/flavors/europe", - Rel: "flavor", - }, - }, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleCreateCDNServiceSuccessfully(t) - - createOpts := os.CreateOpts{ - Name: "mywebsite.com", - Domains: []os.Domain{ - os.Domain{ - Domain: "www.mywebsite.com", - }, - os.Domain{ - Domain: "blog.mywebsite.com", - }, - }, - Origins: []os.Origin{ - os.Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Restrictions: []os.Restriction{ - os.Restriction{ - Name: "website only", - Rules: []os.RestrictionRule{ - os.RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - Caching: []os.CacheRule{ - os.CacheRule{ - Name: "default", - TTL: 3600, - }, - }, - FlavorID: "cdn", - } - - expected := "https://global.cdn.api.rackspacecloud.com/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" - actual, err := Create(fake.ServiceClient(), createOpts).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, expected, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleGetCDNServiceSuccessfully(t) - - expected := &os.Service{ - ID: "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Name: "mywebsite.com", - Domains: []os.Domain{ - os.Domain{ - Domain: "www.mywebsite.com", - Protocol: "http", - }, - }, - Origins: []os.Origin{ - os.Origin{ - Origin: "mywebsite.com", - Port: 80, - SSL: false, - }, - }, - Caching: []os.CacheRule{ - os.CacheRule{ - Name: "default", - TTL: 3600, - }, - os.CacheRule{ - Name: "home", - TTL: 17200, - Rules: []os.TTLRule{ - os.TTLRule{ - Name: "index", - RequestURL: "/index.htm", - }, - }, - }, - os.CacheRule{ - Name: "images", - TTL: 12800, - Rules: []os.TTLRule{ - os.TTLRule{ - Name: "images", - RequestURL: "*.png", - }, - }, - }, - }, - Restrictions: []os.Restriction{ - os.Restriction{ - Name: "website only", - Rules: []os.RestrictionRule{ - os.RestrictionRule{ - Name: "mywebsite.com", - Referrer: "www.mywebsite.com", - }, - }, - }, - }, - FlavorID: "cdn", - Status: "deployed", - Errors: []os.Error{}, - Links: []gophercloud.Link{ - gophercloud.Link{ - Href: "https://global.cdn.api.rackspacecloud.com/v1.0/110011/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", - Rel: "self", - }, - gophercloud.Link{ - Href: "blog.mywebsite.com.cdn1.raxcdn.com", - Rel: "access_url", - }, - gophercloud.Link{ - Href: "https://global.cdn.api.rackspacecloud.com/v1.0/110011/flavors/cdn", - Rel: "flavor", - }, - }, - } - - actual, err := Get(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestSuccessfulUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleUpdateCDNServiceSuccessfully(t) - - expected := "https://www.poppycdn.io/v1.0/services/96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0" - ops := []os.Patch{ - // Append a single Domain - os.Append{Value: os.Domain{Domain: "appended.mocksite4.com"}}, - // Insert a single Domain - os.Insertion{ - Index: 4, - Value: os.Domain{Domain: "inserted.mocksite4.com"}, - }, - // Bulk addition - os.Append{ - Value: os.DomainList{ - os.Domain{Domain: "bulkadded1.mocksite4.com"}, - os.Domain{Domain: "bulkadded2.mocksite4.com"}, - }, - }, - // Replace a single Origin - os.Replacement{ - Index: 2, - Value: os.Origin{Origin: "44.33.22.11", Port: 80, SSL: false}, - }, - // Bulk replace Origins - os.Replacement{ - Index: 0, // Ignored - Value: os.OriginList{ - os.Origin{Origin: "44.33.22.11", Port: 80, SSL: false}, - os.Origin{Origin: "55.44.33.22", Port: 443, SSL: true}, - }, - }, - // Remove a single CacheRule - os.Removal{ - Index: 8, - Path: os.PathCaching, - }, - // Bulk removal - os.Removal{ - All: true, - Path: os.PathCaching, - }, - // Service name replacement - os.NameReplacement{ - NewName: "differentServiceName", - }, - } - - actual, err := Update(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0", ops).Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, expected, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleDeleteCDNServiceSuccessfully(t) - - err := Delete(fake.ServiceClient(), "96737ae3-cfc1-4c72-be88-5d0e7cc9a3f0").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/client_test.go deleted file mode 100644 index 73b1c886ffa..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/client_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package rackspace - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestAuthenticatedClientV2(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/tokens", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, ` - { - "access": { - "token": { - "id": "01234567890", - "expires": "2014-10-01T10:00:00.000000Z" - }, - "serviceCatalog": [] - } - } - `) - }) - - options := gophercloud.AuthOptions{ - Username: "me", - APIKey: "09876543210", - IdentityEndpoint: th.Endpoint() + "v2.0/", - } - client, err := AuthenticatedClient(options) - th.AssertNoErr(t, err) - th.CheckEquals(t, "01234567890", client.TokenID) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/bootfromvolume/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/bootfromvolume/delegate_test.go deleted file mode 100644 index 571a1bed2b7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/bootfromvolume/delegate_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package bootfromvolume - -import ( - "testing" - - osBFV "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume" - "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCreateOpts(t *testing.T) { - base := servers.CreateOpts{ - Name: "createdserver", - ImageRef: "asdfasdfasdf", - FlavorRef: "performance1-1", - } - - ext := osBFV.CreateOptsExt{ - CreateOptsBuilder: base, - BlockDevice: []osBFV.BlockDevice{ - osBFV.BlockDevice{ - UUID: "123456", - SourceType: osBFV.Image, - DestinationType: "volume", - VolumeSize: 10, - }, - }, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "asdfasdfasdf", - "flavorRef": "performance1-1", - "flavorName": "", - "imageName": "", - "block_device_mapping_v2":[ - { - "uuid":"123456", - "source_type":"image", - "destination_type":"volume", - "boot_index": "0", - "delete_on_termination": "false", - "volume_size": "10" - } - ] - } - } - ` - actual, err := ext.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/flavors/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/flavors/delegate_test.go deleted file mode 100644 index 204081dd179..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/flavors/delegate_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package flavors - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListFlavors(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/flavors/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ListOutput) - case "performance1-2": - fmt.Fprintf(w, `{ "flavors": [] }`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) - - count := 0 - err := ListDetail(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - actual, err := ExtractFlavors(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedFlavorSlice, actual) - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGetFlavor(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/flavors/performance1-1", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) - - actual, err := Get(client.ServiceClient(), "performance1-1").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &Performance1Flavor, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/images/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/images/delegate_test.go deleted file mode 100644 index db0a6e3414c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/images/delegate_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package images - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListImageDetails(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/images/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - r.ParseForm() - marker := r.Form.Get("marker") - switch marker { - case "": - fmt.Fprintf(w, ListOutput) - case "e19a734c-c7e6-443a-830c-242209c4d65d": - fmt.Fprintf(w, `{ "images": [] }`) - default: - t.Fatalf("Unexpected marker: [%s]", marker) - } - }) - - count := 0 - err := ListDetail(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractImages(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedImageSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGetImageDetails(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/images/e19a734c-c7e6-443a-830c-242209c4d65d", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) - - actual, err := Get(client.ServiceClient(), "e19a734c-c7e6-443a-830c-242209c4d65d").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &UbuntuImage, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs/delegate_test.go deleted file mode 100644 index 62e5df950ce..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/keypairs/delegate_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package keypairs - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListSuccessfully(t) - - count := 0 - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractKeyPairs(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, os.ExpectedKeyPairSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleCreateSuccessfully(t) - - actual, err := Create(client.ServiceClient(), os.CreateOpts{ - Name: "createdkey", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &os.CreatedKeyPair, actual) -} - -func TestImport(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleImportSuccessfully(t) - - actual, err := Create(client.ServiceClient(), os.CreateOpts{ - Name: "importedkey", - PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDx8nkQv/zgGgB4rMYmIf+6A4l6Rr+o/6lHBQdW5aYd44bd8JttDCE/F/pNRr0lRE+PiqSPO8nDPHw0010JeMH9gYgnnFlyY3/OcJ02RhIPyyxYpv9FhY+2YiUkpwFOcLImyrxEsYXpD/0d3ac30bNH6Sw9JD9UZHYcpSxsIbECHw== Generated by Nova", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &os.ImportedKeyPair, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t) - - actual, err := Get(client.ServiceClient(), "firstkey").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &os.FirstKeyPair, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDeleteSuccessfully(t) - - err := Delete(client.ServiceClient(), "deletedkey").ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/requests_test.go deleted file mode 100644 index 6f44c1caba7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/requests_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package networks - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/os-networksv2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "networks": [ - { - "label": "test-network-1", - "cidr": "192.168.100.0/24", - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - }, - { - "label": "test-network-2", - "cidr": "192.30.250.00/18", - "id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324" - } - ] -} - `) - }) - - client := fake.ServiceClient() - count := 0 - - err := List(client).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNetworks(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []Network{ - Network{ - Label: "test-network-1", - CIDR: "192.168.100.0/24", - ID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - }, - Network{ - Label: "test-network-2", - CIDR: "192.30.250.00/18", - ID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/os-networksv2/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "label": "test-network-1", - "cidr": "192.168.100.0/24", - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.CIDR, "192.168.100.0/24") - th.AssertEquals(t, n.Label, "test-network-1") - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/os-networksv2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "label": "test-network-1", - "cidr": "192.168.100.0/24" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "network": { - "label": "test-network-1", - "cidr": "192.168.100.0/24", - "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c" - } -} - `) - }) - - options := CreateOpts{Label: "test-network-1", CIDR: "192.168.100.0/24"} - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Label, "test-network-1") - th.AssertEquals(t, n.ID, "4e8e5957-649f-477b-9e5b-f1f75b21c03c") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/os-networksv2/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/urls_test.go deleted file mode 100644 index 983992e2b9b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/networks/urls_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package networks - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestGetURL(t *testing.T) { - actual := getURL(endpointClient(), "foo") - expected := endpoint + "os-networksv2/foo" - th.AssertEquals(t, expected, actual) -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "os-networksv2" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := createURL(endpointClient()) - expected := endpoint + "os-networksv2" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "foo") - expected := endpoint + "os-networksv2/foo" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/delegate_test.go deleted file mode 100644 index 03e7acea846..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/delegate_test.go +++ /dev/null @@ -1,182 +0,0 @@ -package servers - -import ( - "fmt" - "net/http" - "testing" - - os "github.com/rackspace/gophercloud/openstack/compute/v2/servers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListServers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/detail", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, ListOutput) - }) - - count := 0 - err := List(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractServers(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedServerSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreateServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleServerCreationSuccessfully(t, CreateOutput) - - actual, err := Create(client.ServiceClient(), os.CreateOpts{ - Name: "derp", - ImageRef: "f90f6034-2570-4974-8351-6b49732ef2eb", - FlavorRef: "1", - }).Extract() - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, &CreatedServer, actual) -} - -func TestDeleteServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleServerDeletionSuccessfully(t) - - res := Delete(client.ServiceClient(), "asdfasdfasdf") - th.AssertNoErr(t, res.Err) -} - -func TestGetServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/8c65cb68-0681-4c30-bc88-6b83a8a26aee", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - - w.Header().Add("Content-Type", "application/json") - fmt.Fprintf(w, GetOutput) - }) - - actual, err := Get(client.ServiceClient(), "8c65cb68-0681-4c30-bc88-6b83a8a26aee").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &GophercloudServer, actual) -} - -func TestUpdateServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/8c65cb68-0681-4c30-bc88-6b83a8a26aee", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", client.TokenID) - th.TestJSONRequest(t, r, `{ "server": { "name": "test-server-updated" } }`) - - w.Header().Add("Content-Type", "application/json") - - fmt.Fprintf(w, UpdateOutput) - }) - - opts := os.UpdateOpts{ - Name: "test-server-updated", - } - actual, err := Update(client.ServiceClient(), "8c65cb68-0681-4c30-bc88-6b83a8a26aee", opts).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &GophercloudUpdatedServer, actual) -} - -func TestChangeAdminPassword(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleAdminPasswordChangeSuccessfully(t) - - res := ChangeAdminPassword(client.ServiceClient(), "1234asdf", "new-password") - th.AssertNoErr(t, res.Err) -} - -func TestReboot(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleRebootSuccessfully(t) - - res := Reboot(client.ServiceClient(), "1234asdf", os.SoftReboot) - th.AssertNoErr(t, res.Err) -} - -func TestRebuildServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleRebuildSuccessfully(t, GetOutput) - - opts := os.RebuildOpts{ - Name: "new-name", - AdminPass: "swordfish", - ImageID: "http://104.130.131.164:8774/fcad67a6189847c4aecfa3c81a05783b/images/f90f6034-2570-4974-8351-6b49732ef2eb", - AccessIPv4: "1.2.3.4", - } - actual, err := Rebuild(client.ServiceClient(), "1234asdf", opts).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &GophercloudServer, actual) -} - -func TestListAddresses(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleAddressListSuccessfully(t) - - expected := os.ListAddressesExpected - pages := 0 - err := ListAddresses(client.ServiceClient(), "asdfasdfasdf").EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractAddresses(page) - th.AssertNoErr(t, err) - - if len(actual) != 2 { - t.Fatalf("Expected 2 networks, got %d", len(actual)) - } - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, pages) -} - -func TestListAddressesByNetwork(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleNetworkAddressListSuccessfully(t) - - expected := os.ListNetworkAddressesExpected - pages := 0 - err := ListAddressesByNetwork(client.ServiceClient(), "asdfasdfasdf", "public").EachPage(func(page pagination.Page) (bool, error) { - pages++ - - actual, err := ExtractNetworkAddresses(page) - th.AssertNoErr(t, err) - - if len(actual) != 2 { - t.Fatalf("Expected 2 addresses, got %d", len(actual)) - } - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, pages) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/requests_test.go deleted file mode 100644 index 828b5dc491e..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/servers/requests_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package servers - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestCreateOpts(t *testing.T) { - opts := CreateOpts{ - Name: "createdserver", - ImageRef: "image-id", - FlavorRef: "flavor-id", - KeyPair: "mykey", - DiskConfig: diskconfig.Manual, - } - - expected := ` - { - "server": { - "name": "createdserver", - "imageRef": "image-id", - "flavorRef": "flavor-id", - "flavorName": "", - "imageName": "", - "key_name": "mykey", - "OS-DCF:diskConfig": "MANUAL" - } - } - ` - actual, err := opts.ToServerCreateMap() - th.AssertNoErr(t, err) - th.CheckJSONEquals(t, expected, actual) -} - -func TestRebuildOpts(t *testing.T) { - opts := RebuildOpts{ - Name: "rebuiltserver", - AdminPass: "swordfish", - ImageID: "asdfasdfasdf", - DiskConfig: diskconfig.Auto, - } - - actual, err := opts.ToServerRebuildMap() - th.AssertNoErr(t, err) - - expected := ` - { - "rebuild": { - "name": "rebuiltserver", - "imageRef": "asdfasdfasdf", - "adminPass": "swordfish", - "OS-DCF:diskConfig": "AUTO" - } - } - ` - th.CheckJSONEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/requests_test.go deleted file mode 100644 index d40af9c4625..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/requests_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package virtualinterfaces - -import ( - "fmt" - "net/http" - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/12345/os-virtual-interfacesv2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "virtual_interfaces": [ - { - "id": "de7c6d53-b895-4b4a-963c-517ccb0f0775", - "ip_addresses": [ - { - "address": "192.168.0.2", - "network_id": "f212726e-6321-4210-9bae-a13f5a33f83f", - "network_label": "superprivate_xml" - } - ], - "mac_address": "BC:76:4E:04:85:20" - }, - { - "id": "e14e789d-3b98-44a6-9c2d-c23eb1d1465c", - "ip_addresses": [ - { - "address": "10.181.1.30", - "network_id": "3b324a1b-31b8-4db5-9fe5-4a2067f60297", - "network_label": "private" - } - ], - "mac_address": "BC:76:4E:04:81:55" - } - ] -} - `) - }) - - client := fake.ServiceClient() - count := 0 - - err := List(client, "12345").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVirtualInterfaces(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []VirtualInterface{ - VirtualInterface{ - MACAddress: "BC:76:4E:04:85:20", - IPAddresses: []IPAddress{ - IPAddress{ - Address: "192.168.0.2", - NetworkID: "f212726e-6321-4210-9bae-a13f5a33f83f", - NetworkLabel: "superprivate_xml", - }, - }, - ID: "de7c6d53-b895-4b4a-963c-517ccb0f0775", - }, - VirtualInterface{ - MACAddress: "BC:76:4E:04:81:55", - IPAddresses: []IPAddress{ - IPAddress{ - Address: "10.181.1.30", - NetworkID: "3b324a1b-31b8-4db5-9fe5-4a2067f60297", - NetworkLabel: "private", - }, - }, - ID: "e14e789d-3b98-44a6-9c2d-c23eb1d1465c", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/12345/os-virtual-interfacesv2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "virtual_interface": { - "network_id": "6789" - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, `{ - "virtual_interfaces": [ - { - "id": "de7c6d53-b895-4b4a-963c-517ccb0f0775", - "ip_addresses": [ - { - "address": "192.168.0.2", - "network_id": "f212726e-6321-4210-9bae-a13f5a33f83f", - "network_label": "superprivate_xml" - } - ], - "mac_address": "BC:76:4E:04:85:20" - } - ] - }`) - }) - - expected := &VirtualInterface{ - MACAddress: "BC:76:4E:04:85:20", - IPAddresses: []IPAddress{ - IPAddress{ - Address: "192.168.0.2", - NetworkID: "f212726e-6321-4210-9bae-a13f5a33f83f", - NetworkLabel: "superprivate_xml", - }, - }, - ID: "de7c6d53-b895-4b4a-963c-517ccb0f0775", - } - - actual, err := Create(fake.ServiceClient(), "12345", "6789").Extract() - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/servers/12345/os-virtual-interfacesv2/6789", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "12345", "6789") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/urls_test.go deleted file mode 100644 index 6732e4ed9f4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/virtualinterfaces/urls_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package virtualinterfaces - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestCreateURL(t *testing.T) { - actual := createURL(endpointClient(), "12345") - expected := endpoint + "servers/12345/os-virtual-interfacesv2" - th.AssertEquals(t, expected, actual) -} - -func TestListURL(t *testing.T) { - actual := createURL(endpointClient(), "12345") - expected := endpoint + "servers/12345/os-virtual-interfacesv2" - th.AssertEquals(t, expected, actual) -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient(), "12345", "6789") - expected := endpoint + "servers/12345/os-virtual-interfacesv2/6789" - th.AssertEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach/delegate_test.go deleted file mode 100644 index f7ef45e621a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach/delegate_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package volumeattach - -import ( - "testing" - - "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach" - fixtures "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach/testing" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -// FirstVolumeAttachment is the first result in ListOutput. -var FirstVolumeAttachment = volumeattach.VolumeAttachment{ - Device: "/dev/vdd", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f803", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f803", -} - -// SecondVolumeAttachment is the first result in ListOutput. -var SecondVolumeAttachment = volumeattach.VolumeAttachment{ - Device: "/dev/vdc", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", -} - -// ExpectedVolumeAttachmentSlide is the slice of results that should be parsed -// from ListOutput, in the expected order. -var ExpectedVolumeAttachmentSlice = []volumeattach.VolumeAttachment{FirstVolumeAttachment, SecondVolumeAttachment} - -//CreatedVolumeAttachment is the parsed result from CreatedOutput. -var CreatedVolumeAttachment = volumeattach.VolumeAttachment{ - Device: "/dev/vdc", - ID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - ServerID: "4d8c3732-a248-40ed-bebc-539a6ffd25c0", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleListSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - count := 0 - err := List(client.ServiceClient(), serverId).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := volumeattach.ExtractVolumeAttachments(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, ExpectedVolumeAttachmentSlice, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleCreateSuccessfully(t) - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - actual, err := Create(client.ServiceClient(), serverId, volumeattach.CreateOpts{ - Device: "/dev/vdc", - VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804", - }).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &CreatedVolumeAttachment, actual) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleGetSuccessfully(t) - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - actual, err := Get(client.ServiceClient(), serverId, aId).Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, &SecondVolumeAttachment, actual) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - fixtures.HandleDeleteSuccessfully(t) - aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804" - serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0" - - err := Delete(client.ServiceClient(), serverId, aId).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/extensions/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/extensions/delegate_test.go deleted file mode 100644 index e30f79404dc..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/extensions/delegate_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package extensions - -import ( - "testing" - - common "github.com/rackspace/gophercloud/openstack/common/extensions" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - common.HandleListExtensionsSuccessfully(t) - - count := 0 - - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractExtensions(page) - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, common.ExpectedExtensions, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - common.HandleGetExtensionSuccessfully(t) - - actual, err := Get(fake.ServiceClient(), "agent").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, common.SingleExtension, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/roles/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/roles/delegate_test.go deleted file mode 100644 index fcee97d0bc3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/roles/delegate_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package roles - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/identity/v2/extensions/admin/roles" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockListRoleResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractRoles(page) - if err != nil { - t.Errorf("Failed to extract users: %v", err) - return false, err - } - - expected := []os.Role{ - os.Role{ - ID: "123", - Name: "compute:admin", - Description: "Nova Administrator", - ServiceID: "cke5372ebabeeabb70a0e702a4626977x4406e5", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestAddUserRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockAddUserRoleResponse(t) - - err := AddUserRole(client.ServiceClient(), "{user_id}", "{role_id}").ExtractErr() - - th.AssertNoErr(t, err) -} - -func TestDeleteUserRole(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - MockDeleteUserRoleResponse(t) - - err := DeleteUserRole(client.ServiceClient(), "{user_id}", "{role_id}").ExtractErr() - - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tenants/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tenants/delegate_test.go deleted file mode 100644 index eccbfe23eb6..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tenants/delegate_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package tenants - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/identity/v2/tenants" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListTenants(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListTenantsSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - actual, err := ExtractTenants(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, os.ExpectedTenantSlice, actual) - - count++ - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tokens/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tokens/delegate_test.go deleted file mode 100644 index 6678ff4a7c2..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/tokens/delegate_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package tokens - -import ( - "testing" - - "github.com/rackspace/gophercloud" - os "github.com/rackspace/gophercloud/openstack/identity/v2/tokens" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func tokenPost(t *testing.T, options gophercloud.AuthOptions, requestJSON string) os.CreateResult { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleTokenPost(t, requestJSON) - - return Create(client.ServiceClient(), WrapOptions(options)) -} - -func TestCreateTokenWithAPIKey(t *testing.T) { - options := gophercloud.AuthOptions{ - Username: "me", - APIKey: "1234567890abcdef", - } - - os.IsSuccessful(t, tokenPost(t, options, ` - { - "auth": { - "RAX-KSKEY:apiKeyCredentials": { - "username": "me", - "apiKey": "1234567890abcdef" - } - } - } - `)) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/users/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/users/delegate_test.go deleted file mode 100644 index 62faf0c5bec..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/identity/v2/users/delegate_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package users - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/identity/v2/users" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListResponse(t) - - count := 0 - - err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - users, err := os.ExtractUsers(page) - - th.AssertNoErr(t, err) - th.AssertEquals(t, "u1000", users[0].ID) - th.AssertEquals(t, "u1001", users[1].ID) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreateUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateUser(t) - - opts := CreateOpts{ - Username: "new_user", - Enabled: os.Disabled, - Email: "new_user@foo.com", - Password: "foo", - } - - user, err := Create(client.ServiceClient(), opts).Extract() - - th.AssertNoErr(t, err) - - th.AssertEquals(t, "123456", user.ID) - th.AssertEquals(t, "5830280", user.DomainID) - th.AssertEquals(t, "DFW", user.DefaultRegion) -} - -func TestGetUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetUser(t) - - user, err := Get(client.ServiceClient(), "new_user").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, true, user.Enabled) - th.AssertEquals(t, true, user.MultiFactorEnabled) -} - -func TestUpdateUser(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateUser(t) - - id := "c39e3de9be2d4c779f1dfd6abacc176d" - - opts := UpdateOpts{ - Enabled: os.Enabled, - Email: "new_email@foo.com", - } - - user, err := Update(client.ServiceClient(), id, opts).Extract() - - th.AssertNoErr(t, err) - - th.AssertEquals(t, true, user.Enabled) - th.AssertEquals(t, "new_email@foo.com", user.Email) -} - -func TestDeleteServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteUser(t) - - res := Delete(client.ServiceClient(), "c39e3de9be2d4c779f1dfd6abacc176d") - th.AssertNoErr(t, res.Err) -} - -func TestResetAPIKey(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockResetAPIKey(t) - - apiKey, err := ResetAPIKey(client.ServiceClient(), "99").Extract() - th.AssertNoErr(t, err) - th.AssertEquals(t, "joesmith", apiKey.Username) - th.AssertEquals(t, "mooH1eiLahd5ahYood7r", apiKey.APIKey) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/acl/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/acl/requests_test.go deleted file mode 100644 index c4961a3dd8f..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/acl/requests_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package acl - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - lbID = 12345 - itemID1 = 67890 - itemID2 = 67891 -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListResponse(t, lbID) - - count := 0 - - err := List(client.ServiceClient(), lbID).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractAccessList(page) - th.AssertNoErr(t, err) - - expected := AccessList{ - NetworkItem{Address: "206.160.163.21", ID: 21, Type: DENY}, - NetworkItem{Address: "206.160.163.22", ID: 22, Type: DENY}, - NetworkItem{Address: "206.160.163.23", ID: 23, Type: DENY}, - NetworkItem{Address: "206.160.163.24", ID: 24, Type: DENY}, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateResponse(t, lbID) - - opts := CreateOpts{ - CreateOpt{Address: "206.160.163.21", Type: DENY}, - CreateOpt{Address: "206.160.165.11", Type: DENY}, - } - - err := Create(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestBulkDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - ids := []int{itemID1, itemID2} - - mockBatchDeleteResponse(t, lbID, ids) - - err := BulkDelete(client.ServiceClient(), lbID, ids).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID, itemID1) - - err := Delete(client.ServiceClient(), lbID, itemID1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDeleteAll(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteAllResponse(t, lbID) - - err := DeleteAll(client.ServiceClient(), lbID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/lbs/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/lbs/requests_test.go deleted file mode 100644 index a8ec19e07c3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/lbs/requests_test.go +++ /dev/null @@ -1,438 +0,0 @@ -package lbs - -import ( - "testing" - "time" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - "github.com/rackspace/gophercloud/rackspace/lb/v1/nodes" - "github.com/rackspace/gophercloud/rackspace/lb/v1/sessions" - "github.com/rackspace/gophercloud/rackspace/lb/v1/throttle" - "github.com/rackspace/gophercloud/rackspace/lb/v1/vips" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - id1 = 12345 - id2 = 67890 - ts1 = "2010-11-30T03:23:42Z" - ts2 = "2010-11-30T03:23:44Z" -) - -func toTime(t *testing.T, str string) time.Time { - ts, err := time.Parse(time.RFC3339, str) - if err != nil { - t.Fatalf("Could not parse time: %s", err.Error()) - } - return ts -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListLBResponse(t) - - count := 0 - - err := List(client.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractLBs(page) - th.AssertNoErr(t, err) - - expected := []LoadBalancer{ - LoadBalancer{ - Name: "lb-site1", - ID: 71, - Protocol: "HTTP", - Port: 80, - Algorithm: "RANDOM", - Status: ACTIVE, - NodeCount: 3, - VIPs: []vips.VIP{ - vips.VIP{ - ID: 403, - Address: "206.55.130.1", - Type: "PUBLIC", - Version: "IPV4", - }, - }, - Created: Datetime{Time: toTime(t, ts1)}, - Updated: Datetime{Time: toTime(t, ts2)}, - }, - LoadBalancer{ - ID: 72, - Name: "lb-site2", - Created: Datetime{Time: toTime(t, "2011-11-30T03:23:42Z")}, - Updated: Datetime{Time: toTime(t, "2011-11-30T03:23:44Z")}, - }, - LoadBalancer{ - ID: 73, - Name: "lb-site3", - Created: Datetime{Time: toTime(t, "2012-11-30T03:23:42Z")}, - Updated: Datetime{Time: toTime(t, "2012-11-30T03:23:44Z")}, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateLBResponse(t) - - opts := CreateOpts{ - Name: "a-new-loadbalancer", - Port: 80, - Protocol: "HTTP", - VIPs: []vips.VIP{ - vips.VIP{ID: 2341}, - vips.VIP{ID: 900001}, - }, - Nodes: []nodes.Node{ - nodes.Node{Address: "10.1.1.1", Port: 80, Condition: "ENABLED"}, - }, - } - - lb, err := Create(client.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := &LoadBalancer{ - Name: "a-new-loadbalancer", - ID: 144, - Protocol: "HTTP", - HalfClosed: false, - Port: 83, - Algorithm: "RANDOM", - Status: BUILD, - Timeout: 30, - Cluster: Cluster{Name: "ztm-n01.staging1.lbaas.rackspace.net"}, - Nodes: []nodes.Node{ - nodes.Node{ - Address: "10.1.1.1", - ID: 653, - Port: 80, - Status: "ONLINE", - Condition: "ENABLED", - Weight: 1, - }, - }, - VIPs: []vips.VIP{ - vips.VIP{ - ID: 39, - Address: "206.10.10.210", - Type: vips.PUBLIC, - Version: vips.IPV4, - }, - vips.VIP{ - ID: 900001, - Address: "2001:4801:79f1:0002:711b:be4c:0000:0021", - Type: vips.PUBLIC, - Version: vips.IPV6, - }, - }, - Created: Datetime{Time: toTime(t, ts1)}, - Updated: Datetime{Time: toTime(t, ts2)}, - ConnectionLogging: ConnectionLogging{Enabled: false}, - } - - th.AssertDeepEquals(t, expected, lb) -} - -func TestBulkDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - ids := []int{id1, id2} - - mockBatchDeleteLBResponse(t, ids) - - err := BulkDelete(client.ServiceClient(), ids).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteLBResponse(t, id1) - - err := Delete(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetLBResponse(t, id1) - - lb, err := Get(client.ServiceClient(), id1).Extract() - - expected := &LoadBalancer{ - Name: "sample-loadbalancer", - ID: 2000, - Protocol: "HTTP", - Port: 80, - Algorithm: "RANDOM", - Status: ACTIVE, - Timeout: 30, - ConnectionLogging: ConnectionLogging{Enabled: true}, - VIPs: []vips.VIP{ - vips.VIP{ - ID: 1000, - Address: "206.10.10.210", - Type: "PUBLIC", - Version: "IPV4", - }, - }, - Nodes: []nodes.Node{ - nodes.Node{ - Address: "10.1.1.1", - ID: 1041, - Port: 80, - Status: "ONLINE", - Condition: "ENABLED", - }, - nodes.Node{ - Address: "10.1.1.2", - ID: 1411, - Port: 80, - Status: "ONLINE", - Condition: "ENABLED", - }, - }, - SessionPersistence: sessions.SessionPersistence{Type: "HTTP_COOKIE"}, - ConnectionThrottle: throttle.ConnectionThrottle{MaxConnections: 100}, - Cluster: Cluster{Name: "c1.dfw1"}, - Created: Datetime{Time: toTime(t, ts1)}, - Updated: Datetime{Time: toTime(t, ts2)}, - SourceAddrs: SourceAddrs{ - IPv4Public: "10.12.99.28", - IPv4Private: "10.0.0.0", - IPv6Public: "2001:4801:79f1:1::1/64", - }, - } - - th.AssertDeepEquals(t, expected, lb) - th.AssertNoErr(t, err) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateLBResponse(t, id1) - - opts := UpdateOpts{ - Name: "a-new-loadbalancer", - Protocol: "TCP", - HalfClosed: gophercloud.Enabled, - Algorithm: "RANDOM", - Port: 8080, - Timeout: 100, - HTTPSRedirect: gophercloud.Disabled, - } - - err := Update(client.ServiceClient(), id1, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestListProtocols(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListProtocolsResponse(t) - - count := 0 - - err := ListProtocols(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractProtocols(page) - th.AssertNoErr(t, err) - - expected := []Protocol{ - Protocol{Name: "DNS_TCP", Port: 53}, - Protocol{Name: "DNS_UDP", Port: 53}, - Protocol{Name: "FTP", Port: 21}, - Protocol{Name: "HTTP", Port: 80}, - Protocol{Name: "HTTPS", Port: 443}, - Protocol{Name: "IMAPS", Port: 993}, - Protocol{Name: "IMAPv4", Port: 143}, - } - - th.CheckDeepEquals(t, expected[0:7], actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestListAlgorithms(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListAlgorithmsResponse(t) - - count := 0 - - err := ListAlgorithms(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractAlgorithms(page) - th.AssertNoErr(t, err) - - expected := []Algorithm{ - Algorithm{Name: "LEAST_CONNECTIONS"}, - Algorithm{Name: "RANDOM"}, - Algorithm{Name: "ROUND_ROBIN"}, - Algorithm{Name: "WEIGHTED_LEAST_CONNECTIONS"}, - Algorithm{Name: "WEIGHTED_ROUND_ROBIN"}, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestIsLoggingEnabled(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetLoggingResponse(t, id1) - - res, err := IsLoggingEnabled(client.ServiceClient(), id1) - th.AssertNoErr(t, err) - th.AssertEquals(t, true, res) -} - -func TestEnablingLogging(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockEnableLoggingResponse(t, id1) - - err := EnableLogging(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDisablingLogging(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDisableLoggingResponse(t, id1) - - err := DisableLogging(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGetErrorPage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetErrorPageResponse(t, id1) - - content, err := GetErrorPage(client.ServiceClient(), id1).Extract() - th.AssertNoErr(t, err) - - expected := &ErrorPage{Content: "DEFAULT ERROR PAGE"} - th.AssertDeepEquals(t, expected, content) -} - -func TestSetErrorPage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockSetErrorPageResponse(t, id1) - - html := "New error page" - content, err := SetErrorPage(client.ServiceClient(), id1, html).Extract() - th.AssertNoErr(t, err) - - expected := &ErrorPage{Content: html} - th.AssertDeepEquals(t, expected, content) -} - -func TestDeleteErrorPage(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteErrorPageResponse(t, id1) - - err := DeleteErrorPage(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGetStats(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetStatsResponse(t, id1) - - content, err := GetStats(client.ServiceClient(), id1).Extract() - th.AssertNoErr(t, err) - - expected := &Stats{ - ConnectTimeout: 10, - ConnectError: 20, - ConnectFailure: 30, - DataTimedOut: 40, - KeepAliveTimedOut: 50, - MaxConnections: 60, - CurrentConnections: 40, - SSLConnectTimeout: 10, - SSLConnectError: 20, - SSLConnectFailure: 30, - SSLDataTimedOut: 40, - SSLKeepAliveTimedOut: 50, - SSLMaxConnections: 60, - SSLCurrentConnections: 40, - } - th.AssertDeepEquals(t, expected, content) -} - -func TestIsCached(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetCachingResponse(t, id1) - - res, err := IsContentCached(client.ServiceClient(), id1) - th.AssertNoErr(t, err) - th.AssertEquals(t, true, res) -} - -func TestEnablingCaching(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockEnableCachingResponse(t, id1) - - err := EnableCaching(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDisablingCaching(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDisableCachingResponse(t, id1) - - err := DisableCaching(client.ServiceClient(), id1).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/monitors/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/monitors/requests_test.go deleted file mode 100644 index 76a60db7f45..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/monitors/requests_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package monitors - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const lbID = 12345 - -func TestUpdateCONNECT(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateConnectResponse(t, lbID) - - opts := UpdateConnectMonitorOpts{ - AttemptLimit: 3, - Delay: 10, - Timeout: 10, - } - - err := Update(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestUpdateHTTP(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateHTTPResponse(t, lbID) - - opts := UpdateHTTPMonitorOpts{ - AttemptLimit: 3, - Delay: 10, - Timeout: 10, - BodyRegex: "{regex}", - Path: "/foo", - StatusRegex: "200", - Type: HTTPS, - } - - err := Update(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetResponse(t, lbID) - - m, err := Get(client.ServiceClient(), lbID).Extract() - th.AssertNoErr(t, err) - - expected := &Monitor{ - Type: CONNECT, - Delay: 10, - Timeout: 10, - AttemptLimit: 3, - } - - th.AssertDeepEquals(t, expected, m) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID) - - err := Delete(client.ServiceClient(), lbID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/nodes/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/nodes/requests_test.go deleted file mode 100644 index a964af8f90d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/nodes/requests_test.go +++ /dev/null @@ -1,243 +0,0 @@ -package nodes - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - lbID = 12345 - nodeID = 67890 - nodeID2 = 67891 -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListResponse(t, lbID) - - count := 0 - - err := List(client.ServiceClient(), lbID, nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNodes(page) - th.AssertNoErr(t, err) - - expected := []Node{ - Node{ - ID: 410, - Address: "10.1.1.1", - Port: 80, - Condition: ENABLED, - Status: ONLINE, - Weight: 3, - Type: PRIMARY, - }, - Node{ - ID: 411, - Address: "10.1.1.2", - Port: 80, - Condition: ENABLED, - Status: ONLINE, - Weight: 8, - Type: SECONDARY, - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateResponse(t, lbID) - - opts := CreateOpts{ - CreateOpt{ - Address: "10.2.2.3", - Port: 80, - Condition: ENABLED, - Type: PRIMARY, - }, - CreateOpt{ - Address: "10.2.2.4", - Port: 81, - Condition: ENABLED, - Type: SECONDARY, - }, - } - - page := Create(client.ServiceClient(), lbID, opts) - - actual, err := page.ExtractNodes() - th.AssertNoErr(t, err) - - expected := []Node{ - Node{ - ID: 185, - Address: "10.2.2.3", - Port: 80, - Condition: ENABLED, - Status: ONLINE, - Weight: 1, - Type: PRIMARY, - }, - Node{ - ID: 186, - Address: "10.2.2.4", - Port: 81, - Condition: ENABLED, - Status: ONLINE, - Weight: 1, - Type: SECONDARY, - }, - } - - th.CheckDeepEquals(t, expected, actual) -} - -func TestCreateErr(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateErrResponse(t, lbID) - - opts := CreateOpts{ - CreateOpt{ - Address: "10.2.2.3", - Port: 80, - Condition: ENABLED, - Type: PRIMARY, - }, - CreateOpt{ - Address: "10.2.2.4", - Port: 81, - Condition: ENABLED, - Type: SECONDARY, - }, - } - - page := Create(client.ServiceClient(), lbID, opts) - - actual, err := page.ExtractNodes() - if err == nil { - t.Fatal("Did not receive expected error from ExtractNodes") - } - if actual != nil { - t.Fatalf("Received non-nil result from failed ExtractNodes: %#v", actual) - } -} - -func TestBulkDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - ids := []int{nodeID, nodeID2} - - mockBatchDeleteResponse(t, lbID, ids) - - err := BulkDelete(client.ServiceClient(), lbID, ids).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetResponse(t, lbID, nodeID) - - node, err := Get(client.ServiceClient(), lbID, nodeID).Extract() - th.AssertNoErr(t, err) - - expected := &Node{ - ID: 410, - Address: "10.1.1.1", - Port: 80, - Condition: ENABLED, - Status: ONLINE, - Weight: 12, - Type: PRIMARY, - } - - th.AssertDeepEquals(t, expected, node) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateResponse(t, lbID, nodeID) - - opts := UpdateOpts{ - Weight: gophercloud.IntToPointer(10), - Condition: DRAINING, - Type: SECONDARY, - } - - err := Update(client.ServiceClient(), lbID, nodeID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID, nodeID) - - err := Delete(client.ServiceClient(), lbID, nodeID).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestListEvents(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListEventsResponse(t, lbID) - - count := 0 - - pager := ListEvents(client.ServiceClient(), lbID, ListEventsOpts{}) - - err := pager.EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNodeEvents(page) - th.AssertNoErr(t, err) - - expected := []NodeEvent{ - NodeEvent{ - DetailedMessage: "Node is ok", - NodeID: 373, - ID: 7, - Type: "UPDATE_NODE", - Description: "Node '373' status changed to 'ONLINE' for load balancer '323'", - Category: "UPDATE", - Severity: "INFO", - RelativeURI: "/406271/loadbalancers/323/nodes/373/events", - AccountID: 406271, - LoadBalancerID: 323, - Title: "Node Status Updated", - Author: "Rackspace Cloud", - Created: "10-30-2012 10:18:23", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/sessions/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/sessions/requests_test.go deleted file mode 100644 index f319e540bb3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/sessions/requests_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package sessions - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const lbID = 12345 - -func TestEnable(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockEnableResponse(t, lbID) - - opts := CreateOpts{Type: HTTPCOOKIE} - err := Enable(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetResponse(t, lbID) - - sp, err := Get(client.ServiceClient(), lbID).Extract() - th.AssertNoErr(t, err) - - expected := &SessionPersistence{Type: HTTPCOOKIE} - th.AssertDeepEquals(t, expected, sp) -} - -func TestDisable(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDisableResponse(t, lbID) - - err := Disable(client.ServiceClient(), lbID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/ssl/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/ssl/requests_test.go deleted file mode 100644 index fb14c4a28d5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/ssl/requests_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package ssl - -import ( - "testing" - - "github.com/rackspace/gophercloud" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - lbID = 12345 - certID = 67890 -) - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetResponse(t, lbID) - - sp, err := Get(client.ServiceClient(), lbID).Extract() - th.AssertNoErr(t, err) - - expected := &SSLTermConfig{ - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - Enabled: true, - SecureTrafficOnly: false, - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - SecurePort: 443, - } - th.AssertDeepEquals(t, expected, sp) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateResponse(t, lbID) - - opts := UpdateOpts{ - Enabled: gophercloud.Enabled, - SecurePort: 443, - SecureTrafficOnly: gophercloud.Disabled, - PrivateKey: "foo", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - err := Update(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID) - - err := Delete(client.ServiceClient(), lbID).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestListCerts(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListCertsResponse(t, lbID) - - count := 0 - - err := ListCerts(client.ServiceClient(), lbID).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractCerts(page) - th.AssertNoErr(t, err) - - expected := []Certificate{ - Certificate{ID: 123, HostName: "rackspace.com"}, - Certificate{ID: 124, HostName: "*.rackspace.com"}, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreateCert(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockAddCertResponse(t, lbID) - - opts := CreateCertOpts{ - HostName: "rackspace.com", - PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAwIudSMpRZx7TS0/AtDVX3DgXwLD9g+XrNaoazlhwhpYALgzJ\nLAbAnOxT6OT0gTpkPus/B7QhW6y6Auf2cdBeW31XoIwPsSoyNhxgErGBxzNARRB9\nlI1HCa1ojFrcULluj4W6rpaOycI5soDBJiJHin/hbZBPZq6vhPCuNP7Ya48Zd/2X\nCQ9ft3XKfmbs1SdrdROIhigse/SGRbMrCorn/vhNIuohr7yOlHG3GcVcUI9k6ZSZ\nBbqF+ZA4ApSF/Q6/cumieEgofhkYbx5fg02s9Jwr4IWnIR2bSHs7UQ6sVgKYzjs7\nPd3Unpa74jFw6/H6shABoO2CIYLotGmQbFgnpwIDAQABAoIBAQCBCQ+PCIclJHNV\ntUzfeCA5ZR4F9JbxHdRTUnxEbOB8UWotckQfTScoAvj4yvdQ42DrCZxj/UOdvFOs\nPufZvlp91bIz1alugWjE+p8n5+2hIaegoTyHoWZKBfxak0myj5KYfHZvKlbmv1ML\nXV4TwEVRfAIG+v87QTY/UUxuF5vR+BpKIbgUJLfPUFFvJUdl84qsJ44pToxaYUd/\nh5YAGC00U4ay1KVSAUnTkkPNZ0lPG/rWU6w6WcTvNRLMd8DzFLTKLOgQfHhbExAF\n+sXPWjWSzbBRP1O7fHqq96QQh4VFiY/7w9W+sDKQyV6Ul17OSXs6aZ4f+lq4rJTI\n1FG96YiBAoGBAO1tiH0h1oWDBYfJB3KJJ6CQQsDGwtHo/DEgznFVP4XwEVbZ98Ha\nBfBCn3sAybbaikyCV1Hwj7kfHMZPDHbrcUSFX7quu/2zPK+wO3lZKXSyu4YsguSa\nRedInN33PpdnlPhLyQdWSuD5sVHJDF6xn22vlyxeILH3ooLg2WOFMPmVAoGBAM+b\nUG/a7iyfpAQKYyuFAsXz6SeFaDY+ZYeX45L112H8Pu+Ie/qzon+bzLB9FIH8GP6+\nQpQgmm/p37U2gD1zChUv7iW6OfQBKk9rWvMpfRF6d7YHquElejhizfTZ+ntBV/VY\ndOYEczxhrdW7keLpatYaaWUy/VboRZmlz/9JGqVLAoGAHfqNmFc0cgk4IowEj7a3\ntTNh6ltub/i+FynwRykfazcDyXaeLPDtfQe8gVh5H8h6W+y9P9BjJVnDVVrX1RAn\nbiJ1EupLPF5sVDapW8ohTOXgfbGTGXBNUUW+4Nv+IDno+mz/RhjkPYHpnM0I7c/5\ntGzOZsC/2hjNgT8I0+MWav0CgYEAuULdJeQVlKalI6HtW2Gn1uRRVJ49H+LQkY6e\nW3+cw2jo9LI0CMWSphNvNrN3wIMp/vHj0fHCP0pSApDvIWbuQXfzKaGko7UCf7rK\nf6GvZRCHkV4IREBAb97j8bMvThxClMNqFfU0rFZyXP+0MOyhFQyertswrgQ6T+Fi\n2mnvKD8CgYAmJHP3NTDRMoMRyAzonJ6nEaGUbAgNmivTaUWMe0+leCvAdwD89gzC\nTKbm3eDUg/6Va3X6ANh3wsfIOe4RXXxcbcFDk9R4zO2M5gfLSjYm5Q87EBZ2hrdj\nM2gLI7dt6thx0J8lR8xRHBEMrVBdgwp0g1gQzo5dAV88/kpkZVps8Q==\n-----END RSA PRIVATE KEY-----\n", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - - cm, err := CreateCert(client.ServiceClient(), lbID, opts).Extract() - th.AssertNoErr(t, err) - - expected := &Certificate{ - ID: 123, - HostName: "rackspace.com", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - th.AssertDeepEquals(t, expected, cm) -} - -func TestGetCertMapping(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetCertResponse(t, lbID, certID) - - sp, err := GetCert(client.ServiceClient(), lbID, certID).Extract() - th.AssertNoErr(t, err) - - expected := &Certificate{ - ID: 123, - HostName: "rackspace.com", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - th.AssertDeepEquals(t, expected, sp) -} - -func TestUpdateCert(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockUpdateCertResponse(t, lbID, certID) - - opts := UpdateCertOpts{ - HostName: "rackspace.com", - PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAwIudSMpRZx7TS0/AtDVX3DgXwLD9g+XrNaoazlhwhpYALgzJ\nLAbAnOxT6OT0gTpkPus/B7QhW6y6Auf2cdBeW31XoIwPsSoyNhxgErGBxzNARRB9\nlI1HCa1ojFrcULluj4W6rpaOycI5soDBJiJHin/hbZBPZq6vhPCuNP7Ya48Zd/2X\nCQ9ft3XKfmbs1SdrdROIhigse/SGRbMrCorn/vhNIuohr7yOlHG3GcVcUI9k6ZSZ\nBbqF+ZA4ApSF/Q6/cumieEgofhkYbx5fg02s9Jwr4IWnIR2bSHs7UQ6sVgKYzjs7\nPd3Unpa74jFw6/H6shABoO2CIYLotGmQbFgnpwIDAQABAoIBAQCBCQ+PCIclJHNV\ntUzfeCA5ZR4F9JbxHdRTUnxEbOB8UWotckQfTScoAvj4yvdQ42DrCZxj/UOdvFOs\nPufZvlp91bIz1alugWjE+p8n5+2hIaegoTyHoWZKBfxak0myj5KYfHZvKlbmv1ML\nXV4TwEVRfAIG+v87QTY/UUxuF5vR+BpKIbgUJLfPUFFvJUdl84qsJ44pToxaYUd/\nh5YAGC00U4ay1KVSAUnTkkPNZ0lPG/rWU6w6WcTvNRLMd8DzFLTKLOgQfHhbExAF\n+sXPWjWSzbBRP1O7fHqq96QQh4VFiY/7w9W+sDKQyV6Ul17OSXs6aZ4f+lq4rJTI\n1FG96YiBAoGBAO1tiH0h1oWDBYfJB3KJJ6CQQsDGwtHo/DEgznFVP4XwEVbZ98Ha\nBfBCn3sAybbaikyCV1Hwj7kfHMZPDHbrcUSFX7quu/2zPK+wO3lZKXSyu4YsguSa\nRedInN33PpdnlPhLyQdWSuD5sVHJDF6xn22vlyxeILH3ooLg2WOFMPmVAoGBAM+b\nUG/a7iyfpAQKYyuFAsXz6SeFaDY+ZYeX45L112H8Pu+Ie/qzon+bzLB9FIH8GP6+\nQpQgmm/p37U2gD1zChUv7iW6OfQBKk9rWvMpfRF6d7YHquElejhizfTZ+ntBV/VY\ndOYEczxhrdW7keLpatYaaWUy/VboRZmlz/9JGqVLAoGAHfqNmFc0cgk4IowEj7a3\ntTNh6ltub/i+FynwRykfazcDyXaeLPDtfQe8gVh5H8h6W+y9P9BjJVnDVVrX1RAn\nbiJ1EupLPF5sVDapW8ohTOXgfbGTGXBNUUW+4Nv+IDno+mz/RhjkPYHpnM0I7c/5\ntGzOZsC/2hjNgT8I0+MWav0CgYEAuULdJeQVlKalI6HtW2Gn1uRRVJ49H+LQkY6e\nW3+cw2jo9LI0CMWSphNvNrN3wIMp/vHj0fHCP0pSApDvIWbuQXfzKaGko7UCf7rK\nf6GvZRCHkV4IREBAb97j8bMvThxClMNqFfU0rFZyXP+0MOyhFQyertswrgQ6T+Fi\n2mnvKD8CgYAmJHP3NTDRMoMRyAzonJ6nEaGUbAgNmivTaUWMe0+leCvAdwD89gzC\nTKbm3eDUg/6Va3X6ANh3wsfIOe4RXXxcbcFDk9R4zO2M5gfLSjYm5Q87EBZ2hrdj\nM2gLI7dt6thx0J8lR8xRHBEMrVBdgwp0g1gQzo5dAV88/kpkZVps8Q==\n-----END RSA PRIVATE KEY-----\n", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - - cm, err := UpdateCert(client.ServiceClient(), lbID, certID, opts).Extract() - th.AssertNoErr(t, err) - - expected := &Certificate{ - ID: 123, - HostName: "rackspace.com", - Certificate: "-----BEGIN CERTIFICATE-----\nMIIEXTCCA0WgAwIBAgIGATTEAjK3MA0GCSqGSIb3DQEBBQUAMIGDMRkwFwYDVQQD\nExBUZXN0IENBIFNUdWIgS2V5MRcwFQYDVQQLEw5QbGF0Zm9ybSBMYmFhczEaMBgG\nA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFDASBgNVBAcTC1NhbiBBbnRvbmlvMQ4w\nDAYDVQQIEwVUZXhhczELMAkGA1UEBhMCVVMwHhcNMTIwMTA5MTk0NjQ1WhcNMTQw\nMTA4MTk0NjQ1WjCBgjELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMRQwEgYD\nVQQHEwtTYW4gQW50b25pbzEaMBgGA1UEChMRUmFja3NwYWNlIEhvc3RpbmcxFzAV\nBgNVBAsTDlBsYXRmb3JtIExiYWFzMRgwFgYDVQQDEw9UZXN0IENsaWVudCBLZXkw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDAi51IylFnHtNLT8C0NVfc\nOBfAsP2D5es1qhrOWHCGlgAuDMksBsCc7FPo5PSBOmQ+6z8HtCFbrLoC5/Zx0F5b\nfVegjA+xKjI2HGASsYHHM0BFEH2UjUcJrWiMWtxQuW6Phbqulo7JwjmygMEmIkeK\nf+FtkE9mrq+E8K40/thrjxl3/ZcJD1+3dcp+ZuzVJ2t1E4iGKCx79IZFsysKiuf+\n+E0i6iGvvI6UcbcZxVxQj2TplJkFuoX5kDgClIX9Dr9y6aJ4SCh+GRhvHl+DTaz0\nnCvghachHZtIeztRDqxWApjOOzs93dSelrviMXDr8fqyEAGg7YIhgui0aZBsWCen\nAgMBAAGjgdUwgdIwgbAGA1UdIwSBqDCBpYAUNpx1Pc6cGA7KqEwHMmHBTZMA7lSh\ngYmkgYYwgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVU4IBATAd\nBgNVHQ4EFgQULueOfsjZZOHwJHZwBy6u0swnpccwDQYJKoZIhvcNAQEFBQADggEB\nAFNuqSVUaotUJoWDv4z7Kbi6JFpTjDht5ORw4BdVYlRD4h9DACAFzPrPV2ym/Osp\nhNMdZq6msZku7MdOSQVhdeGWrSNk3M8O9Hg7cVzPNXOF3iNoo3irQ5tURut44xs4\nWw5YWQqS9WyUY5snD8tm7Y1rQTPfhg+678xIq/zWCv/u+FSnfVv1nlhLVQkEeG/Y\ngh1uMaTIpUKTGEjIAGtpGP7wwIcXptR/HyfzhTUSTaWc1Ef7zoKT9LL5z3IV1hC2\njVWz+RwYs98LjMuksJFoHqRfWyYhCIym0jb6GTwaEmpxAjc+d7OLNQdnoEGoUYGP\nYjtfkRYg265ESMA+Kww4Xy8=\n-----END CERTIFICATE-----\n", - IntCertificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzEZMBcGA1UEAxMQVGVz\ndCBDQSBTVHViIEtleTEXMBUGA1UECxMOUGxhdGZvcm0gTGJhYXMxGjAYBgNVBAoT\nEVJhY2tzcGFjZSBIb3N0aW5nMRQwEgYDVQQHEwtTYW4gQW50b25pbzEOMAwGA1UE\nCBMFVGV4YXMxCzAJBgNVBAYTAlVTMB4XDTEyMDEwOTE5NDU0OVoXDTE0MDEwODE5\nNDU0OVowgYMxGTAXBgNVBAMTEFRlc3QgQ0EgU1R1YiBLZXkxFzAVBgNVBAsTDlBs\nYXRmb3JtIExiYWFzMRowGAYDVQQKExFSYWNrc3BhY2UgSG9zdGluZzEUMBIGA1UE\nBxMLU2FuIEFudG9uaW8xDjAMBgNVBAgTBVRleGFzMQswCQYDVQQGEwJVUzCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANNh55lwTVwQvNoEZjq1zGdYz9jA\nXXdjizn8AJhjHLOAallfPtvCfTEgKanhdoyz5FnhQE8HbDAop/KNS1lN2UMvdl5f\nZNLTSjJrNtedqxQwxN/i3bpyBxNVejUH2NjV1mmyj+5CJYwCzWalvI/gLPq/A3as\nO2EQqtf3U8unRgn0zXLRdYxV9MrUzNAmdipPNvNrsVdrCgA42rgF/8KsyRVQfJCX\nfN7PGCfrsC3YaUvhymraWxNnXIzMYTNa9wEeBZLUw8SlEtpa1Zsvui+TPXu3USNZ\nVnWH8Lb6ENlnoX0VBwo62fjOG3JzhNKoJawi3bRqyDdINOvafr7iPrrs/T8CAwEA\nAaMyMDAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUNpx1Pc6cGA7KqEwHMmHB\nTZMA7lQwDQYJKoZIhvcNAQEFBQADggEBAMoRgH3iTG3t317viLKoY+lNMHUgHuR7\nb3mn9MidJKyYVewe6hCDIN6WY4fUojmMW9wFJWJIo0hRMNHL3n3tq8HP2j20Mxy8\nacPdfGZJa+jiBw72CrIGdobKaFduIlIEDBA1pNdZIJ+EulrtqrMesnIt92WaypIS\n8JycbIgDMCiyC0ENHEk8UWlC6429c7OZAsplMTbHME/1R4btxjkdfrYZJjdJ2yL2\n8cjZDUDMCPTdW/ycP07Gkq30RB5tACB5aZdaCn2YaKC8FsEdhff4X7xEOfOEHWEq\nSRxADDj8Lx1MT6QpR07hCiDyHfTCtbqzI0iGjX63Oh7xXSa0f+JVTa8=\n-----END CERTIFICATE-----\n", - } - th.AssertDeepEquals(t, expected, cm) -} - -func TestDeleteCert(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteCertResponse(t, lbID, certID) - - err := DeleteCert(client.ServiceClient(), lbID, certID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/throttle/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/throttle/requests_test.go deleted file mode 100644 index 6e9703ffce3..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/throttle/requests_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package throttle - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const lbID = 12345 - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateResponse(t, lbID) - - opts := CreateOpts{MaxConnections: 200} - err := Create(client.ServiceClient(), lbID, opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockGetResponse(t, lbID) - - sp, err := Get(client.ServiceClient(), lbID).Extract() - th.AssertNoErr(t, err) - - expected := &ConnectionThrottle{MaxConnections: 100} - th.AssertDeepEquals(t, expected, sp) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID) - - err := Delete(client.ServiceClient(), lbID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/vips/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/vips/requests_test.go deleted file mode 100644 index 74ac4617381..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/lb/v1/vips/requests_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package vips - -import ( - "testing" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" -) - -const ( - lbID = 12345 - vipID = 67890 - vipID2 = 67891 -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockListResponse(t, lbID) - - count := 0 - - err := List(client.ServiceClient(), lbID).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractVIPs(page) - th.AssertNoErr(t, err) - - expected := []VIP{ - VIP{ID: 1000, Address: "206.10.10.210", Type: "PUBLIC"}, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - th.AssertNoErr(t, err) - th.AssertEquals(t, 1, count) -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockCreateResponse(t, lbID) - - opts := CreateOpts{ - Type: "PUBLIC", - Version: "IPV6", - } - - vip, err := Create(client.ServiceClient(), lbID, opts).Extract() - th.AssertNoErr(t, err) - - expected := &VIP{ - Address: "fd24:f480:ce44:91bc:1af2:15ff:0000:0002", - ID: 9000134, - Type: "PUBLIC", - Version: "IPV6", - } - - th.CheckDeepEquals(t, expected, vip) -} - -func TestBulkDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - ids := []int{vipID, vipID2} - - mockBatchDeleteResponse(t, lbID, ids) - - err := BulkDelete(client.ServiceClient(), lbID, ids).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - mockDeleteResponse(t, lbID, vipID) - - err := Delete(client.ServiceClient(), lbID, vipID).ExtractErr() - th.AssertNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/networks/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/networks/delegate_test.go deleted file mode 100644 index 0b3a6b15eb4..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/networks/delegate_test.go +++ /dev/null @@ -1,285 +0,0 @@ -package networks - -import ( - "fmt" - "net/http" - "testing" - - os "github.com/rackspace/gophercloud/openstack/networking/v2/networks" - "github.com/rackspace/gophercloud/pagination" - fake "github.com/rackspace/gophercloud/rackspace/networking/v2/common" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "networks": [ - { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - }, - { - "status": "ACTIVE", - "subnets": [ - "08eae331-0402-425a-923c-34f7cfe39c1b" - ], - "name": "private", - "admin_state_up": true, - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "shared": true, - "id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324" - } - ] -} - `) - }) - - client := fake.ServiceClient() - count := 0 - - List(client, os.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractNetworks(page) - if err != nil { - t.Errorf("Failed to extract networks: %v", err) - return false, err - } - - expected := []os.Network{ - os.Network{ - Status: "ACTIVE", - Subnets: []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"}, - Name: "private-network", - AdminStateUp: true, - TenantID: "4fd44f30292945e481c7b8a0c8908869", - Shared: true, - ID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - }, - os.Network{ - Status: "ACTIVE", - Subnets: []string{"08eae331-0402-425a-923c-34f7cfe39c1b"}, - Name: "private", - AdminStateUp: true, - TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e", - Shared: true, - ID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [ - "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - ], - "name": "private-network", - "admin_state_up": true, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{"54d6f61d-db07-451c-9ab3-b9609b6b6f0b"}) - th.AssertEquals(t, n.Name, "private-network") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertEquals(t, n.Shared, true) - th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [], - "name": "net1", - "admin_state_up": true, - "tenant_id": "9bacb3c5d39d41a79512987f338cf177", - "shared": false, - "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c" - } -} - `) - }) - - iTrue := true - options := os.CreateOpts{Name: "sample_network", AdminStateUp: &iTrue} - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertDeepEquals(t, n.Subnets, []string{}) - th.AssertEquals(t, n.Name, "net1") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.TenantID, "9bacb3c5d39d41a79512987f338cf177") - th.AssertEquals(t, n.Shared, false) - th.AssertEquals(t, n.ID, "4e8e5957-649f-477b-9e5b-f1f75b21c03c") -} - -func TestCreateWithOptionalFields(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true, - "shared": true, - "tenant_id": "12345" - } -} - `) - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, ` -{ - "network": { - "name": "sample_network", - "admin_state_up": true, - "shared": true, - "tenant_id": "12345" - } -} - `) - }) - - iTrue := true - options := os.CreateOpts{Name: "sample_network", AdminStateUp: &iTrue, Shared: &iTrue, TenantID: "12345"} - _, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "network": { - "name": "new_network_name", - "admin_state_up": false, - "shared": true - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "network": { - "status": "ACTIVE", - "subnets": [], - "name": "new_network_name", - "admin_state_up": false, - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "shared": true, - "id": "4e8e5957-649f-477b-9e5b-f1f75b21c03c" - } -} - `) - }) - - iTrue := true - options := os.UpdateOpts{Name: "new_network_name", AdminStateUp: os.Down, Shared: &iTrue} - n, err := Update(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Name, "new_network_name") - th.AssertEquals(t, n.AdminStateUp, false) - th.AssertEquals(t, n.Shared, true) - th.AssertEquals(t, n.ID, "4e8e5957-649f-477b-9e5b-f1f75b21c03c") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/networks/4e8e5957-649f-477b-9e5b-f1f75b21c03c", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4e8e5957-649f-477b-9e5b-f1f75b21c03c") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/ports/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/ports/delegate_test.go deleted file mode 100644 index f53ff595a04..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/ports/delegate_test.go +++ /dev/null @@ -1,322 +0,0 @@ -package ports - -import ( - "fmt" - "net/http" - "testing" - - os "github.com/rackspace/gophercloud/openstack/networking/v2/ports" - "github.com/rackspace/gophercloud/pagination" - fake "github.com/rackspace/gophercloud/rackspace/networking/v2/common" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/ports", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "ports": [ - { - "status": "ACTIVE", - "binding:host_id": "devstack", - "name": "", - "admin_state_up": true, - "network_id": "70c1db1f-b701-45bd-96e0-a313ee3430b3", - "tenant_id": "", - "device_owner": "network:router_gateway", - "mac_address": "fa:16:3e:58:42:ed", - "fixed_ips": [ - { - "subnet_id": "008ba151-0b8c-4a67-98b5-0d2b87666062", - "ip_address": "172.24.4.2" - } - ], - "id": "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b", - "security_groups": [], - "device_id": "9ae135f4-b6e0-4dad-9e91-3c223e385824" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), os.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractPorts(page) - if err != nil { - t.Errorf("Failed to extract subnets: %v", err) - return false, nil - } - - expected := []os.Port{ - os.Port{ - Status: "ACTIVE", - Name: "", - AdminStateUp: true, - NetworkID: "70c1db1f-b701-45bd-96e0-a313ee3430b3", - TenantID: "", - DeviceOwner: "network:router_gateway", - MACAddress: "fa:16:3e:58:42:ed", - FixedIPs: []os.IP{ - os.IP{ - SubnetID: "008ba151-0b8c-4a67-98b5-0d2b87666062", - IPAddress: "172.24.4.2", - }, - }, - ID: "d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b", - SecurityGroups: []string{}, - DeviceID: "9ae135f4-b6e0-4dad-9e91-3c223e385824", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/ports/46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "ACTIVE", - "name": "", - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "7e02058126cc4950b75f9970368ba177", - "device_owner": "network:router_interface", - "mac_address": "fa:16:3e:23:fd:d7", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.1" - } - ], - "id": "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2", - "security_groups": [], - "device_id": "5e3898d7-11be-483e-9732-b2f5eccd2b2e" - } -} - `) - }) - - n, err := Get(fake.ServiceClient(), "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertEquals(t, n.Name, "") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.NetworkID, "a87cc70a-3e15-4acf-8205-9b711a3531b7") - th.AssertEquals(t, n.TenantID, "7e02058126cc4950b75f9970368ba177") - th.AssertEquals(t, n.DeviceOwner, "network:router_interface") - th.AssertEquals(t, n.MACAddress, "fa:16:3e:23:fd:d7") - th.AssertDeepEquals(t, n.FixedIPs, []os.IP{ - os.IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.1"}, - }) - th.AssertEquals(t, n.ID, "46d4bfb9-b26e-41f3-bd2e-e6dcc1ccedb2") - th.AssertDeepEquals(t, n.SecurityGroups, []string{}) - th.AssertEquals(t, n.Status, "ACTIVE") - th.AssertEquals(t, n.DeviceID, "5e3898d7-11be-483e-9732-b2f5eccd2b2e") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/ports", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "port": { - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "name": "private-port", - "admin_state_up": true, - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.2" - } - ], - "security_groups": ["foo"] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "DOWN", - "name": "private-port", - "allowed_address_pairs": [], - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "d6700c0c9ffa4f1cb322cd4a1f3906fa", - "device_owner": "", - "mac_address": "fa:16:3e:c9:cb:f0", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.2" - } - ], - "id": "65c0ee9f-d634-4522-8954-51021b570b0d", - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ], - "device_id": "" - } -} - `) - }) - - asu := true - options := os.CreateOpts{ - Name: "private-port", - AdminStateUp: &asu, - NetworkID: "a87cc70a-3e15-4acf-8205-9b711a3531b7", - FixedIPs: []os.IP{ - os.IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.2"}, - }, - SecurityGroups: []string{"foo"}, - } - n, err := Create(fake.ServiceClient(), options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, n.Status, "DOWN") - th.AssertEquals(t, n.Name, "private-port") - th.AssertEquals(t, n.AdminStateUp, true) - th.AssertEquals(t, n.NetworkID, "a87cc70a-3e15-4acf-8205-9b711a3531b7") - th.AssertEquals(t, n.TenantID, "d6700c0c9ffa4f1cb322cd4a1f3906fa") - th.AssertEquals(t, n.DeviceOwner, "") - th.AssertEquals(t, n.MACAddress, "fa:16:3e:c9:cb:f0") - th.AssertDeepEquals(t, n.FixedIPs, []os.IP{ - os.IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.2"}, - }) - th.AssertEquals(t, n.ID, "65c0ee9f-d634-4522-8954-51021b570b0d") - th.AssertDeepEquals(t, n.SecurityGroups, []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), os.CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/ports/65c0ee9f-d634-4522-8954-51021b570b0d", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "port": { - "name": "new_port_name", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.3" - } - ], - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "port": { - "status": "DOWN", - "name": "new_port_name", - "admin_state_up": true, - "network_id": "a87cc70a-3e15-4acf-8205-9b711a3531b7", - "tenant_id": "d6700c0c9ffa4f1cb322cd4a1f3906fa", - "device_owner": "", - "mac_address": "fa:16:3e:c9:cb:f0", - "fixed_ips": [ - { - "subnet_id": "a0304c3a-4f08-4c43-88af-d796509c97d2", - "ip_address": "10.0.0.3" - } - ], - "id": "65c0ee9f-d634-4522-8954-51021b570b0d", - "security_groups": [ - "f0ac4394-7e4a-4409-9701-ba8be283dbc3" - ], - "device_id": "" - } -} - `) - }) - - options := os.UpdateOpts{ - Name: "new_port_name", - FixedIPs: []os.IP{ - os.IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.3"}, - }, - SecurityGroups: []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}, - } - - s, err := Update(fake.ServiceClient(), "65c0ee9f-d634-4522-8954-51021b570b0d", options).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "new_port_name") - th.AssertDeepEquals(t, s.FixedIPs, []os.IP{ - os.IP{SubnetID: "a0304c3a-4f08-4c43-88af-d796509c97d2", IPAddress: "10.0.0.3"}, - }) - th.AssertDeepEquals(t, s.SecurityGroups, []string{"f0ac4394-7e4a-4409-9701-ba8be283dbc3"}) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/ports/65c0ee9f-d634-4522-8954-51021b570b0d", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "65c0ee9f-d634-4522-8954-51021b570b0d") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/groups/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/groups/delegate_test.go deleted file mode 100644 index 45cd3ba8d4c..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/groups/delegate_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package groups - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - osGroups "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/groups" - osRules "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` - { - "security_groups": [ - { - "description": "default", - "id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "name": "default", - "security_group_rules": [], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ] - } - `) - }) - - count := 0 - - List(fake.ServiceClient(), osGroups.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := osGroups.ExtractGroups(page) - if err != nil { - t.Errorf("Failed to extract secgroups: %v", err) - return false, err - } - - expected := []osGroups.SecGroup{ - osGroups.SecGroup{ - Description: "default", - ID: "85cc3048-abc3-43cc-89b3-377341426ac5", - Name: "default", - Rules: []osRules.SecGroupRule{}, - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - { - "security_group": { - "name": "new-webservers", - "description": "security group for webservers" - } - } - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` - { - "security_group": { - "description": "security group for webservers", - "id": "2076db17-a522-4506-91de-c6dd8e837028", - "name": "new-webservers", - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv4", - "id": "38ce2d8e-e8f1-48bd-83c2-d33cb9f50c3d", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "2076db17-a522-4506-91de-c6dd8e837028", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv6", - "id": "565b9502-12de-4ffd-91e9-68885cff6ae1", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "2076db17-a522-4506-91de-c6dd8e837028", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - } - `) - }) - - opts := osGroups.CreateOpts{Name: "new-webservers", Description: "security group for webservers"} - _, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups/85cc3048-abc3-43cc-89b3-377341426ac5", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` - { - "security_group": { - "description": "default", - "id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "name": "default", - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv4", - "id": "93aa42e5-80db-4581-9391-3a608bd0e448", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ], - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - } - `) - }) - - sg, err := Get(fake.ServiceClient(), "85cc3048-abc3-43cc-89b3-377341426ac5").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "default", sg.Description) - th.AssertEquals(t, "85cc3048-abc3-43cc-89b3-377341426ac5", sg.ID) - th.AssertEquals(t, "default", sg.Name) - th.AssertEquals(t, 2, len(sg.Rules)) - th.AssertEquals(t, "e4f50856753b4dc6afee5fa6b9b6c550", sg.TenantID) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-groups/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/rules/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/rules/delegate_test.go deleted file mode 100644 index 3563fbeaa6a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/security/rules/delegate_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package rules - -import ( - "fmt" - "net/http" - "testing" - - fake "github.com/rackspace/gophercloud/openstack/networking/v2/common" - osRules "github.com/rackspace/gophercloud/openstack/networking/v2/extensions/security/rules" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` - { - "security_group_rules": [ - { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - }, - { - "direction": "egress", - "ethertype": "IPv4", - "id": "93aa42e5-80db-4581-9391-3a608bd0e448", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - ] - } - `) - }) - - count := 0 - - List(fake.ServiceClient(), osRules.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := osRules.ExtractRules(page) - if err != nil { - t.Errorf("Failed to extract secrules: %v", err) - return false, err - } - - expected := []osRules.SecGroupRule{ - osRules.SecGroupRule{ - Direction: "egress", - EtherType: "IPv6", - ID: "3c0e45ff-adaf-4124-b083-bf390e5482ff", - PortRangeMax: 0, - PortRangeMin: 0, - Protocol: "", - RemoteGroupID: "", - RemoteIPPrefix: "", - SecGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - osRules.SecGroupRule{ - Direction: "egress", - EtherType: "IPv4", - ID: "93aa42e5-80db-4581-9391-3a608bd0e448", - PortRangeMax: 0, - PortRangeMin: 0, - Protocol: "", - RemoteGroupID: "", - RemoteIPPrefix: "", - SecGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - TenantID: "e4f50856753b4dc6afee5fa6b9b6c550", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - { - "security_group_rule": { - "direction": "ingress", - "port_range_min": 80, - "ethertype": "IPv4", - "port_range_max": 80, - "protocol": "tcp", - "remote_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "security_group_id": "a7734e61-b545-452d-a3cd-0189cbd9747a" - } - } - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` - { - "security_group_rule": { - "direction": "ingress", - "ethertype": "IPv4", - "id": "2bc0accf-312e-429a-956e-e4407625eb62", - "port_range_max": 80, - "port_range_min": 80, - "protocol": "tcp", - "remote_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "remote_ip_prefix": null, - "security_group_id": "a7734e61-b545-452d-a3cd-0189cbd9747a", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - } - `) - }) - - opts := osRules.CreateOpts{ - Direction: "ingress", - PortRangeMin: 80, - EtherType: "IPv4", - PortRangeMax: 80, - Protocol: "tcp", - RemoteGroupID: "85cc3048-abc3-43cc-89b3-377341426ac5", - SecGroupID: "a7734e61-b545-452d-a3cd-0189cbd9747a", - } - _, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), osRules.CreateOpts{Direction: "something"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), osRules.CreateOpts{Direction: osRules.DirIngress, EtherType: "something"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), osRules.CreateOpts{Direction: osRules.DirIngress, EtherType: osRules.Ether4}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - res = Create(fake.ServiceClient(), osRules.CreateOpts{Direction: osRules.DirIngress, EtherType: osRules.Ether4, SecGroupID: "something", Protocol: "foo"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules/3c0e45ff-adaf-4124-b083-bf390e5482ff", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` - { - "security_group_rule": { - "direction": "egress", - "ethertype": "IPv6", - "id": "3c0e45ff-adaf-4124-b083-bf390e5482ff", - "port_range_max": null, - "port_range_min": null, - "protocol": null, - "remote_group_id": null, - "remote_ip_prefix": null, - "security_group_id": "85cc3048-abc3-43cc-89b3-377341426ac5", - "tenant_id": "e4f50856753b4dc6afee5fa6b9b6c550" - } - } - `) - }) - - sr, err := Get(fake.ServiceClient(), "3c0e45ff-adaf-4124-b083-bf390e5482ff").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, "egress", sr.Direction) - th.AssertEquals(t, "IPv6", sr.EtherType) - th.AssertEquals(t, "3c0e45ff-adaf-4124-b083-bf390e5482ff", sr.ID) - th.AssertEquals(t, 0, sr.PortRangeMax) - th.AssertEquals(t, 0, sr.PortRangeMin) - th.AssertEquals(t, "", sr.Protocol) - th.AssertEquals(t, "", sr.RemoteGroupID) - th.AssertEquals(t, "", sr.RemoteIPPrefix) - th.AssertEquals(t, "85cc3048-abc3-43cc-89b3-377341426ac5", sr.SecGroupID) - th.AssertEquals(t, "e4f50856753b4dc6afee5fa6b9b6c550", sr.TenantID) -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/v2.0/security-group-rules/4ec89087-d057-4e2c-911f-60a3b47ee304", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "4ec89087-d057-4e2c-911f-60a3b47ee304") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/subnets/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/subnets/delegate_test.go deleted file mode 100644 index fafc6fb3020..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/networking/v2/subnets/delegate_test.go +++ /dev/null @@ -1,363 +0,0 @@ -package subnets - -import ( - "fmt" - "net/http" - "testing" - - os "github.com/rackspace/gophercloud/openstack/networking/v2/subnets" - "github.com/rackspace/gophercloud/pagination" - fake "github.com/rackspace/gophercloud/rackspace/networking/v2/common" - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/subnets", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnets": [ - { - "name": "private-subnet", - "enable_dhcp": true, - "network_id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "10.0.0.2", - "end": "10.0.0.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "10.0.0.1", - "cidr": "10.0.0.0/24", - "id": "08eae331-0402-425a-923c-34f7cfe39c1b" - }, - { - "name": "my_subnet", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.0.0.2", - "end": "192.255.255.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.0.0.1", - "cidr": "192.0.0.0/8", - "id": "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - } - ] -} - `) - }) - - count := 0 - - List(fake.ServiceClient(), os.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractSubnets(page) - if err != nil { - t.Errorf("Failed to extract subnets: %v", err) - return false, nil - } - - expected := []os.Subnet{ - os.Subnet{ - Name: "private-subnet", - EnableDHCP: true, - NetworkID: "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - TenantID: "26a7980765d0414dbc1fc1f88cdb7e6e", - DNSNameservers: []string{}, - AllocationPools: []os.AllocationPool{ - os.AllocationPool{ - Start: "10.0.0.2", - End: "10.0.0.254", - }, - }, - HostRoutes: []os.HostRoute{}, - IPVersion: 4, - GatewayIP: "10.0.0.1", - CIDR: "10.0.0.0/24", - ID: "08eae331-0402-425a-923c-34f7cfe39c1b", - }, - os.Subnet{ - Name: "my_subnet", - EnableDHCP: true, - NetworkID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - TenantID: "4fd44f30292945e481c7b8a0c8908869", - DNSNameservers: []string{}, - AllocationPools: []os.AllocationPool{ - os.AllocationPool{ - Start: "192.0.0.2", - End: "192.255.255.254", - }, - }, - HostRoutes: []os.HostRoute{}, - IPVersion: 4, - GatewayIP: "192.0.0.1", - CIDR: "192.0.0.0/8", - ID: "54d6f61d-db07-451c-9ab3-b9609b6b6f0b", - }, - } - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - - if count != 1 { - t.Errorf("Expected 1 page, got %d", count) - } -} - -func TestGet(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/subnets/54d6f61d-db07-451c-9ab3-b9609b6b6f0b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "my_subnet", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.0.0.2", - "end": "192.255.255.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.0.0.1", - "cidr": "192.0.0.0/8", - "id": "54d6f61d-db07-451c-9ab3-b9609b6b6f0b" - } -} - `) - }) - - s, err := Get(fake.ServiceClient(), "54d6f61d-db07-451c-9ab3-b9609b6b6f0b").Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "my_subnet") - th.AssertEquals(t, s.EnableDHCP, true) - th.AssertEquals(t, s.NetworkID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertEquals(t, s.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertDeepEquals(t, s.DNSNameservers, []string{}) - th.AssertDeepEquals(t, s.AllocationPools, []os.AllocationPool{ - os.AllocationPool{ - Start: "192.0.0.2", - End: "192.255.255.254", - }, - }) - th.AssertDeepEquals(t, s.HostRoutes, []os.HostRoute{}) - th.AssertEquals(t, s.IPVersion, 4) - th.AssertEquals(t, s.GatewayIP, "192.0.0.1") - th.AssertEquals(t, s.CIDR, "192.0.0.0/8") - th.AssertEquals(t, s.ID, "54d6f61d-db07-451c-9ab3-b9609b6b6f0b") -} - -func TestCreate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/subnets", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet": { - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "ip_version": 4, - "cidr": "192.168.199.0/24", - "dns_nameservers": ["foo"], - "allocation_pools": [ - { - "start": "192.168.199.2", - "end": "192.168.199.254" - } - ], - "host_routes": [{"destination":"","nexthop": "bar"}] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "", - "enable_dhcp": true, - "network_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22", - "tenant_id": "4fd44f30292945e481c7b8a0c8908869", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "192.168.199.2", - "end": "192.168.199.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "192.168.199.1", - "cidr": "192.168.199.0/24", - "id": "3b80198d-4f7b-4f77-9ef5-774d54e17126" - } -} - `) - }) - - opts := os.CreateOpts{ - NetworkID: "d32019d3-bc6e-4319-9c1d-6722fc136a22", - IPVersion: 4, - CIDR: "192.168.199.0/24", - AllocationPools: []os.AllocationPool{ - os.AllocationPool{ - Start: "192.168.199.2", - End: "192.168.199.254", - }, - }, - DNSNameservers: []string{"foo"}, - HostRoutes: []os.HostRoute{ - os.HostRoute{NextHop: "bar"}, - }, - } - s, err := Create(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "") - th.AssertEquals(t, s.EnableDHCP, true) - th.AssertEquals(t, s.NetworkID, "d32019d3-bc6e-4319-9c1d-6722fc136a22") - th.AssertEquals(t, s.TenantID, "4fd44f30292945e481c7b8a0c8908869") - th.AssertDeepEquals(t, s.DNSNameservers, []string{}) - th.AssertDeepEquals(t, s.AllocationPools, []os.AllocationPool{ - os.AllocationPool{ - Start: "192.168.199.2", - End: "192.168.199.254", - }, - }) - th.AssertDeepEquals(t, s.HostRoutes, []os.HostRoute{}) - th.AssertEquals(t, s.IPVersion, 4) - th.AssertEquals(t, s.GatewayIP, "192.168.199.1") - th.AssertEquals(t, s.CIDR, "192.168.199.0/24") - th.AssertEquals(t, s.ID, "3b80198d-4f7b-4f77-9ef5-774d54e17126") -} - -func TestRequiredCreateOpts(t *testing.T) { - res := Create(fake.ServiceClient(), os.CreateOpts{}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - - res = Create(fake.ServiceClient(), os.CreateOpts{NetworkID: "foo"}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } - - res = Create(fake.ServiceClient(), os.CreateOpts{NetworkID: "foo", CIDR: "bar", IPVersion: 40}) - if res.Err == nil { - t.Fatalf("Expected error, got none") - } -} - -func TestUpdate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/subnets/08eae331-0402-425a-923c-34f7cfe39c1b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Content-Type", "application/json") - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` -{ - "subnet": { - "name": "my_new_subnet", - "dns_nameservers": ["foo"], - "host_routes": [{"destination":"","nexthop": "bar"}] - } -} - `) - - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - - fmt.Fprintf(w, ` -{ - "subnet": { - "name": "my_new_subnet", - "enable_dhcp": true, - "network_id": "db193ab3-96e3-4cb3-8fc5-05f4296d0324", - "tenant_id": "26a7980765d0414dbc1fc1f88cdb7e6e", - "dns_nameservers": [], - "allocation_pools": [ - { - "start": "10.0.0.2", - "end": "10.0.0.254" - } - ], - "host_routes": [], - "ip_version": 4, - "gateway_ip": "10.0.0.1", - "cidr": "10.0.0.0/24", - "id": "08eae331-0402-425a-923c-34f7cfe39c1b" - } -} - `) - }) - - opts := os.UpdateOpts{ - Name: "my_new_subnet", - DNSNameservers: []string{"foo"}, - HostRoutes: []os.HostRoute{ - os.HostRoute{NextHop: "bar"}, - }, - } - s, err := Update(fake.ServiceClient(), "08eae331-0402-425a-923c-34f7cfe39c1b", opts).Extract() - th.AssertNoErr(t, err) - - th.AssertEquals(t, s.Name, "my_new_subnet") - th.AssertEquals(t, s.ID, "08eae331-0402-425a-923c-34f7cfe39c1b") -} - -func TestDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - th.Mux.HandleFunc("/subnets/08eae331-0402-425a-923c-34f7cfe39c1b", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - w.WriteHeader(http.StatusNoContent) - }) - - res := Delete(fake.ServiceClient(), "08eae331-0402-425a-923c-34f7cfe39c1b") - th.AssertNoErr(t, res.Err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts/delegate_test.go deleted file mode 100644 index a1ea98bb700..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/accounts/delegate_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package accounts - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/accounts" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestUpdateAccounts(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleUpdateAccountSuccessfully(t) - - options := &UpdateOpts{Metadata: map[string]string{"gophercloud-test": "accounts"}} - res := Update(fake.ServiceClient(), options) - th.CheckNoErr(t, res.Err) -} - -func TestGetAccounts(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - os.HandleGetAccountSuccessfully(t) - - expected := map[string]string{"Foo": "bar"} - actual, err := Get(fake.ServiceClient()).ExtractMetadata() - th.CheckNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/requests_test.go deleted file mode 100644 index 8b5578e91e8..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/requests_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package bulk - -import ( - "fmt" - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestBulkDelete(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.AssertEquals(t, r.URL.RawQuery, "bulk-delete") - - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` - { - "Number Not Found": 1, - "Response Status": "200 OK", - "Errors": [], - "Number Deleted": 1, - "Response Body": "" - } - `) - }) - - options := DeleteOpts{"gophercloud-testcontainer1", "gophercloud-testcontainer2"} - actual, err := Delete(fake.ServiceClient(), options).ExtractBody() - th.AssertNoErr(t, err) - th.AssertEquals(t, actual.NumberDeleted, 1) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/urls_test.go deleted file mode 100644 index 9169e52f16b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/bulk/urls_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package bulk - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestDeleteURL(t *testing.T) { - actual := deleteURL(endpointClient()) - expected := endpoint + "?bulk-delete" - th.CheckEquals(t, expected, actual) -} - -func TestExtractURL(t *testing.T) { - actual := extractURL(endpointClient(), "tar") - expected := endpoint + "?extract-archive=tar" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/delegate_test.go deleted file mode 100644 index 02c3c5e150a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/delegate_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package cdncontainers - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListCDNContainers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListContainerNamesSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNames(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ExpectedListNames, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetCDNContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetContainerSuccessfully(t) - - _, err := Get(fake.ServiceClient(), "testContainer").ExtractMetadata() - th.CheckNoErr(t, err) - -} - -func TestUpdateCDNContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleUpdateContainerSuccessfully(t) - - options := &UpdateOpts{TTL: 3600} - res := Update(fake.ServiceClient(), "testContainer", options) - th.CheckNoErr(t, res.Err) - -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/requests_test.go deleted file mode 100644 index 28b963dacef..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/requests_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package cdncontainers - -import ( - "net/http" - "testing" - - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestEnableCDNContainer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "PUT") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Add("X-Ttl", "259200") - w.Header().Add("X-Cdn-Enabled", "True") - w.WriteHeader(http.StatusNoContent) - }) - - options := &EnableOpts{CDNEnabled: true, TTL: 259200} - actual := Enable(fake.ServiceClient(), "testContainer", options) - th.AssertNoErr(t, actual.Err) - th.CheckEquals(t, actual.Header["X-Ttl"][0], "259200") - th.CheckEquals(t, actual.Header["X-Cdn-Enabled"][0], "True") -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/urls_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/urls_test.go deleted file mode 100644 index aa5bfe68b29..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdncontainers/urls_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package cdncontainers - -import ( - "testing" - - "github.com/rackspace/gophercloud" - th "github.com/rackspace/gophercloud/testhelper" -) - -const endpoint = "http://localhost:57909/" - -func endpointClient() *gophercloud.ServiceClient { - return &gophercloud.ServiceClient{Endpoint: endpoint} -} - -func TestEnableURL(t *testing.T) { - actual := enableURL(endpointClient(), "foo") - expected := endpoint + "foo" - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdnobjects/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdnobjects/delegate_test.go deleted file mode 100644 index b5e04a98c3b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/cdnobjects/delegate_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package cdnobjects - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestDeleteCDNObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDeleteObjectSuccessfully(t) - - res := Delete(fake.ServiceClient(), "testContainer", "testObject", nil) - th.AssertNoErr(t, res.Err) - -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers/delegate_test.go deleted file mode 100644 index 7ba4eb21c68..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/containers/delegate_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package containers - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/containers" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListContainerInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListContainerInfoSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), &os.ListOpts{Full: true}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractInfo(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ExpectedListInfo, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListContainerNames(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListContainerNamesSuccessfully(t) - - count := 0 - err := List(fake.ServiceClient(), &os.ListOpts{Full: false}).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNames(page) - if err != nil { - t.Errorf("Failed to extract container names: %v", err) - return false, err - } - - th.CheckDeepEquals(t, os.ExpectedListNames, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestCreateContainers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleCreateContainerSuccessfully(t) - - options := os.CreateOpts{ContentType: "application/json", Metadata: map[string]string{"foo": "bar"}} - res := Create(fake.ServiceClient(), "testContainer", options) - th.CheckNoErr(t, res.Err) - th.CheckEquals(t, "bar", res.Header["X-Container-Meta-Foo"][0]) - -} - -func TestDeleteContainers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDeleteContainerSuccessfully(t) - - res := Delete(fake.ServiceClient(), "testContainer") - th.CheckNoErr(t, res.Err) -} - -func TestUpdateContainers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleUpdateContainerSuccessfully(t) - - options := &os.UpdateOpts{Metadata: map[string]string{"foo": "bar"}} - res := Update(fake.ServiceClient(), "testContainer", options) - th.CheckNoErr(t, res.Err) -} - -func TestGetContainers(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetContainerSuccessfully(t) - - _, err := Get(fake.ServiceClient(), "testContainer").ExtractMetadata() - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects/delegate_test.go deleted file mode 100644 index 21cd4179a5d..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects/delegate_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package objects - -import ( - "strings" - "testing" - - os "github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestDownloadObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDownloadObjectSuccessfully(t) - - content, err := Download(fake.ServiceClient(), "testContainer", "testObject", nil).ExtractContent() - th.AssertNoErr(t, err) - th.CheckEquals(t, string(content), "Successful download with Gophercloud") -} - -func TestListObjectsInfo(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListObjectsInfoSuccessfully(t) - - count := 0 - options := &os.ListOpts{Full: true} - err := List(fake.ServiceClient(), "testContainer", options).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractInfo(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ExpectedListInfo, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListObjectNames(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListObjectNamesSuccessfully(t) - - count := 0 - options := &os.ListOpts{Full: false} - err := List(fake.ServiceClient(), "testContainer", options).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNames(page) - if err != nil { - t.Errorf("Failed to extract container names: %v", err) - return false, err - } - - th.CheckDeepEquals(t, os.ExpectedListNames, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestCreateObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - content := "Did gyre and gimble in the wabe" - os.HandleCreateTextObjectSuccessfully(t, content) - - options := &os.CreateOpts{ContentType: "text/plain"} - res := Create(fake.ServiceClient(), "testContainer", "testObject", strings.NewReader(content), options) - th.AssertNoErr(t, res.Err) -} - -func TestCreateObjectWithoutContentType(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - - content := "The sky was the color of television, tuned to a dead channel." - os.HandleCreateTypelessObjectSuccessfully(t, content) - - res := Create(fake.ServiceClient(), "testContainer", "testObject", strings.NewReader(content), &os.CreateOpts{}) - th.AssertNoErr(t, res.Err) -} - -func TestCopyObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleCopyObjectSuccessfully(t) - - options := &CopyOpts{Destination: "/newTestContainer/newTestObject"} - res := Copy(fake.ServiceClient(), "testContainer", "testObject", options) - th.AssertNoErr(t, res.Err) -} - -func TestDeleteObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDeleteObjectSuccessfully(t) - - res := Delete(fake.ServiceClient(), "testContainer", "testObject", nil) - th.AssertNoErr(t, res.Err) -} - -func TestUpdateObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleUpdateObjectSuccessfully(t) - - options := &os.UpdateOpts{Metadata: map[string]string{"Gophercloud-Test": "objects"}} - res := Update(fake.ServiceClient(), "testContainer", "testObject", options) - th.AssertNoErr(t, res.Err) -} - -func TestGetObject(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetObjectSuccessfully(t) - - expected := map[string]string{"Gophercloud-Test": "objects"} - actual, err := Get(fake.ServiceClient(), "testContainer", "testObject", nil).ExtractMetadata() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/buildinfo/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/buildinfo/delegate_test.go deleted file mode 100644 index b25a690c8df..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/buildinfo/delegate_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package buildinfo - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/orchestration/v1/buildinfo" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t, os.GetOutput) - - actual, err := Get(fake.ServiceClient()).Extract() - th.AssertNoErr(t, err) - - expected := os.GetExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackevents/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackevents/delegate_test.go deleted file mode 100644 index e1c0bc8dbcf..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackevents/delegate_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package stackevents - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackevents" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestFindEvents(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleFindSuccessfully(t, os.FindOutput) - - actual, err := Find(fake.ServiceClient(), "postman_stack").Extract() - th.AssertNoErr(t, err) - - expected := os.FindExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestList(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListSuccessfully(t, os.ListOutput) - - count := 0 - err := List(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractEvents(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestListResourceEvents(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListResourceEventsSuccessfully(t, os.ListResourceEventsOutput) - - count := 0 - err := ListResourceEvents(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", "my_resource", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractEvents(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ListResourceEventsExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetEvent(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t, os.GetOutput) - - actual, err := Get(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", "my_resource", "93940999-7d40-44ae-8de4-19624e7b8d18").Extract() - th.AssertNoErr(t, err) - - expected := os.GetExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources/delegate_test.go deleted file mode 100644 index 18e9614151a..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stackresources/delegate_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package stackresources - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/orchestration/v1/stackresources" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestFindResources(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleFindSuccessfully(t, os.FindOutput) - - actual, err := Find(fake.ServiceClient(), "hello_world").Extract() - th.AssertNoErr(t, err) - - expected := os.FindExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListResources(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListSuccessfully(t, os.ListOutput) - - count := 0 - err := List(fake.ServiceClient(), "hello_world", "49181cd6-169a-4130-9455-31185bbfc5bf", nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractResources(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetResource(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t, os.GetOutput) - - actual, err := Get(fake.ServiceClient(), "teststack", "0b1771bd-9336-4f2b-ae86-a80f971faf1e", "wordpress_instance").Extract() - th.AssertNoErr(t, err) - - expected := os.GetExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestResourceMetadata(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleMetadataSuccessfully(t, os.MetadataOutput) - - actual, err := Metadata(fake.ServiceClient(), "teststack", "0b1771bd-9336-4f2b-ae86-a80f971faf1e", "wordpress_instance").Extract() - th.AssertNoErr(t, err) - - expected := os.MetadataExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListResourceTypes(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListTypesSuccessfully(t, os.ListTypesOutput) - - count := 0 - err := ListTypes(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractResourceTypes(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ListTypesExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, 1, count) -} - -func TestGetResourceSchema(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSchemaSuccessfully(t, os.GetSchemaOutput) - - actual, err := Schema(fake.ServiceClient(), "OS::Heat::AResourceName").Extract() - th.AssertNoErr(t, err) - - expected := os.GetSchemaExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestGetResourceTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetTemplateSuccessfully(t, os.GetTemplateOutput) - - actual, err := Template(fake.ServiceClient(), "OS::Heat::AResourceName").Extract() - th.AssertNoErr(t, err) - - expected := os.GetTemplateExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks/delegate_test.go deleted file mode 100644 index a1fb3931299..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacks/delegate_test.go +++ /dev/null @@ -1,461 +0,0 @@ -package stacks - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacks" - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestCreateStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleCreateSuccessfully(t, CreateOutput) - - createOpts := os.CreateOpts{ - Name: "stackcreated", - Timeout: 60, - Template: `{ - "outputs": { - "db_host": { - "value": { - "get_attr": [ - "db", - "hostname" - ] - } - } - }, - "heat_template_version": "2014-10-16", - "description": "HEAT template for creating a Cloud Database.\n", - "parameters": { - "db_name": { - "default": "wordpress", - "type": "string", - "description": "the name for the database", - "constraints": [ - { - "length": { - "max": 64, - "min": 1 - }, - "description": "must be between 1 and 64 characters" - }, - { - "allowed_pattern": "[a-zA-Z][a-zA-Z0-9]*", - "description": "must begin with a letter and contain only alphanumeric characters." - } - ] - }, - "db_instance_name": { - "default": "Cloud_DB", - "type": "string", - "description": "the database instance name" - }, - "db_username": { - "default": "admin", - "hidden": true, - "type": "string", - "description": "database admin account username", - "constraints": [ - { - "length": { - "max": 16, - "min": 1 - }, - "description": "must be between 1 and 16 characters" - }, - { - "allowed_pattern": "[a-zA-Z][a-zA-Z0-9]*", - "description": "must begin with a letter and contain only alphanumeric characters." - } - ] - }, - "db_volume_size": { - "default": 30, - "type": "number", - "description": "database volume size (in GB)", - "constraints": [ - { - "range": { - "max": 1024, - "min": 1 - }, - "description": "must be between 1 and 1024 GB" - } - ] - }, - "db_flavor": { - "default": "1GB Instance", - "type": "string", - "description": "database instance size", - "constraints": [ - { - "description": "must be a valid cloud database flavor", - "allowed_values": [ - "1GB Instance", - "2GB Instance", - "4GB Instance", - "8GB Instance", - "16GB Instance" - ] - } - ] - }, - "db_password": { - "default": "admin", - "hidden": true, - "type": "string", - "description": "database admin account password", - "constraints": [ - { - "length": { - "max": 41, - "min": 1 - }, - "description": "must be between 1 and 14 characters" - }, - { - "allowed_pattern": "[a-zA-Z0-9]*", - "description": "must contain only alphanumeric characters." - } - ] - } - }, - "resources": { - "db": { - "type": "OS::Trove::Instance", - "properties": { - "flavor": { - "get_param": "db_flavor" - }, - "size": { - "get_param": "db_volume_size" - }, - "users": [ - { - "password": { - "get_param": "db_password" - }, - "name": { - "get_param": "db_username" - }, - "databases": [ - { - "get_param": "db_name" - } - ] - } - ], - "name": { - "get_param": "db_instance_name" - }, - "databases": [ - { - "name": { - "get_param": "db_name" - } - } - ] - } - } - } - }`, - DisableRollback: os.Disable, - } - actual, err := Create(fake.ServiceClient(), createOpts).Extract() - th.AssertNoErr(t, err) - - expected := CreateExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestAdoptStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleCreateSuccessfully(t, CreateOutput) - - adoptOpts := os.AdoptOpts{ - AdoptStackData: `{\"environment\":{\"parameters\":{}}, \"status\":\"COMPLETE\",\"name\": \"trovestack\",\n \"template\": {\n \"outputs\": {\n \"db_host\": {\n \"value\": {\n \"get_attr\": [\n \"db\",\n \"hostname\"\n ]\n }\n }\n },\n \"heat_template_version\": \"2014-10-16\",\n \"description\": \"HEAT template for creating a Cloud Database.\\n\",\n \"parameters\": {\n \"db_instance_name\": {\n \"default\": \"Cloud_DB\",\n \"type\": \"string\",\n \"description\": \"the database instance name\"\n },\n \"db_flavor\": {\n \"default\": \"1GB Instance\",\n \"type\": \"string\",\n \"description\": \"database instance size\",\n \"constraints\": [\n {\n \"description\": \"must be a valid cloud database flavor\",\n \"allowed_values\": [\n \"1GB Instance\",\n \"2GB Instance\",\n \"4GB Instance\",\n \"8GB Instance\",\n \"16GB Instance\"\n ]\n }\n ]\n },\n \"db_password\": {\n \"default\": \"admin\",\n \"hidden\": true,\n \"type\": \"string\",\n \"description\": \"database admin account password\",\n \"constraints\": [\n {\n \"length\": {\n \"max\": 41,\n \"min\": 1\n },\n \"description\": \"must be between 1 and 14 characters\"\n },\n {\n \"allowed_pattern\": \"[a-zA-Z0-9]*\",\n \"description\": \"must contain only alphanumeric characters.\"\n }\n ]\n },\n \"db_name\": {\n \"default\": \"wordpress\",\n \"type\": \"string\",\n \"description\": \"the name for the database\",\n \"constraints\": [\n {\n \"length\": {\n \"max\": 64,\n \"min\": 1\n },\n \"description\": \"must be between 1 and 64 characters\"\n },\n {\n \"allowed_pattern\": \"[a-zA-Z][a-zA-Z0-9]*\",\n \"description\": \"must begin with a letter and contain only alphanumeric characters.\"\n }\n ]\n },\n \"db_username\": {\n \"default\": \"admin\",\n \"hidden\": true,\n \"type\": \"string\",\n \"description\": \"database admin account username\",\n \"constraints\": [\n {\n \"length\": {\n \"max\": 16,\n \"min\": 1\n },\n \"description\": \"must be between 1 and 16 characters\"\n },\n {\n \"allowed_pattern\": \"[a-zA-Z][a-zA-Z0-9]*\",\n \"description\": \"must begin with a letter and contain only alphanumeric characters.\"\n }\n ]\n },\n \"db_volume_size\": {\n \"default\": 30,\n \"type\": \"number\",\n \"description\": \"database volume size (in GB)\",\n \"constraints\": [\n {\n \"range\": {\n \"max\": 1024,\n \"min\": 1\n },\n \"description\": \"must be between 1 and 1024 GB\"\n }\n ]\n }\n },\n \"resources\": {\n \"db\": {\n \"type\": \"OS::Trove::Instance\",\n \"properties\": {\n \"flavor\": {\n \"get_param\": \"db_flavor\"\n },\n \"databases\": [\n {\n \"name\": {\n \"get_param\": \"db_name\"\n }\n }\n ],\n \"users\": [\n {\n \"password\": {\n \"get_param\": \"db_password\"\n },\n \"name\": {\n \"get_param\": \"db_username\"\n },\n \"databases\": [\n {\n \"get_param\": \"db_name\"\n }\n ]\n }\n ],\n \"name\": {\n \"get_param\": \"db_instance_name\"\n },\n \"size\": {\n \"get_param\": \"db_volume_size\"\n }\n }\n }\n }\n },\n \"action\": \"CREATE\",\n \"id\": \"exxxxd-7xx5-4xxb-bxx2-cxxxxxx5\",\n \"resources\": {\n \"db\": {\n \"status\": \"COMPLETE\",\n \"name\": \"db\",\n \"resource_data\": {},\n \"resource_id\": \"exxxx2-9xx0-4xxxb-bxx2-dxxxxxx4\",\n \"action\": \"CREATE\",\n \"type\": \"OS::Trove::Instance\",\n \"metadata\": {}\n }\n }\n},`, - Name: "stackadopted", - Timeout: 60, - Template: `{ - "outputs": { - "db_host": { - "value": { - "get_attr": [ - "db", - "hostname" - ] - } - } - }, - "heat_template_version": "2014-10-16", - "description": "HEAT template for creating a Cloud Database.\n", - "parameters": { - "db_name": { - "default": "wordpress", - "type": "string", - "description": "the name for the database", - "constraints": [ - { - "length": { - "max": 64, - "min": 1 - }, - "description": "must be between 1 and 64 characters" - }, - { - "allowed_pattern": "[a-zA-Z][a-zA-Z0-9]*", - "description": "must begin with a letter and contain only alphanumeric characters." - } - ] - }, - "db_instance_name": { - "default": "Cloud_DB", - "type": "string", - "description": "the database instance name" - }, - "db_username": { - "default": "admin", - "hidden": true, - "type": "string", - "description": "database admin account username", - "constraints": [ - { - "length": { - "max": 16, - "min": 1 - }, - "description": "must be between 1 and 16 characters" - }, - { - "allowed_pattern": "[a-zA-Z][a-zA-Z0-9]*", - "description": "must begin with a letter and contain only alphanumeric characters." - } - ] - }, - "db_volume_size": { - "default": 30, - "type": "number", - "description": "database volume size (in GB)", - "constraints": [ - { - "range": { - "max": 1024, - "min": 1 - }, - "description": "must be between 1 and 1024 GB" - } - ] - }, - "db_flavor": { - "default": "1GB Instance", - "type": "string", - "description": "database instance size", - "constraints": [ - { - "description": "must be a valid cloud database flavor", - "allowed_values": [ - "1GB Instance", - "2GB Instance", - "4GB Instance", - "8GB Instance", - "16GB Instance" - ] - } - ] - }, - "db_password": { - "default": "admin", - "hidden": true, - "type": "string", - "description": "database admin account password", - "constraints": [ - { - "length": { - "max": 41, - "min": 1 - }, - "description": "must be between 1 and 14 characters" - }, - { - "allowed_pattern": "[a-zA-Z0-9]*", - "description": "must contain only alphanumeric characters." - } - ] - } - }, - "resources": { - "db": { - "type": "OS::Trove::Instance", - "properties": { - "flavor": { - "get_param": "db_flavor" - }, - "size": { - "get_param": "db_volume_size" - }, - "users": [ - { - "password": { - "get_param": "db_password" - }, - "name": { - "get_param": "db_username" - }, - "databases": [ - { - "get_param": "db_name" - } - ] - } - ], - "name": { - "get_param": "db_instance_name" - }, - "databases": [ - { - "name": { - "get_param": "db_name" - } - } - ] - } - } - } - }`, - DisableRollback: os.Disable, - } - actual, err := Adopt(fake.ServiceClient(), adoptOpts).Extract() - th.AssertNoErr(t, err) - - expected := CreateExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestListStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleListSuccessfully(t, os.FullListOutput) - - count := 0 - err := List(fake.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := os.ExtractStacks(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, os.ListExpected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestUpdateStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleUpdateSuccessfully(t) - - updateOpts := os.UpdateOpts{ - Template: ` - { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - }`, - } - err := Update(fake.ServiceClient(), "gophercloud-test-stack-2", "db6977b2-27aa-4775-9ae7-6213212d4ada", updateOpts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestDeleteStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleDeleteSuccessfully(t) - - err := Delete(fake.ServiceClient(), "gophercloud-test-stack-2", "db6977b2-27aa-4775-9ae7-6213212d4ada").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestPreviewStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandlePreviewSuccessfully(t, os.GetOutput) - - previewOpts := os.PreviewOpts{ - Name: "stackcreated", - Timeout: 60, - Template: ` - { - "stack_name": "postman_stack", - "template": { - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": { - "flavor": { - "default": "m1.tiny", - "type": "string" - } - }, - "resources": { - "hello_world": { - "type":"OS::Nova::Server", - "properties": { - "key_name": "heat_key", - "flavor": { - "get_param": "flavor" - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n" - } - } - } - } - }`, - DisableRollback: os.Disable, - } - actual, err := Preview(fake.ServiceClient(), previewOpts).Extract() - th.AssertNoErr(t, err) - - expected := os.PreviewExpected - th.AssertDeepEquals(t, expected, actual) -} - -/* -func TestAbandonStack(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleAbandonSuccessfully(t) - - //actual, err := Abandon(fake.ServiceClient(), "postman_stack", "16ef0584-4458-41eb-87c8-0dc8d5f66c87").Extract() - //th.AssertNoErr(t, err) - res := Abandon(fake.ServiceClient(), "postman_stack", "16ef0584-4458-41eb-87c8-0dc8d5f66c87") //.Extract() - th.AssertNoErr(t, res.Err) - t.Logf("actual: %+v", res) - - //expected := os.AbandonExpected - //th.AssertDeepEquals(t, expected, actual) -} -*/ diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates/delegate_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates/delegate_test.go deleted file mode 100644 index d4006c476d5..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/orchestration/v1/stacktemplates/delegate_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package stacktemplates - -import ( - "testing" - - os "github.com/rackspace/gophercloud/openstack/orchestration/v1/stacktemplates" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestGetTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleGetSuccessfully(t, os.GetOutput) - - actual, err := Get(fake.ServiceClient(), "postman_stack", "16ef0584-4458-41eb-87c8-0dc8d5f66c87").Extract() - th.AssertNoErr(t, err) - - expected := os.GetExpected - th.AssertDeepEquals(t, expected, actual) -} - -func TestValidateTemplate(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - os.HandleValidateSuccessfully(t, os.ValidateOutput) - - opts := os.ValidateOpts{ - Template: map[string]interface{}{ - "heat_template_version": "2013-05-23", - "description": "Simple template to test heat commands", - "parameters": map[string]interface{}{ - "flavor": map[string]interface{}{ - "default": "m1.tiny", - "type": "string", - }, - }, - "resources": map[string]interface{}{ - "hello_world": map[string]interface{}{ - "type": "OS::Nova::Server", - "properties": map[string]interface{}{ - "key_name": "heat_key", - "flavor": map[string]interface{}{ - "get_param": "flavor", - }, - "image": "ad091b52-742f-469e-8f3c-fd81cadf0743", - "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n", - }, - }, - }, - }, - } - actual, err := Validate(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - - expected := os.ValidateExpected - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/cloudnetworks/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/cloudnetworks/requests_test.go deleted file mode 100644 index 10d15dd11f7..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/cloudnetworks/requests_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package cloudnetworks - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListCloudNetworks(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/cloud_networks", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `[{ - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "updated": "2014-05-25T02:28:44Z" - }]`) - }) - - expected := []CloudNetwork{ - CloudNetwork{ - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - Name: "RC-CLOUD", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - } - - count := 0 - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractCloudNetworks(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetCloudNetwork(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/cloud_networks/07426958-1ebf-4c38-b032-d456820ca21a", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, `{ - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "updated": "2014-05-25T02:28:44Z" - }`) - }) - - expected := &CloudNetwork{ - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - Name: "RC-CLOUD", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - } - - actual, err := Get(fake.ServiceClient(), "07426958-1ebf-4c38-b032-d456820ca21a").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/lbpools/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/lbpools/requests_test.go deleted file mode 100644 index 48ebcece131..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/lbpools/requests_test.go +++ /dev/null @@ -1,876 +0,0 @@ -package lbpools - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListPools(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `[ - { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - "name": "RCv3Test", - "node_counts": { - "cloud_servers": 3, - "external": 4, - "total": 7 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.5" - }, - { - "id": "33021100-4abf-4836-9080-465a6d87ab68", - "name": "RCv3Test2", - "node_counts": { - "cloud_servers": 1, - "external": 0, - "total": 1 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.7" - }, - { - "id": "b644350a-301b-47b5-a411-c6e0f933c347", - "name": "RCv3Test3", - "node_counts": { - "cloud_servers": 2, - "external": 3, - "total": 5 - }, - "port": 443, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.15" - } - ]`) - }) - - expected := []Pool{ - Pool{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - Name: "RCv3Test", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 3, - External: 4, - Total: 7, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.5", - }, - Pool{ - ID: "33021100-4abf-4836-9080-465a6d87ab68", - Name: "RCv3Test2", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 1, - External: 0, - Total: 1, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.7", - }, - Pool{ - ID: "b644350a-301b-47b5-a411-c6e0f933c347", - Name: "RCv3Test3", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 2, - External: 3, - Total: 5, - }, - Port: 443, - Status: "ACTIVE", - VirtualIP: "203.0.113.15", - }, - } - - count := 0 - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPools(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetLBPool(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, `{ - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - "name": "RCv3Test", - "node_counts": { - "cloud_servers": 3, - "external": 4, - "total": 7 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.5" - }`) - }) - - expected := &Pool{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - Name: "RCv3Test", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 3, - External: 4, - Total: 7, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.5", - } - - actual, err := Get(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, expected, actual) -} - -func TestListNodes(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `[ - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ACTIVE", - "updated": "2014-05-30T03:24:18Z" - }, - { - "created": "2014-05-31T08:23:12Z", - "cloud_server": { - "id": "f28b870f-a063-498a-8b12-7025e5b1caa6" - }, - "id": "b70481dd-7edf-4dbb-a44b-41cc7679d4fb", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ADDING", - "updated": "2014-05-31T08:23:26Z" - }, - { - "created": "2014-05-31T08:23:18Z", - "cloud_server": { - "id": "a3d3a6b3-e4e4-496f-9a3d-5c987163e458" - }, - "id": "ced9ddc8-6fae-4e72-9457-16ead52b5515", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ADD_FAILED", - "status_detail": "Unable to communicate with network device", - "updated": "2014-05-31T08:24:36Z" - } - ]`) - }) - - expected := []Node{ - Node{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - }, - Node{ - CreatedAt: time.Date(2014, 5, 31, 8, 23, 12, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "f28b870f-a063-498a-8b12-7025e5b1caa6", - }, - ID: "b70481dd-7edf-4dbb-a44b-41cc7679d4fb", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ADDING", - UpdatedAt: time.Date(2014, 5, 31, 8, 23, 26, 0, time.UTC), - }, - Node{ - CreatedAt: time.Date(2014, 5, 31, 8, 23, 18, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "a3d3a6b3-e4e4-496f-9a3d-5c987163e458", - }, - ID: "ced9ddc8-6fae-4e72-9457-16ead52b5515", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ADD_FAILED", - StatusDetail: "Unable to communicate with network device", - UpdatedAt: time.Date(2014, 5, 31, 8, 24, 36, 0, time.UTC), - }, - } - - count := 0 - err := ListNodes(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNodes(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestCreateNode(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - } - } - `) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, ` - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - `) - }) - - expected := &Node{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - } - - actual, err := CreateNode(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", "d95ae0c4-6ab8-4873-b82f-f8433840cff2").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, expected, actual) -} - -func TestListNodesDetails(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes/details", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, ` - [ - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - "name": "RCv3Test", - "node_counts": { - "cloud_servers": 3, - "external": 4, - "total": 7 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.5" - }, - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - ] - `) - }) - - expected := []NodeDetails{ - NodeDetails{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: Pool{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - Name: "RCv3Test", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 3, - External: 4, - Total: 7, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.5", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - }, - } - count := 0 - err := ListNodesDetails(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNodesDetails(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestGetNode(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes/1860451d-fb89-45b8-b54e-151afceb50e5", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - `) - }) - - expected := &Node{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - } - - actual, err := GetNode(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", "1860451d-fb89-45b8-b54e-151afceb50e5").Extract() - th.AssertNoErr(t, err) - - th.AssertDeepEquals(t, expected, actual) -} - -func TestDeleteNode(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes/1860451d-fb89-45b8-b54e-151afceb50e5", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusNoContent) - }) - - err := DeleteNode(client.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", "1860451d-fb89-45b8-b54e-151afceb50e5").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestGetNodeDetails(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2/nodes/d95ae0c4-6ab8-4873-b82f-f8433840cff2/details", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, ` - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - "name": "RCv3Test", - "node_counts": { - "cloud_servers": 3, - "external": 4, - "total": 7 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.5" - }, - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - `) - }) - - expected := &NodeDetails{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: Pool{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - Name: "RCv3Test", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 3, - External: 4, - Total: 7, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.5", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - } - - actual, err := GetNodeDetails(fake.ServiceClient(), "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", "d95ae0c4-6ab8-4873-b82f-f8433840cff2").Extract() - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) -} - -func TestCreateNodes(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/nodes", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - [ - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - } - }, - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "load_balancer_pool": { - "id": "33021100-4abf-4836-9080-465a6d87ab68" - } - } - ] - `) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, ` - [ - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - }, - "status": "ADDING", - "status_detail": null, - "updated": null - }, - { - "created": "2014-05-31T08:23:12Z", - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "id": "b70481dd-7edf-4dbb-a44b-41cc7679d4fb", - "load_balancer_pool": { - "id": "33021100-4abf-4836-9080-465a6d87ab68" - }, - "status": "ADDING", - "status_detail": null, - "updated": null - } - ] - `) - }) - - expected := []Node{ - Node{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - }, - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - Status: "ADDING", - }, - Node{ - CreatedAt: time.Date(2014, 5, 31, 8, 23, 12, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - }, - ID: "b70481dd-7edf-4dbb-a44b-41cc7679d4fb", - LoadBalancerPool: struct { - ID string `mapstructure:"id"` - }{ - ID: "33021100-4abf-4836-9080-465a6d87ab68", - }, - Status: "ADDING", - }, - } - - opts := NodesOpts{ - NodeOpts{ - ServerID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - PoolID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - NodeOpts{ - ServerID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - PoolID: "33021100-4abf-4836-9080-465a6d87ab68", - }, - } - actual, err := CreateNodes(fake.ServiceClient(), opts).Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestDeleteNodes(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/nodes", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - [ - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2" - } - }, - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - }, - "load_balancer_pool": { - "id": "33021100-4abf-4836-9080-465a6d87ab68" - } - } - ] - `) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusNoContent) - }) - - opts := NodesOpts{ - NodeOpts{ - ServerID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - PoolID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - }, - NodeOpts{ - ServerID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - PoolID: "33021100-4abf-4836-9080-465a6d87ab68", - }, - } - err := DeleteNodes(client.ServiceClient(), opts).ExtractErr() - th.AssertNoErr(t, err) -} - -func TestListNodesForServerDetails(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/load_balancer_pools/nodes/details", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, ` - [ - { - "created": "2014-05-30T03:23:42Z", - "id": "1860451d-fb89-45b8-b54e-151afceb50e5", - "load_balancer_pool": { - "id": "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - "name": "RCv3Test", - "node_counts": { - "cloud_servers": 3, - "external": 4, - "total": 7 - }, - "port": 80, - "status": "ACTIVE", - "status_detail": null, - "virtual_ip": "203.0.113.5" - }, - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - ] - `) - }) - - expected := []NodeDetailsForServer{ - NodeDetailsForServer{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - ID: "1860451d-fb89-45b8-b54e-151afceb50e5", - LoadBalancerPool: Pool{ - ID: "d6d3aa7c-dfa5-4e61-96ee-1d54ac1075d2", - Name: "RCv3Test", - NodeCounts: struct { - CloudServers int `mapstructure:"cloud_servers"` - External int `mapstructure:"external"` - Total int `mapstructure:"total"` - }{ - CloudServers: 3, - External: 4, - Total: 7, - }, - Port: 80, - Status: "ACTIVE", - VirtualIP: "203.0.113.5", - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - }, - } - count := 0 - err := ListNodesDetailsForServer(fake.ServiceClient(), "07426958-1ebf-4c38-b032-d456820ca21a").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractNodesDetailsForServer(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/publicips/requests_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/publicips/requests_test.go deleted file mode 100644 index 61da2b03d9b..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/rackspace/rackconnect/v3/publicips/requests_test.go +++ /dev/null @@ -1,378 +0,0 @@ -package publicips - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/rackspace/gophercloud/pagination" - th "github.com/rackspace/gophercloud/testhelper" - "github.com/rackspace/gophercloud/testhelper/client" - fake "github.com/rackspace/gophercloud/testhelper/client" -) - -func TestListIPs(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/public_ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, `[ - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "2d0f586b-37a7-4ae0-adac-2743d5feb450", - "public_ip_v4": "203.0.113.110", - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - } - ]`) - }) - - expected := []PublicIP{ - PublicIP{ - ID: "2d0f586b-37a7-4ae0-adac-2743d5feb450", - PublicIPv4: "203.0.113.110", - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - Status: "ACTIVE", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - }, - } - - count := 0 - err := List(fake.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPublicIPs(page) - th.AssertNoErr(t, err) - - th.CheckDeepEquals(t, expected, actual) - - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} - -func TestCreateIP(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/public_ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "POST") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - th.TestJSONRequest(t, r, ` - { - "cloud_server": { - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2" - } - } - `) - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusCreated) - fmt.Fprintf(w, ` - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "2d0f586b-37a7-4ae0-adac-2743d5feb450", - "status": "ADDING" - }`) - }) - - expected := &PublicIP{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - ID: "2d0f586b-37a7-4ae0-adac-2743d5feb450", - Status: "ADDING", - } - - actual, err := Create(fake.ServiceClient(), "d95ae0c4-6ab8-4873-b82f-f8433840cff2").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestGetIP(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/public_ips/2d0f586b-37a7-4ae0-adac-2743d5feb450", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, ` - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "2d0f586b-37a7-4ae0-adac-2743d5feb450", - "public_ip_v4": "203.0.113.110", - "status": "ACTIVE", - "status_detail": null, - "updated": "2014-05-30T03:24:18Z" - }`) - }) - - expected := &PublicIP{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - ID: "2d0f586b-37a7-4ae0-adac-2743d5feb450", - Status: "ACTIVE", - PublicIPv4: "203.0.113.110", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - } - - actual, err := Get(fake.ServiceClient(), "2d0f586b-37a7-4ae0-adac-2743d5feb450").Extract() - th.AssertNoErr(t, err) - th.AssertDeepEquals(t, expected, actual) -} - -func TestDeleteIP(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/public_ips/2d0f586b-37a7-4ae0-adac-2743d5feb450", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "DELETE") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusNoContent) - }) - - err := Delete(client.ServiceClient(), "2d0f586b-37a7-4ae0-adac-2743d5feb450").ExtractErr() - th.AssertNoErr(t, err) -} - -func TestListForServer(t *testing.T) { - th.SetupHTTP() - defer th.TeardownHTTP() - th.Mux.HandleFunc("/public_ips", func(w http.ResponseWriter, r *http.Request) { - th.TestMethod(t, r, "GET") - th.TestHeader(t, r, "X-Auth-Token", fake.TokenID) - th.TestHeader(t, r, "Accept", "application/json") - - w.Header().Set("Content-Type", "application/json") - fmt.Fprintf(w, ` - [ - { - "created": "2014-05-30T03:23:42Z", - "cloud_server": { - "cloud_network": { - "cidr": "192.168.100.0/24", - "created": "2014-05-25T01:23:42Z", - "id": "07426958-1ebf-4c38-b032-d456820ca21a", - "name": "RC-CLOUD", - "private_ip_v4": "192.168.100.5", - "updated": "2014-05-25T02:28:44Z" - }, - "created": "2014-05-30T02:18:42Z", - "id": "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - "name": "RCv3TestServer1", - "updated": "2014-05-30T02:19:18Z" - }, - "id": "2d0f586b-37a7-4ae0-adac-2743d5feb450", - "public_ip_v4": "203.0.113.110", - "status": "ACTIVE", - "updated": "2014-05-30T03:24:18Z" - } - ]`) - }) - - expected := []PublicIP{ - PublicIP{ - CreatedAt: time.Date(2014, 5, 30, 3, 23, 42, 0, time.UTC), - CloudServer: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - CloudNetwork struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - } `mapstructure:"cloud_network"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "d95ae0c4-6ab8-4873-b82f-f8433840cff2", - CloudNetwork: struct { - ID string `mapstructure:"id"` - Name string `mapstructure:"name"` - PrivateIPv4 string `mapstructure:"private_ip_v4"` - CIDR string `mapstructure:"cidr"` - CreatedAt time.Time `mapstructure:"-"` - UpdatedAt time.Time `mapstructure:"-"` - }{ - ID: "07426958-1ebf-4c38-b032-d456820ca21a", - CIDR: "192.168.100.0/24", - CreatedAt: time.Date(2014, 5, 25, 1, 23, 42, 0, time.UTC), - Name: "RC-CLOUD", - PrivateIPv4: "192.168.100.5", - UpdatedAt: time.Date(2014, 5, 25, 2, 28, 44, 0, time.UTC), - }, - CreatedAt: time.Date(2014, 5, 30, 2, 18, 42, 0, time.UTC), - Name: "RCv3TestServer1", - UpdatedAt: time.Date(2014, 5, 30, 2, 19, 18, 0, time.UTC), - }, - ID: "2d0f586b-37a7-4ae0-adac-2743d5feb450", - Status: "ACTIVE", - PublicIPv4: "203.0.113.110", - UpdatedAt: time.Date(2014, 5, 30, 3, 24, 18, 0, time.UTC), - }, - } - count := 0 - err := ListForServer(fake.ServiceClient(), "d95ae0c4-6ab8-4873-b82f-f8433840cff2").EachPage(func(page pagination.Page) (bool, error) { - count++ - actual, err := ExtractPublicIPs(page) - th.AssertNoErr(t, err) - th.CheckDeepEquals(t, expected, actual) - return true, nil - }) - th.AssertNoErr(t, err) - th.CheckEquals(t, count, 1) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/service_client_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/service_client_test.go deleted file mode 100644 index 84beb3f7681..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/service_client_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package gophercloud - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestServiceURL(t *testing.T) { - c := &ServiceClient{Endpoint: "http://123.45.67.8/"} - expected := "http://123.45.67.8/more/parts/here" - actual := c.ServiceURL("more", "parts", "here") - th.CheckEquals(t, expected, actual) -} diff --git a/Godeps/_workspace/src/github.com/rackspace/gophercloud/util_test.go b/Godeps/_workspace/src/github.com/rackspace/gophercloud/util_test.go deleted file mode 100644 index 5a15a005d35..00000000000 --- a/Godeps/_workspace/src/github.com/rackspace/gophercloud/util_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package gophercloud - -import ( - "testing" - - th "github.com/rackspace/gophercloud/testhelper" -) - -func TestWaitFor(t *testing.T) { - err := WaitFor(5, func() (bool, error) { - return true, nil - }) - th.CheckNoErr(t, err) -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go deleted file mode 100644 index b726c070cc0..00000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go +++ /dev/null @@ -1,1296 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Unit tests for block parsing -// - -package blackfriday - -import ( - "testing" -) - -func runMarkdownBlockWithRenderer(input string, extensions int, renderer Renderer) string { - return string(Markdown([]byte(input), renderer, extensions)) -} - -func runMarkdownBlock(input string, extensions int) string { - htmlFlags := 0 - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRenderer(htmlFlags, "", "") - - return runMarkdownBlockWithRenderer(input, extensions, renderer) -} - -func runnerWithRendererParameters(parameters HtmlRendererParameters) func(string, int) string { - return func(input string, extensions int) string { - htmlFlags := 0 - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRendererWithParameters(htmlFlags, "", "", parameters) - - return runMarkdownBlockWithRenderer(input, extensions, renderer) - } -} - -func doTestsBlock(t *testing.T, tests []string, extensions int) { - doTestsBlockWithRunner(t, tests, extensions, runMarkdownBlock) -} - -func doTestsBlockWithRunner(t *testing.T, tests []string, extensions int, runner func(string, int) string) { - // catch and report panics - var candidate string - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err) - } - }() - - for i := 0; i+1 < len(tests); i += 2 { - input := tests[i] - candidate = input - expected := tests[i+1] - actual := runner(candidate, extensions) - if actual != expected { - t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]", - candidate, expected, actual) - } - - // now test every substring to stress test bounds checking - if !testing.Short() { - for start := 0; start < len(input); start++ { - for end := start + 1; end <= len(input); end++ { - candidate = input[start:end] - _ = runMarkdownBlock(candidate, extensions) - } - } - } - } -} - -func TestPrefixHeaderNoExtensions(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "#Header 1\n", - "

Header 1

\n", - - "##Header 2\n", - "

Header 2

\n", - - "###Header 3\n", - "

Header 3

\n", - - "####Header 4\n", - "

Header 4

\n", - - "#####Header 5\n", - "
Header 5
\n", - - "######Header 6\n", - "
Header 6
\n", - - "#######Header 7\n", - "
#Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPrefixHeaderSpaceExtension(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "

####### Header 7

\n", - - "#Header 1\n", - "

#Header 1

\n", - - "##Header 2\n", - "

##Header 2

\n", - - "###Header 3\n", - "

###Header 3

\n", - - "####Header 4\n", - "

####Header 4

\n", - - "#####Header 5\n", - "

#####Header 5

\n", - - "######Header 6\n", - "

######Header 6

\n", - - "#######Header 7\n", - "

#######Header 7

\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List\n#Header
  • \n
  • List
  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_SPACE_HEADERS) -} - -func TestPrefixHeaderIdExtension(t *testing.T) { - var tests = []string{ - "# Header 1 {#someid}\n", - "

Header 1

\n", - - "# Header 1 {#someid} \n", - "

Header 1

\n", - - "# Header 1 {#someid}\n", - "

Header 1

\n", - - "# Header 1 {#someid\n", - "

Header 1 {#someid

\n", - - "# Header 1 {#someid\n", - "

Header 1 {#someid

\n", - - "# Header 1 {#someid}}\n", - "

Header 1

\n\n

}

\n", - - "## Header 2 {#someid}\n", - "

Header 2

\n", - - "### Header 3 {#someid}\n", - "

Header 3

\n", - - "#### Header 4 {#someid}\n", - "

Header 4

\n", - - "##### Header 5 {#someid}\n", - "
Header 5
\n", - - "###### Header 6 {#someid}\n", - "
Header 6
\n", - - "####### Header 7 {#someid}\n", - "
# Header 7
\n", - - "# Header 1 # {#someid}\n", - "

Header 1

\n", - - "## Header 2 ## {#someid}\n", - "

Header 2

\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header {#someid}\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_HEADER_IDS) -} - -func TestPrefixHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { - var tests = []string{ - "# header 1 {#someid}\n", - "

header 1

\n", - - "## header 2 {#someid}\n", - "

header 2

\n", - - "### header 3 {#someid}\n", - "

header 3

\n", - - "#### header 4 {#someid}\n", - "

header 4

\n", - - "##### header 5 {#someid}\n", - "
header 5
\n", - - "###### header 6 {#someid}\n", - "
header 6
\n", - - "####### header 7 {#someid}\n", - "
# header 7
\n", - - "# header 1 # {#someid}\n", - "

header 1

\n", - - "## header 2 ## {#someid}\n", - "

header 2

\n", - - "* List\n# Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header {#someid}\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header {#someid}\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - } - - parameters := HtmlRendererParameters{ - HeaderIDPrefix: "PRE:", - HeaderIDSuffix: ":POST", - } - - doTestsBlockWithRunner(t, tests, EXTENSION_HEADER_IDS, runnerWithRendererParameters(parameters)) -} - -func TestPrefixAutoHeaderIdExtension(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "# Header 1 \n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - - "# Header\n\n# Header\n", - "

Header

\n\n

Header

\n", - - "# Header 1\n\n# Header 1", - "

Header 1

\n\n

Header 1

\n", - - "# Header\n\n# Header 1\n\n# Header\n\n# Header", - "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) -} - -func TestPrefixAutoHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { - var tests = []string{ - "# Header 1\n", - "

Header 1

\n", - - "# Header 1 \n", - "

Header 1

\n", - - "## Header 2\n", - "

Header 2

\n", - - "### Header 3\n", - "

Header 3

\n", - - "#### Header 4\n", - "

Header 4

\n", - - "##### Header 5\n", - "
Header 5
\n", - - "###### Header 6\n", - "
Header 6
\n", - - "####### Header 7\n", - "
# Header 7
\n", - - "Hello\n# Header 1\nGoodbye\n", - "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", - - "* List\n# Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n#Header\n* List\n", - "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", - - "* List\n * Nested list\n # Nested header\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + - "

      Nested header

    • \n
  • \n
\n", - - "# Header\n\n# Header\n", - "

Header

\n\n

Header

\n", - - "# Header 1\n\n# Header 1", - "

Header 1

\n\n

Header 1

\n", - - "# Header\n\n# Header 1\n\n# Header\n\n# Header", - "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", - } - - parameters := HtmlRendererParameters{ - HeaderIDPrefix: "PRE:", - HeaderIDSuffix: ":POST", - } - - doTestsBlockWithRunner(t, tests, EXTENSION_AUTO_HEADER_IDS, runnerWithRendererParameters(parameters)) -} - -func TestPrefixMultipleHeaderExtensions(t *testing.T) { - var tests = []string{ - "# Header\n\n# Header {#header}\n\n# Header 1", - "

Header

\n\n

Header

\n\n

Header 1

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS|EXTENSION_HEADER_IDS) -} - -func TestUnderlineHeaders(t *testing.T) { - var tests = []string{ - "Header 1\n========\n", - "

Header 1

\n", - - "Header 2\n--------\n", - "

Header 2

\n", - - "A\n=\n", - "

A

\n", - - "B\n-\n", - "

B

\n", - - "Paragraph\nHeader\n=\n", - "

Paragraph

\n\n

Header

\n", - - "Header\n===\nParagraph\n", - "

Header

\n\n

Paragraph

\n", - - "Header\n===\nAnother header\n---\n", - "

Header

\n\n

Another header

\n", - - " Header\n======\n", - "

Header

\n", - - " Code\n========\n", - "
Code\n
\n\n

========

\n", - - "Header with *inline*\n=====\n", - "

Header with inline

\n", - - "* List\n * Sublist\n Not a header\n ------\n", - "
    \n
  • List\n\n
      \n
    • Sublist\nNot a header\n------
    • \n
  • \n
\n", - - "Paragraph\n\n\n\n\nHeader\n===\n", - "

Paragraph

\n\n

Header

\n", - - "Trailing space \n==== \n\n", - "

Trailing space

\n", - - "Trailing spaces\n==== \n\n", - "

Trailing spaces

\n", - - "Double underline\n=====\n=====\n", - "

Double underline

\n\n

=====

\n", - } - doTestsBlock(t, tests, 0) -} - -func TestUnderlineHeadersAutoIDs(t *testing.T) { - var tests = []string{ - "Header 1\n========\n", - "

Header 1

\n", - - "Header 2\n--------\n", - "

Header 2

\n", - - "A\n=\n", - "

A

\n", - - "B\n-\n", - "

B

\n", - - "Paragraph\nHeader\n=\n", - "

Paragraph

\n\n

Header

\n", - - "Header\n===\nParagraph\n", - "

Header

\n\n

Paragraph

\n", - - "Header\n===\nAnother header\n---\n", - "

Header

\n\n

Another header

\n", - - " Header\n======\n", - "

Header

\n", - - "Header with *inline*\n=====\n", - "

Header with inline

\n", - - "Paragraph\n\n\n\n\nHeader\n===\n", - "

Paragraph

\n\n

Header

\n", - - "Trailing space \n==== \n\n", - "

Trailing space

\n", - - "Trailing spaces\n==== \n\n", - "

Trailing spaces

\n", - - "Double underline\n=====\n=====\n", - "

Double underline

\n\n

=====

\n", - - "Header\n======\n\nHeader\n======\n", - "

Header

\n\n

Header

\n", - - "Header 1\n========\n\nHeader 1\n========\n", - "

Header 1

\n\n

Header 1

\n", - } - doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) -} - -func TestHorizontalRule(t *testing.T) { - var tests = []string{ - "-\n", - "

-

\n", - - "--\n", - "

--

\n", - - "---\n", - "
\n", - - "----\n", - "
\n", - - "*\n", - "

*

\n", - - "**\n", - "

**

\n", - - "***\n", - "
\n", - - "****\n", - "
\n", - - "_\n", - "

_

\n", - - "__\n", - "

__

\n", - - "___\n", - "
\n", - - "____\n", - "
\n", - - "-*-\n", - "

-*-

\n", - - "- - -\n", - "
\n", - - "* * *\n", - "
\n", - - "_ _ _\n", - "
\n", - - "-----*\n", - "

-----*

\n", - - " ------ \n", - "
\n", - - "Hello\n***\n", - "

Hello

\n\n
\n", - - "---\n***\n___\n", - "
\n\n
\n\n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestUnorderedList(t *testing.T) { - var tests = []string{ - "* Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "* Yin\n* Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "* Ting\n* Bong\n* Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "* Yin\n\n* Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "* Ting\n\n* Bong\n* Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "+ Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "+ Yin\n+ Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "+ Ting\n+ Bong\n+ Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "+ Yin\n\n+ Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "+ Ting\n\n+ Bong\n+ Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "- Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "- Yin\n- Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "- Ting\n- Bong\n- Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "- Yin\n\n- Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "- Ting\n\n- Bong\n- Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "*Hello\n", - "

*Hello

\n", - - "* Hello \n", - "
    \n
  • Hello
  • \n
\n", - - "* Hello \n Next line \n", - "
    \n
  • Hello\nNext line
  • \n
\n", - - "Paragraph\n* No linebreak\n", - "

Paragraph\n* No linebreak

\n", - - "Paragraph\n\n* Linebreak\n", - "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", - - "* List\n * Nested list\n", - "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n\n * Nested list\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n Second line\n\n + Nested\n", - "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", - - "* List\n + Nested\n\n Continued\n", - "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", - - "* List\n * shallow indent\n", - "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", - - "* List\n" + - " * shallow indent\n" + - " * part of second list\n" + - " * still second\n" + - " * almost there\n" + - " * third level\n", - "
    \n" + - "
  • List\n\n" + - "
      \n" + - "
    • shallow indent
    • \n" + - "
    • part of second list
    • \n" + - "
    • still second
    • \n" + - "
    • almost there\n\n" + - "
        \n" + - "
      • third level
      • \n" + - "
    • \n" + - "
  • \n" + - "
\n", - - "* List\n extra indent, same paragraph\n", - "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", - - "* List\n\n code block\n", - "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", - - "* List\n\n code block with spaces\n", - "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", - - "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", - "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestOrderedList(t *testing.T) { - var tests = []string{ - "1. Hello\n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Yin\n2. Yang\n", - "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", - - "1. Ting\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", - - "1. Yin\n\n2. Yang\n", - "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", - - "1. Ting\n\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", - - "1 Hello\n", - "

1 Hello

\n", - - "1.Hello\n", - "

1.Hello

\n", - - "1. Hello \n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Hello \n Next line \n", - "
    \n
  1. Hello\nNext line
  2. \n
\n", - - "Paragraph\n1. No linebreak\n", - "

Paragraph\n1. No linebreak

\n", - - "Paragraph\n\n1. Linebreak\n", - "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", - - "1. List\n 1. Nested list\n", - "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n\n 1. Nested list\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n Second line\n\n 1. Nested\n", - "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", - - "1. List\n 1. Nested\n\n Continued\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", - - "1. List\n 1. shallow indent\n", - "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", - - "1. List\n" + - " 1. shallow indent\n" + - " 2. part of second list\n" + - " 3. still second\n" + - " 4. almost there\n" + - " 1. third level\n", - "
    \n" + - "
  1. List\n\n" + - "
      \n" + - "
    1. shallow indent
    2. \n" + - "
    3. part of second list
    4. \n" + - "
    5. still second
    6. \n" + - "
    7. almost there\n\n" + - "
        \n" + - "
      1. third level
      2. \n" + - "
    8. \n" + - "
  2. \n" + - "
\n", - - "1. List\n extra indent, same paragraph\n", - "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", - - "1. List\n\n code block\n", - "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", - - "1. List\n\n code block with spaces\n", - "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", - - "1. List\n * Mixted list\n", - "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", - - "1. List\n * Mixed list\n", - "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "1. numbers\n1. are ignored\n", - "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPreformattedHtml(t *testing.T) { - var tests = []string{ - "
\n", - "
\n", - - "
\n
\n", - "
\n
\n", - - "
\n
\nParagraph\n", - "

\n
\nParagraph

\n", - - "
\n
\n", - "
\n
\n", - - "
\nAnything here\n
\n", - "
\nAnything here\n
\n", - - "
\n Anything here\n
\n", - "
\n Anything here\n
\n", - - "
\nAnything here\n
\n", - "
\nAnything here\n
\n", - - "
\nThis is *not* &proceessed\n
\n", - "
\nThis is *not* &proceessed\n
\n", - - "\n Something\n\n", - "

\n Something\n

\n", - - "
\n Something here\n\n", - "

\n Something here\n

\n", - - "Paragraph\n
\nHere? >&<\n
\n", - "

Paragraph\n

\nHere? >&<\n

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n", - - "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", - "

Paragraph\n

\nHere? >&<\n
\nAnd here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n

\nHow about here? >&<\n
\nAnd here?

\n", - - "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", - "

Paragraph\n

\nHere? >&<\n

\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - } - doTestsBlock(t, tests, 0) -} - -func TestPreformattedHtmlLax(t *testing.T) { - var tests = []string{ - "Paragraph\n
\nHere? >&<\n
\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n", - - "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - - "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", - - "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", - "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", - } - doTestsBlock(t, tests, EXTENSION_LAX_HTML_BLOCKS) -} - -func TestFencedCodeBlock(t *testing.T) { - var tests = []string{ - "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", - "
func foo() bool {\n\treturn true;\n}\n
\n", - - "``` c\n/* special & char < > \" escaping */\n```\n", - "
/* special & char < > " escaping */\n
\n", - - "``` c\nno *inline* processing ~~of text~~\n```\n", - "
no *inline* processing ~~of text~~\n
\n", - - "```\nNo language\n```\n", - "
No language\n
\n", - - "``` {ocaml}\nlanguage in braces\n```\n", - "
language in braces\n
\n", - - "``` {ocaml} \nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "```{ ocaml }\nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "~ ~~ java\nWith whitespace\n~~~\n", - "

~ ~~ java\nWith whitespace\n~~~

\n", - - "~~\nonly two\n~~\n", - "

~~\nonly two\n~~

\n", - - "```` python\nextra\n````\n", - "
extra\n
\n", - - "~~~ perl\nthree to start, four to end\n~~~~\n", - "

~~~ perl\nthree to start, four to end\n~~~~

\n", - - "~~~~ perl\nfour to start, three to end\n~~~\n", - "

~~~~ perl\nfour to start, three to end\n~~~

\n", - - "~~~ bash\ntildes\n~~~\n", - "
tildes\n
\n", - - "``` lisp\nno ending\n", - "

``` lisp\nno ending

\n", - - "~~~ lisp\nend with language\n~~~ lisp\n", - "

~~~ lisp\nend with language\n~~~ lisp

\n", - - "```\nmismatched begin and end\n~~~\n", - "

```\nmismatched begin and end\n~~~

\n", - - "~~~\nmismatched begin and end\n```\n", - "

~~~\nmismatched begin and end\n```

\n", - - " ``` oz\nleading spaces\n```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - "``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
``` oz\n
\n\n

leading spaces\n ```

\n", - - "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n", - "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n", - - "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nAnd some text after a fenced code block", - "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

And some text after a fenced code block

\n", - - "`", - "

`

\n", - - "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n\n``` oz\nmultiple code blocks work okay\n```\n\nBla Bla\n", - "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n\n
multiple code blocks work okay\n
\n\n

Bla Bla

\n", - - "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nSome text in between\n``` oz\nmultiple code blocks work okay\n```\nAnd some text after a fenced code block", - "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

Some text in between

\n\n
multiple code blocks work okay\n
\n\n

And some text after a fenced code block

\n", - } - doTestsBlock(t, tests, EXTENSION_FENCED_CODE) -} - -func TestTable(t *testing.T) { - var tests = []string{ - "a | b\n---|---\nc | d\n", - "\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n
ab
cd
\n", - - "a | b\n---|--\nc | d\n", - "

a | b\n---|--\nc | d

\n", - - "|a|b|c|d|\n|----|----|----|---|\n|e|f|g|h|\n", - "\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n
abcd
efgh
\n", - - "*a*|__b__|[c](C)|d\n---|---|---|---\ne|f|g|h\n", - "\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n
abcd
efgh
\n", - - "a|b|c\n---|---|---\nd|e|f\ng|h\ni|j|k|l|m\nn|o|p\n", - "\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n" + - "\n\n\n\n\n\n" + - "\n\n\n\n\n\n
abc
def
gh
ijk
nop
\n", - - "a|b|c\n---|---|---\n*d*|__e__|f\n", - "\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n
abc
def
\n", - - "a|b|c|d\n:--|--:|:-:|---\ne|f|g|h\n", - "\n\n\n\n\n" + - "\n\n\n\n\n" + - "\n\n\n\n" + - "\n\n\n\n
abcd
efgh
\n", - - "a|b|c\n---|---|---\n", - "\n\n\n\n\n\n\n\n\n\n\n
abc
\n", - - "a| b|c | d | e\n---|---|---|---|---\nf| g|h | i |j\n", - "\n\n\n\n\n\n\n\n\n\n\n" + - "\n\n\n\n\n\n\n\n\n
abcde
fghij
\n", - - "a|b\\|c|d\n---|---|---\nf|g\\|h|i\n", - "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ab|cd
fg|hi
\n", - } - doTestsBlock(t, tests, EXTENSION_TABLES) -} - -func TestUnorderedListWith_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "* Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "* Yin\n* Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "* Ting\n* Bong\n* Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "* Yin\n\n* Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "* Ting\n\n* Bong\n* Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "+ Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "+ Yin\n+ Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "+ Ting\n+ Bong\n+ Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "+ Yin\n\n+ Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "+ Ting\n\n+ Bong\n+ Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "- Hello\n", - "
    \n
  • Hello
  • \n
\n", - - "- Yin\n- Yang\n", - "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", - - "- Ting\n- Bong\n- Goo\n", - "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", - - "- Yin\n\n- Yang\n", - "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", - - "- Ting\n\n- Bong\n- Goo\n", - "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", - - "*Hello\n", - "

*Hello

\n", - - "* Hello \n", - "
    \n
  • Hello
  • \n
\n", - - "* Hello \n Next line \n", - "
    \n
  • Hello\nNext line
  • \n
\n", - - "Paragraph\n* No linebreak\n", - "

Paragraph

\n\n
    \n
  • No linebreak
  • \n
\n", - - "Paragraph\n\n* Linebreak\n", - "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", - - "* List\n * Nested list\n", - "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n\n * Nested list\n", - "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", - - "* List\n Second line\n\n + Nested\n", - "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", - - "* List\n + Nested\n\n Continued\n", - "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", - - "* List\n * shallow indent\n", - "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", - - "* List\n" + - " * shallow indent\n" + - " * part of second list\n" + - " * still second\n" + - " * almost there\n" + - " * third level\n", - "
    \n" + - "
  • List\n\n" + - "
      \n" + - "
    • shallow indent
    • \n" + - "
    • part of second list
    • \n" + - "
    • still second
    • \n" + - "
    • almost there\n\n" + - "
        \n" + - "
      • third level
      • \n" + - "
    • \n" + - "
  • \n" + - "
\n", - - "* List\n extra indent, same paragraph\n", - "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", - - "* List\n\n code block\n", - "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", - - "* List\n\n code block with spaces\n", - "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", - - "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", - "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", - } - doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestOrderedList_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "1. Hello\n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Yin\n2. Yang\n", - "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", - - "1. Ting\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", - - "1. Yin\n\n2. Yang\n", - "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", - - "1. Ting\n\n2. Bong\n3. Goo\n", - "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", - - "1 Hello\n", - "

1 Hello

\n", - - "1.Hello\n", - "

1.Hello

\n", - - "1. Hello \n", - "
    \n
  1. Hello
  2. \n
\n", - - "1. Hello \n Next line \n", - "
    \n
  1. Hello\nNext line
  2. \n
\n", - - "Paragraph\n1. No linebreak\n", - "

Paragraph

\n\n
    \n
  1. No linebreak
  2. \n
\n", - - "Paragraph\n\n1. Linebreak\n", - "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", - - "1. List\n 1. Nested list\n", - "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n\n 1. Nested list\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", - - "1. List\n Second line\n\n 1. Nested\n", - "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", - - "1. List\n 1. Nested\n\n Continued\n", - "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", - - "1. List\n 1. shallow indent\n", - "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", - - "1. List\n" + - " 1. shallow indent\n" + - " 2. part of second list\n" + - " 3. still second\n" + - " 4. almost there\n" + - " 1. third level\n", - "
    \n" + - "
  1. List\n\n" + - "
      \n" + - "
    1. shallow indent
    2. \n" + - "
    3. part of second list
    4. \n" + - "
    5. still second
    6. \n" + - "
    7. almost there\n\n" + - "
        \n" + - "
      1. third level
      2. \n" + - "
    8. \n" + - "
  2. \n" + - "
\n", - - "1. List\n extra indent, same paragraph\n", - "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", - - "1. List\n\n code block\n", - "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", - - "1. List\n\n code block with spaces\n", - "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", - - "1. List\n * Mixted list\n", - "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", - - "1. List\n * Mixed list\n", - "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "* Start with unordered\n 1. Ordered\n", - "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", - - "1. numbers\n1. are ignored\n", - "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", - } - doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestFencedCodeBlock_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - var tests = []string{ - "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", - "
func foo() bool {\n\treturn true;\n}\n
\n", - - "``` c\n/* special & char < > \" escaping */\n```\n", - "
/* special & char < > " escaping */\n
\n", - - "``` c\nno *inline* processing ~~of text~~\n```\n", - "
no *inline* processing ~~of text~~\n
\n", - - "```\nNo language\n```\n", - "
No language\n
\n", - - "``` {ocaml}\nlanguage in braces\n```\n", - "
language in braces\n
\n", - - "``` {ocaml} \nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "```{ ocaml }\nwith extra whitespace\n```\n", - "
with extra whitespace\n
\n", - - "~ ~~ java\nWith whitespace\n~~~\n", - "

~ ~~ java\nWith whitespace\n~~~

\n", - - "~~\nonly two\n~~\n", - "

~~\nonly two\n~~

\n", - - "```` python\nextra\n````\n", - "
extra\n
\n", - - "~~~ perl\nthree to start, four to end\n~~~~\n", - "

~~~ perl\nthree to start, four to end\n~~~~

\n", - - "~~~~ perl\nfour to start, three to end\n~~~\n", - "

~~~~ perl\nfour to start, three to end\n~~~

\n", - - "~~~ bash\ntildes\n~~~\n", - "
tildes\n
\n", - - "``` lisp\nno ending\n", - "

``` lisp\nno ending

\n", - - "~~~ lisp\nend with language\n~~~ lisp\n", - "

~~~ lisp\nend with language\n~~~ lisp

\n", - - "```\nmismatched begin and end\n~~~\n", - "

```\nmismatched begin and end\n~~~

\n", - - "~~~\nmismatched begin and end\n```\n", - "

~~~\nmismatched begin and end\n```

\n", - - " ``` oz\nleading spaces\n```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - "``` oz\nleading spaces\n ```\n", - "
leading spaces\n
\n", - - " ``` oz\nleading spaces\n ```\n", - "
``` oz\n
\n\n

leading spaces

\n\n
```\n
\n", - } - doTestsBlock(t, tests, EXTENSION_FENCED_CODE|EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} - -func TestTitleBlock_EXTENSION_TITLEBLOCK(t *testing.T) { - var tests = []string{ - "% Some title\n" + - "% Another title line\n" + - "% Yep, more here too\n", - "

" + - "Some title\n" + - "Another title line\n" + - "Yep, more here too\n" + - "

", - } - - doTestsBlock(t, tests, EXTENSION_TITLEBLOCK) - -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go deleted file mode 100644 index fb3bdec8c4c..00000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go +++ /dev/null @@ -1,859 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Unit tests for inline parsing -// - -package blackfriday - -import ( - "regexp" - "testing" - - "strings" -) - -func runMarkdownInline(input string, extensions, htmlFlags int, params HtmlRendererParameters) string { - extensions |= EXTENSION_AUTOLINK - extensions |= EXTENSION_STRIKETHROUGH - - htmlFlags |= HTML_USE_XHTML - - renderer := HtmlRendererWithParameters(htmlFlags, "", "", params) - - return string(Markdown([]byte(input), renderer, extensions)) -} - -func doTestsInline(t *testing.T, tests []string) { - doTestsInlineParam(t, tests, 0, 0, HtmlRendererParameters{}) -} - -func doLinkTestsInline(t *testing.T, tests []string) { - doTestsInline(t, tests) - - prefix := "http://localhost" - params := HtmlRendererParameters{AbsolutePrefix: prefix} - transformTests := transformLinks(tests, prefix) - doTestsInlineParam(t, transformTests, 0, 0, params) - doTestsInlineParam(t, transformTests, 0, commonHtmlFlags, params) -} - -func doSafeTestsInline(t *testing.T, tests []string) { - doTestsInlineParam(t, tests, 0, HTML_SAFELINK, HtmlRendererParameters{}) - - // All the links in this test should not have the prefix appended, so - // just rerun it with different parameters and the same expectations. - prefix := "http://localhost" - params := HtmlRendererParameters{AbsolutePrefix: prefix} - transformTests := transformLinks(tests, prefix) - doTestsInlineParam(t, transformTests, 0, HTML_SAFELINK, params) -} - -func doTestsInlineParam(t *testing.T, tests []string, extensions, htmlFlags int, - params HtmlRendererParameters) { - // catch and report panics - var candidate string - /* - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v] (%v)\n", candidate, err) - } - }() - */ - - for i := 0; i+1 < len(tests); i += 2 { - input := tests[i] - candidate = input - expected := tests[i+1] - actual := runMarkdownInline(candidate, extensions, htmlFlags, params) - if actual != expected { - t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]", - candidate, expected, actual) - } - - // now test every substring to stress test bounds checking - if !testing.Short() { - for start := 0; start < len(input); start++ { - for end := start + 1; end <= len(input); end++ { - candidate = input[start:end] - _ = runMarkdownInline(candidate, extensions, htmlFlags, params) - } - } - } - } -} - -func transformLinks(tests []string, prefix string) []string { - newTests := make([]string, len(tests)) - anchorRe := regexp.MustCompile(`nothing inline

\n", - - "simple *inline* test\n", - "

simple inline test

\n", - - "*at the* beginning\n", - "

at the beginning

\n", - - "at the *end*\n", - "

at the end

\n", - - "*try two* in *one line*\n", - "

try two in one line

\n", - - "over *two\nlines* test\n", - "

over two\nlines test

\n", - - "odd *number of* markers* here\n", - "

odd number of markers* here

\n", - - "odd *number\nof* markers* here\n", - "

odd number\nof markers* here

\n", - - "simple _inline_ test\n", - "

simple inline test

\n", - - "_at the_ beginning\n", - "

at the beginning

\n", - - "at the _end_\n", - "

at the end

\n", - - "_try two_ in _one line_\n", - "

try two in one line

\n", - - "over _two\nlines_ test\n", - "

over two\nlines test

\n", - - "odd _number of_ markers_ here\n", - "

odd number of markers_ here

\n", - - "odd _number\nof_ markers_ here\n", - "

odd number\nof markers_ here

\n", - - "mix of *markers_\n", - "

mix of *markers_

\n", - } - doTestsInline(t, tests) -} - -func TestStrong(t *testing.T) { - var tests = []string{ - "nothing inline\n", - "

nothing inline

\n", - - "simple **inline** test\n", - "

simple inline test

\n", - - "**at the** beginning\n", - "

at the beginning

\n", - - "at the **end**\n", - "

at the end

\n", - - "**try two** in **one line**\n", - "

try two in one line

\n", - - "over **two\nlines** test\n", - "

over two\nlines test

\n", - - "odd **number of** markers** here\n", - "

odd number of markers** here

\n", - - "odd **number\nof** markers** here\n", - "

odd number\nof markers** here

\n", - - "simple __inline__ test\n", - "

simple inline test

\n", - - "__at the__ beginning\n", - "

at the beginning

\n", - - "at the __end__\n", - "

at the end

\n", - - "__try two__ in __one line__\n", - "

try two in one line

\n", - - "over __two\nlines__ test\n", - "

over two\nlines test

\n", - - "odd __number of__ markers__ here\n", - "

odd number of markers__ here

\n", - - "odd __number\nof__ markers__ here\n", - "

odd number\nof markers__ here

\n", - - "mix of **markers__\n", - "

mix of **markers__

\n", - } - doTestsInline(t, tests) -} - -func TestEmphasisMix(t *testing.T) { - var tests = []string{ - "***triple emphasis***\n", - "

triple emphasis

\n", - - "***triple\nemphasis***\n", - "

triple\nemphasis

\n", - - "___triple emphasis___\n", - "

triple emphasis

\n", - - "***triple emphasis___\n", - "

***triple emphasis___

\n", - - "*__triple emphasis__*\n", - "

triple emphasis

\n", - - "__*triple emphasis*__\n", - "

triple emphasis

\n", - - "**improper *nesting** is* bad\n", - "

improper *nesting is* bad

\n", - - "*improper **nesting* is** bad\n", - "

improper **nesting is** bad

\n", - } - doTestsInline(t, tests) -} - -func TestEmphasisLink(t *testing.T) { - var tests = []string{ - "[first](before) *text[second] (inside)text* [third](after)\n", - "

first textsecondtext third

\n", - - "*incomplete [link] definition*\n", - "

incomplete [link] definition

\n", - - "*it's [emphasis*] (not link)\n", - "

it's [emphasis] (not link)

\n", - - "*it's [emphasis*] and *[asterisk]\n", - "

it's [emphasis] and *[asterisk]

\n", - } - doTestsInline(t, tests) -} - -func TestStrikeThrough(t *testing.T) { - var tests = []string{ - "nothing inline\n", - "

nothing inline

\n", - - "simple ~~inline~~ test\n", - "

simple inline test

\n", - - "~~at the~~ beginning\n", - "

at the beginning

\n", - - "at the ~~end~~\n", - "

at the end

\n", - - "~~try two~~ in ~~one line~~\n", - "

try two in one line

\n", - - "over ~~two\nlines~~ test\n", - "

over two\nlines test

\n", - - "odd ~~number of~~ markers~~ here\n", - "

odd number of markers~~ here

\n", - - "odd ~~number\nof~~ markers~~ here\n", - "

odd number\nof markers~~ here

\n", - } - doTestsInline(t, tests) -} - -func TestCodeSpan(t *testing.T) { - var tests = []string{ - "`source code`\n", - "

source code

\n", - - "` source code with spaces `\n", - "

source code with spaces

\n", - - "` source code with spaces `not here\n", - "

source code with spacesnot here

\n", - - "a `single marker\n", - "

a `single marker

\n", - - "a single multi-tick marker with ``` no text\n", - "

a single multi-tick marker with ``` no text

\n", - - "markers with ` ` a space\n", - "

markers with a space

\n", - - "`source code` and a `stray\n", - "

source code and a `stray

\n", - - "`source *with* _awkward characters_ in it`\n", - "

source *with* _awkward characters_ in it

\n", - - "`split over\ntwo lines`\n", - "

split over\ntwo lines

\n", - - "```multiple ticks``` for the marker\n", - "

multiple ticks for the marker

\n", - - "```multiple ticks `with` ticks inside```\n", - "

multiple ticks `with` ticks inside

\n", - } - doTestsInline(t, tests) -} - -func TestLineBreak(t *testing.T) { - var tests = []string{ - "this line \nhas a break\n", - "

this line
\nhas a break

\n", - - "this line \ndoes not\n", - "

this line\ndoes not

\n", - - "this has an \nextra space\n", - "

this has an
\nextra space

\n", - } - doTestsInline(t, tests) -} - -func TestInlineLink(t *testing.T) { - var tests = []string{ - "[foo](/bar/)\n", - "

foo

\n", - - "[foo with a title](/bar/ \"title\")\n", - "

foo with a title

\n", - - "[foo with a title](/bar/\t\"title\")\n", - "

foo with a title

\n", - - "[foo with a title](/bar/ \"title\" )\n", - "

foo with a title

\n", - - "[foo with a title](/bar/ title with no quotes)\n", - "

foo with a title

\n", - - "[foo]()\n", - "

[foo]()

\n", - - "![foo](/bar/)\n", - "

\"foo\"\n

\n", - - "![foo with a title](/bar/ \"title\")\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/\t\"title\")\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/ \"title\" )\n", - "

\"foo\n

\n", - - "![foo with a title](/bar/ title with no quotes)\n", - "

\"foo\n

\n", - - "![](img.jpg)\n", - "

\"\"\n

\n", - - "[link](url)\n", - "

link

\n", - - "![foo]()\n", - "

![foo]()

\n", - - "[a link]\t(/with_a_tab/)\n", - "

a link

\n", - - "[a link] (/with_spaces/)\n", - "

a link

\n", - - "[text (with) [[nested] (brackets)]](/url/)\n", - "

text (with) [[nested] (brackets)]

\n", - - "[text (with) [broken nested] (brackets)]](/url/)\n", - "

[text (with) broken nested]](/url/)

\n", - - "[text\nwith a newline](/link/)\n", - "

text\nwith a newline

\n", - - "[text in brackets] [followed](/by a link/)\n", - "

[text in brackets] followed

\n", - - "[link with\\] a closing bracket](/url/)\n", - "

link with] a closing bracket

\n", - - "[link with\\[ an opening bracket](/url/)\n", - "

link with[ an opening bracket

\n", - - "[link with\\) a closing paren](/url/)\n", - "

link with) a closing paren

\n", - - "[link with\\( an opening paren](/url/)\n", - "

link with( an opening paren

\n", - - "[link]( with whitespace)\n", - "

link

\n", - - "[link]( with whitespace )\n", - "

link

\n", - - "[![image](someimage)](with image)\n", - "

\"image\"\n

\n", - - "[link](url \"one quote)\n", - "

link

\n", - - "[link](url 'one quote)\n", - "

link

\n", - - "[link]()\n", - "

link

\n", - - "[link & ampersand](/url/)\n", - "

link & ampersand

\n", - - "[link & ampersand](/url/)\n", - "

link & ampersand

\n", - - "[link](/url/&query)\n", - "

link

\n", - - "[[t]](/t)\n", - "

[t]

\n", - } - doLinkTestsInline(t, tests) - -} - -func TestNofollowLink(t *testing.T) { - var tests = []string{ - "[foo](http://bar.com/foo/)\n", - "

foo

\n", - - "[foo](/bar/)\n", - "

foo

\n", - } - doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_NOFOLLOW_LINKS, - HtmlRendererParameters{}) -} - -func TestHrefTargetBlank(t *testing.T) { - var tests = []string{ - // internal link - "[foo](/bar/)\n", - "

foo

\n", - - "[foo](http://example.com)\n", - "

foo

\n", - } - doTestsInlineParam(t, tests, 0, HTML_SAFELINK|HTML_HREF_TARGET_BLANK, HtmlRendererParameters{}) -} - -func TestSafeInlineLink(t *testing.T) { - var tests = []string{ - "[foo](/bar/)\n", - "

foo

\n", - - "[foo](http://bar/)\n", - "

foo

\n", - - "[foo](https://bar/)\n", - "

foo

\n", - - "[foo](ftp://bar/)\n", - "

foo

\n", - - "[foo](mailto://bar/)\n", - "

foo

\n", - - // Not considered safe - "[foo](baz://bar/)\n", - "

foo

\n", - } - doSafeTestsInline(t, tests) -} - -func TestReferenceLink(t *testing.T) { - var tests = []string{ - "[link][ref]\n", - "

[link][ref]

\n", - - "[link][ref]\n [ref]: /url/ \"title\"\n", - "

link

\n", - - "[link][ref]\n [ref]: /url/\n", - "

link

\n", - - " [ref]: /url/\n", - "", - - " [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n", - "", - - " [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n [4spaces]: /url/\n", - "
[4spaces]: /url/\n
\n", - - "[hmm](ref2)\n [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n", - "

hmm

\n", - - "[ref]\n", - "

[ref]

\n", - - "[ref]\n [ref]: /url/ \"title\"\n", - "

ref

\n", - } - doLinkTestsInline(t, tests) -} - -func TestTags(t *testing.T) { - var tests = []string{ - "a tag\n", - "

a tag

\n", - - "tag\n", - "

tag

\n", - - "mismatch\n", - "

mismatch

\n", - - "a tag\n", - "

a tag

\n", - } - doTestsInline(t, tests) -} - -func TestAutoLink(t *testing.T) { - var tests = []string{ - "http://foo.com/\n", - "

http://foo.com/

\n", - - "1 http://foo.com/\n", - "

1 http://foo.com/

\n", - - "1http://foo.com/\n", - "

1http://foo.com/

\n", - - "1.http://foo.com/\n", - "

1.http://foo.com/

\n", - - "1. http://foo.com/\n", - "
    \n
  1. http://foo.com/
  2. \n
\n", - - "-http://foo.com/\n", - "

-http://foo.com/

\n", - - "- http://foo.com/\n", - "\n", - - "_http://foo.com/\n", - "

_http://foo.com/

\n", - - "令狐http://foo.com/\n", - "

令狐http://foo.com/

\n", - - "令狐 http://foo.com/\n", - "

令狐 http://foo.com/

\n", - - "ahttp://foo.com/\n", - "

ahttp://foo.com/

\n", - - ">http://foo.com/\n", - "
\n

http://foo.com/

\n
\n", - - "> http://foo.com/\n", - "
\n

http://foo.com/

\n
\n", - - "go to \n", - "

go to http://foo.com/

\n", - - "a secure \n", - "

a secure https://link.org

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an email \n", - "

an email some@one.com

\n", - - "an ftp \n", - "

an ftp ftp://old.com

\n", - - "an ftp \n", - "

an ftp ftp:old.com

\n", - - "a link with \n", - "

a link with " + - "http://new.com?query=foo&bar

\n", - - "quotes mean a tag \n", - "

quotes mean a tag

\n", - - "quotes mean a tag \n", - "

quotes mean a tag

\n", - - "unless escaped \n", - "

unless escaped " + - "http://new.com?query="foo"&bar

\n", - - "even a > can be escaped &etc>\n", - "

even a > can be escaped " + - "http://new.com?q=>&etc

\n", - - "http://fancy.com\n", - "

http://fancy.com

\n", - - "This is a link\n", - "

This is a link

\n", - - "http://www.fancy.com/A_B.pdf\n", - "

http://www.fancy.com/A_B.pdf

\n", - - "(http://www.fancy.com/A_B (\n", - "

(http://www.fancy.com/A_B (

\n", - - "(http://www.fancy.com/A_B (part two: http://www.fancy.com/A_B)).\n", - "

(http://www.fancy.com/A_B (part two: http://www.fancy.com/A_B)).

\n", - - "http://www.foo.com
\n", - "

http://www.foo.com

\n", - - "http://foo.com/viewtopic.php?f=18&t=297", - "

http://foo.com/viewtopic.php?f=18&t=297

\n", - - "http://foo.com/viewtopic.php?param="18"zz", - "

http://foo.com/viewtopic.php?param="18"zz

\n", - - "http://foo.com/viewtopic.php?param="18"", - "

http://foo.com/viewtopic.php?param="18"

\n", - } - doLinkTestsInline(t, tests) -} - -var footnoteTests = []string{ - "testing footnotes.[^a]\n\n[^a]: This is the note\n", - `

testing footnotes.1

-
- -
- -
    -
  1. This is the note -
  2. -
-
-`, - - `testing long[^b] notes. - -[^b]: Paragraph 1 - - Paragraph 2 - - ` + "```\n\tsome code\n\t```" + ` - - Paragraph 3 - -No longer in the footnote -`, - `

testing long1 notes.

- -

No longer in the footnote

-
- -
- -
    -
  1. Paragraph 1

    - -

    Paragraph 2

    - -

    -some code -

    - -

    Paragraph 3

    -
  2. -
-
-`, - - `testing[^c] multiple[^d] notes. - -[^c]: this is [note] c - - -omg - -[^d]: this is note d - -what happens here - -[note]: /link/c - -`, - `

testing1 multiple2 notes.

- -

omg

- -

what happens here

-
- -
- -
    -
  1. this is note c -
  2. -
  3. this is note d -
  4. -
-
-`, - - "testing inline^[this is the note] notes.\n", - `

testing inline1 notes.

-
- -
- -
    -
  1. this is the note
  2. -
-
-`, - - "testing multiple[^1] types^[inline note] of notes[^2]\n\n[^2]: the second deferred note\n[^1]: the first deferred note\n\n\twhich happens to be a block\n", - `

testing multiple1 types2 of notes3

-
- -
- -
    -
  1. the first deferred note

    - -

    which happens to be a block

    -
  2. -
  3. inline note
  4. -
  5. the second deferred note -
  6. -
-
-`, - - `This is a footnote[^1]^[and this is an inline footnote] - -[^1]: the footnote text. - - may be multiple paragraphs. -`, - `

This is a footnote12

-
- -
- -
    -
  1. the footnote text.

    - -

    may be multiple paragraphs.

    -
  2. -
  3. and this is an inline footnote
  4. -
-
-`, - - "empty footnote[^]\n\n[^]: fn text", - "

empty footnote1

\n
\n\n
\n\n
    \n
  1. fn text\n
  2. \n
\n
\n", -} - -func TestFootnotes(t *testing.T) { - doTestsInlineParam(t, footnoteTests, EXTENSION_FOOTNOTES, 0, HtmlRendererParameters{}) -} - -func TestFootnotesWithParameters(t *testing.T) { - tests := make([]string, len(footnoteTests)) - - prefix := "testPrefix" - returnText := "ret" - re := regexp.MustCompile(`(?ms)
  • (.*?)
  • `) - - // Transform the test expectations to match the parameters we're using. - for i, test := range footnoteTests { - if i%2 == 1 { - test = strings.Replace(test, "fn:", "fn:"+prefix, -1) - test = strings.Replace(test, "fnref:", "fnref:"+prefix, -1) - test = re.ReplaceAllString(test, `
  • $2 ret
  • `) - } - tests[i] = test - } - - params := HtmlRendererParameters{ - FootnoteAnchorPrefix: prefix, - FootnoteReturnLinkContents: returnText, - } - - doTestsInlineParam(t, tests, EXTENSION_FOOTNOTES, HTML_FOOTNOTE_RETURN_LINKS, params) -} - -func TestSmartDoubleQuotes(t *testing.T) { - var tests = []string{ - "this should be normal \"quoted\" text.\n", - "

    this should be normal “quoted” text.

    \n", - "this \" single double\n", - "

    this “ single double

    \n", - "two pair of \"some\" quoted \"text\".\n", - "

    two pair of “some” quoted “text”.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS, HtmlRendererParameters{}) -} - -func TestSmartAngledDoubleQuotes(t *testing.T) { - var tests = []string{ - "this should be angled \"quoted\" text.\n", - "

    this should be angled «quoted» text.

    \n", - "this \" single double\n", - "

    this « single double

    \n", - "two pair of \"some\" quoted \"text\".\n", - "

    two pair of «some» quoted «text».

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_ANGLED_QUOTES, HtmlRendererParameters{}) -} - -func TestSmartFractions(t *testing.T) { - var tests = []string{ - "1/2, 1/4 and 3/4; 1/4th and 3/4ths\n", - "

    ½, ¼ and ¾; ¼th and ¾ths

    \n", - "1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n", - "

    1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS, HtmlRendererParameters{}) - - tests = []string{ - "1/2, 2/3, 81/100 and 1000000/1048576.\n", - "

    12, 23, 81100 and 10000001048576.

    \n", - "1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n", - "

    1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.

    \n"} - - doTestsInlineParam(t, tests, 0, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_FRACTIONS, HtmlRendererParameters{}) -} diff --git a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go b/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go deleted file mode 100644 index 42a0bdd52ab..00000000000 --- a/Godeps/_workspace/src/github.com/russross/blackfriday/upskirtref_test.go +++ /dev/null @@ -1,128 +0,0 @@ -// -// Blackfriday Markdown Processor -// Available at http://github.com/russross/blackfriday -// -// Copyright © 2011 Russ Ross . -// Distributed under the Simplified BSD License. -// See README.md for details. -// - -// -// Markdown 1.0.3 reference tests -// - -package blackfriday - -import ( - "io/ioutil" - "path/filepath" - "testing" -) - -func runMarkdownReference(input string, flag int) string { - renderer := HtmlRenderer(0, "", "") - return string(Markdown([]byte(input), renderer, flag)) -} - -func doTestsReference(t *testing.T, files []string, flag int) { - // catch and report panics - var candidate string - defer func() { - if err := recover(); err != nil { - t.Errorf("\npanic while processing [%#v]\n", candidate) - } - }() - - for _, basename := range files { - filename := filepath.Join("upskirtref", basename+".text") - inputBytes, err := ioutil.ReadFile(filename) - if err != nil { - t.Errorf("Couldn't open '%s', error: %v\n", filename, err) - continue - } - input := string(inputBytes) - - filename = filepath.Join("upskirtref", basename+".html") - expectedBytes, err := ioutil.ReadFile(filename) - if err != nil { - t.Errorf("Couldn't open '%s', error: %v\n", filename, err) - continue - } - expected := string(expectedBytes) - - // fmt.Fprintf(os.Stderr, "processing %s ...", filename) - actual := string(runMarkdownReference(input, flag)) - if actual != expected { - t.Errorf("\n [%#v]\nExpected[%#v]\nActual [%#v]", - basename+".text", expected, actual) - } - // fmt.Fprintf(os.Stderr, " ok\n") - - // now test every prefix of every input to check for - // bounds checking - if !testing.Short() { - start, max := 0, len(input) - for end := start + 1; end <= max; end++ { - candidate = input[start:end] - // fmt.Fprintf(os.Stderr, " %s %d:%d/%d\n", filename, start, end, max) - _ = runMarkdownReference(candidate, flag) - } - } - } -} - -func TestReference(t *testing.T) { - files := []string{ - "Amps and angle encoding", - "Auto links", - "Backslash escapes", - "Blockquotes with code blocks", - "Code Blocks", - "Code Spans", - "Hard-wrapped paragraphs with list-like lines", - "Horizontal rules", - "Inline HTML (Advanced)", - "Inline HTML (Simple)", - "Inline HTML comments", - "Links, inline style", - "Links, reference style", - "Links, shortcut references", - "Literal quotes in titles", - "Markdown Documentation - Basics", - "Markdown Documentation - Syntax", - "Nested blockquotes", - "Ordered and unordered lists", - "Strong and em together", - "Tabs", - "Tidyness", - } - doTestsReference(t, files, 0) -} - -func TestReference_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { - files := []string{ - "Amps and angle encoding", - "Auto links", - "Backslash escapes", - "Blockquotes with code blocks", - "Code Blocks", - "Code Spans", - "Hard-wrapped paragraphs with list-like lines no empty line before block", - "Horizontal rules", - "Inline HTML (Advanced)", - "Inline HTML (Simple)", - "Inline HTML comments", - "Links, inline style", - "Links, reference style", - "Links, shortcut references", - "Literal quotes in titles", - "Markdown Documentation - Basics", - "Markdown Documentation - Syntax", - "Nested blockquotes", - "Ordered and unordered lists", - "Strong and em together", - "Tabs", - "Tidyness", - } - doTestsReference(t, files, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) -} 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 b8571734ec2..00000000000 --- 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 9fe6b04cebe..00000000000 --- 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 63907268d93..00000000000 --- 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 8a3478a3362..00000000000 --- 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 cafbbd95c26..00000000000 --- 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 b56f77550d0..00000000000 --- 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 fdbe517273e..00000000000 --- 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/scalingdata/gcfg/example_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/example_test.go deleted file mode 100644 index 7fa554c0837..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/example_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package gcfg_test - -import ( - "fmt" - "log" -) - -import "github.com/scalingdata/gcfg" - -func ExampleReadStringInto() { - cfgStr := `; Comment line -[section] -name=value # comment` - cfg := struct { - Section struct { - Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Name) - // Output: value -} - -func ExampleReadStringInto_bool() { - cfgStr := `; Comment line -[section] -switch=on` - cfg := struct { - Section struct { - Switch bool - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Switch) - // Output: true -} - -func ExampleReadStringInto_hyphens() { - cfgStr := `; Comment line -[section-name] -variable-name=value # comment` - cfg := struct { - Section_Name struct { - Variable_Name string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section_Name.Variable_Name) - // Output: value -} - -func ExampleReadStringInto_tags() { - cfgStr := `; Comment line -[section] -var-name=value # comment` - cfg := struct { - Section struct { - FieldName string `gcfg:"var-name"` - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.FieldName) - // Output: value -} - -func ExampleReadStringInto_subsections() { - cfgStr := `; Comment line -[profile "A"] -color = white - -[profile "B"] -color = black -` - cfg := struct { - Profile map[string]*struct { - Color string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Printf("%s %s\n", cfg.Profile["A"].Color, cfg.Profile["B"].Color) - // Output: white black -} - -func ExampleReadStringInto_multivalue() { - cfgStr := `; Comment line -[section] -multi=value1 -multi=value2` - cfg := struct { - Section struct { - Multi []string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.Section.Multi) - // Output: [value1 value2] -} - -func ExampleReadStringInto_unicode() { - cfgStr := `; Comment line -[甲] -乙=丙 # comment` - cfg := struct { - X甲 struct { - X乙 string - } - }{} - err := gcfg.ReadStringInto(&cfg, cfgStr) - if err != nil { - log.Fatalf("Failed to parse gcfg data: %s", err) - } - fmt.Println(cfg.X甲.X乙) - // Output: 丙 -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go deleted file mode 100644 index 796dd10b6f7..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/issues_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "strings" - "testing" -) - -type Config1 struct { - Section struct { - Int int - BigInt big.Int - } -} - -var testsIssue1 = []struct { - cfg string - typename string -}{ - {"[section]\nint=X", "int"}, - {"[section]\nint=", "int"}, - {"[section]\nint=1A", "int"}, - {"[section]\nbigint=X", "big.Int"}, - {"[section]\nbigint=", "big.Int"}, - {"[section]\nbigint=1A", "big.Int"}, -} - -// Value parse error should: -// - include plain type name -// - not include reflect internals -func TestIssue1(t *testing.T) { - for i, tt := range testsIssue1 { - var c Config1 - err := ReadStringInto(&c, tt.cfg) - switch { - case err == nil: - t.Errorf("%d fail: got ok; wanted error", i) - case !strings.Contains(err.Error(), tt.typename): - t.Errorf("%d fail: error message doesn't contain type name %q: %v", - i, tt.typename, err) - case strings.Contains(err.Error(), "reflect"): - t.Errorf("%d fail: error message includes reflect internals: %v", - i, err) - default: - t.Logf("%d pass: %v", i, err) - } - } -} - -type confIssue2 struct{ Main struct{ Foo string } } - -var testsIssue2 = []readtest{ - {"[main]\n;\nfoo = bar\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, - {"[main]\r\n;\r\nfoo = bar\r\n", &confIssue2{struct{ Foo string }{"bar"}}, true}, -} - -func TestIssue2(t *testing.T) { - for i, tt := range testsIssue2 { - id := fmt.Sprintf("issue2:%d", i) - testRead(t, id, tt) - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go deleted file mode 100644 index 4a7d8e191f5..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/read_test.go +++ /dev/null @@ -1,333 +0,0 @@ -package gcfg - -import ( - "fmt" - "math/big" - "os" - "reflect" - "testing" -) - -const ( - // 64 spaces - sp64 = " " - // 512 spaces - sp512 = sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 + sp64 - // 4096 spaces - sp4096 = sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 + sp512 -) - -type cBasic struct { - Section cBasicS1 - Hyphen_In_Section cBasicS2 - unexported cBasicS1 - Exported cBasicS3 - TagName cBasicS1 `gcfg:"tag-name"` -} -type cBasicS1 struct { - Name string - Int int - PName *string -} -type cBasicS2 struct { - Hyphen_In_Name string -} -type cBasicS3 struct { - unexported string -} - -type nonMulti []string - -type unmarshalable string - -func (u *unmarshalable) UnmarshalText(text []byte) error { - s := string(text) - if s == "error" { - return fmt.Errorf("%s", s) - } - *u = unmarshalable(s) - return nil -} - -var _ textUnmarshaler = new(unmarshalable) - -type cUni struct { - X甲 cUniS1 - XSection cUniS2 -} -type cUniS1 struct { - X乙 string -} -type cUniS2 struct { - XName string -} - -type cMulti struct { - M1 cMultiS1 - M2 cMultiS2 - M3 cMultiS3 -} -type cMultiS1 struct{ Multi []string } -type cMultiS2 struct{ NonMulti nonMulti } -type cMultiS3 struct{ MultiInt []int } - -type cSubs struct{ Sub map[string]*cSubsS1 } -type cSubsS1 struct{ Name string } - -type cBool struct{ Section cBoolS1 } -type cBoolS1 struct{ Bool bool } - -type cTxUnm struct{ Section cTxUnmS1 } -type cTxUnmS1 struct{ Name unmarshalable } - -type cNum struct { - N1 cNumS1 - N2 cNumS2 - N3 cNumS3 -} -type cNumS1 struct { - Int int - IntDHO int `gcfg:",int=dho"` - Big *big.Int -} -type cNumS2 struct { - MultiInt []int - MultiBig []*big.Int -} -type cNumS3 struct{ FileMode os.FileMode } -type readtest struct { - gcfg string - exp interface{} - ok bool -} - -func newString(s string) *string { - return &s -} - -var readtests = []struct { - group string - tests []readtest -}{{"scanning", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // quoted string value - {"[section]\nname=\"\"", &cBasic{Section: cBasicS1{Name: ""}}, true}, - {"[section]\nname=\" \"", &cBasic{Section: cBasicS1{Name: " "}}, true}, - {"[section]\nname=\"value\"", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=\" value \"", &cBasic{Section: cBasicS1{Name: " value "}}, true}, - {"\n[section]\nname=\"va ; lue\"", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"[section]\nname=\"val\" \"ue\"", &cBasic{Section: cBasicS1{Name: "val ue"}}, true}, - {"[section]\nname=\"value", &cBasic{}, false}, - // escape sequences - {"[section]\nname=\"va\\\\lue\"", &cBasic{Section: cBasicS1{Name: "va\\lue"}}, true}, - {"[section]\nname=\"va\\\"lue\"", &cBasic{Section: cBasicS1{Name: "va\"lue"}}, true}, - {"[section]\nname=\"va\\nlue\"", &cBasic{Section: cBasicS1{Name: "va\nlue"}}, true}, - {"[section]\nname=\"va\\tlue\"", &cBasic{Section: cBasicS1{Name: "va\tlue"}}, true}, - {"\n[section]\nname=\\", &cBasic{}, false}, - {"\n[section]\nname=\\a", &cBasic{}, false}, - {"\n[section]\nname=\"val\\a\"", &cBasic{}, false}, - {"\n[section]\nname=val\\", &cBasic{}, false}, - {"\n[sub \"A\\\n\"]\nname=value", &cSubs{}, false}, - {"\n[sub \"A\\\t\"]\nname=value", &cSubs{}, false}, - // broken line - {"[section]\nname=value \\\n value", &cBasic{Section: cBasicS1{Name: "value value"}}, true}, - {"[section]\nname=\"value \\\n value\"", &cBasic{}, false}, -}}, {"scanning:whitespace", []readtest{ - {" \n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" [section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[ section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section ]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n name=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname =value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname= value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value ", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {";cmnt\r\n[section]\r\nname=value\r\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // long lines - {sp4096 + "[section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[" + sp4096 + "section]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section" + sp4096 + "]\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]" + sp4096 + "\nname=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\n" + sp4096 + "name=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname" + sp4096 + "=value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=" + sp4096 + "value\n", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=value\n" + sp4096, &cBasic{Section: cBasicS1{Name: "value"}}, true}, -}}, {"scanning:comments", []readtest{ - {"; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"# cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {" ; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\t; cmnt\n[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section] ; cmnt\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"value\" ; cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=value ; \"cmnt", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"\n[section]\nname=\"va ; lue\" ; cmnt", &cBasic{Section: cBasicS1{Name: "va ; lue"}}, true}, - {"\n[section]\nname=; cmnt", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"scanning:subsections", []readtest{ - {"\n[sub \"A\"]\nname=value", &cSubs{map[string]*cSubsS1{"A": &cSubsS1{"value"}}}, true}, - {"\n[sub \"b\"]\nname=value", &cSubs{map[string]*cSubsS1{"b": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\\\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\\": &cSubsS1{"value"}}}, true}, - {"\n[sub \"A\\\"\"]\nname=value", &cSubs{map[string]*cSubsS1{"A\"": &cSubsS1{"value"}}}, true}, -}}, {"syntax", []readtest{ - // invalid line - {"\n[section]\n=", &cBasic{}, false}, - // no section - {"name=value", &cBasic{}, false}, - // empty section - {"\n[]\nname=value", &cBasic{}, false}, - // empty subsection - {"\n[sub \"\"]\nname=value", &cSubs{}, false}, -}}, {"setting", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - // pointer - {"[section]", &cBasic{Section: cBasicS1{PName: nil}}, true}, - {"[section]\npname=value", &cBasic{Section: cBasicS1{PName: newString("value")}}, true}, - // section name not matched - {"\n[nonexistent]\nname=value", &cBasic{}, false}, - // subsection name not matched - {"\n[section \"nonexistent\"]\nname=value", &cBasic{}, false}, - // variable name not matched - {"\n[section]\nnonexistent=value", &cBasic{}, false}, - // hyphen in name - {"[hyphen-in-section]\nhyphen-in-name=value", &cBasic{Hyphen_In_Section: cBasicS2{Hyphen_In_Name: "value"}}, true}, - // ignore unexported fields - {"[unexported]\nname=value", &cBasic{}, false}, - {"[exported]\nunexported=value", &cBasic{}, false}, - // 'X' prefix for non-upper/lower-case letters - {"[甲]\n乙=丙", &cUni{X甲: cUniS1{X乙: "丙"}}, true}, - //{"[section]\nxname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - //{"[xsection]\nname=value", &cBasic{XSection: cBasicS4{XName: "value"}}, false}, - // name specified as struct tag - {"[tag-name]\nname=value", &cBasic{TagName: cBasicS1{Name: "value"}}, true}, -}}, {"multivalue", []readtest{ - // unnamed slice type: treat as multi-value - {"\n[m1]", &cMulti{M1: cMultiS1{}}, true}, - {"\n[m1]\nmulti=value", &cMulti{M1: cMultiS1{[]string{"value"}}}, true}, - {"\n[m1]\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // "blank" empties multi-valued slice -- here same result as above - {"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true}, - // named slice type: do not treat as multi-value - {"\n[m2]", &cMulti{}, true}, - {"\n[m2]\nmulti=value", &cMulti{}, false}, - {"\n[m2]\nmulti=value1\nmulti=value2", &cMulti{}, false}, -}}, {"type:string", []readtest{ - {"[section]\nname=value", &cBasic{Section: cBasicS1{Name: "value"}}, true}, - {"[section]\nname=", &cBasic{Section: cBasicS1{Name: ""}}, true}, -}}, {"type:bool", []readtest{ - // explicit values - {"[section]\nbool=true", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=yes", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=on", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=1", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=tRuE", &cBool{cBoolS1{true}}, true}, - {"[section]\nbool=false", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=no", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=off", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=0", &cBool{cBoolS1{false}}, true}, - {"[section]\nbool=NO", &cBool{cBoolS1{false}}, true}, - // "blank" value handled as true - {"[section]\nbool", &cBool{cBoolS1{true}}, true}, - // bool parse errors - {"[section]\nbool=maybe", &cBool{}, false}, - {"[section]\nbool=t", &cBool{}, false}, - {"[section]\nbool=truer", &cBool{}, false}, - {"[section]\nbool=2", &cBool{}, false}, - {"[section]\nbool=-1", &cBool{}, false}, -}}, {"type:numeric", []readtest{ - {"[section]\nint=0", &cBasic{Section: cBasicS1{Int: 0}}, true}, - {"[section]\nint=1", &cBasic{Section: cBasicS1{Int: 1}}, true}, - {"[section]\nint=-1", &cBasic{Section: cBasicS1{Int: -1}}, true}, - {"[section]\nint=0.2", &cBasic{}, false}, - {"[section]\nint=1e3", &cBasic{}, false}, - // primitive [u]int(|8|16|32|64) and big.Int is parsed as dec or hex (not octal) - {"[n1]\nint=010", &cNum{N1: cNumS1{Int: 10}}, true}, - {"[n1]\nint=0x10", &cNum{N1: cNumS1{Int: 0x10}}, true}, - {"[n1]\nbig=1", &cNum{N1: cNumS1{Big: big.NewInt(1)}}, true}, - {"[n1]\nbig=0x10", &cNum{N1: cNumS1{Big: big.NewInt(0x10)}}, true}, - {"[n1]\nbig=010", &cNum{N1: cNumS1{Big: big.NewInt(10)}}, true}, - {"[n2]\nmultiint=010", &cNum{N2: cNumS2{MultiInt: []int{10}}}, true}, - {"[n2]\nmultibig=010", &cNum{N2: cNumS2{MultiBig: []*big.Int{big.NewInt(10)}}}, true}, - // set parse mode for int types via struct tag - {"[n1]\nintdho=010", &cNum{N1: cNumS1{IntDHO: 010}}, true}, - // octal allowed for named type - {"[n3]\nfilemode=0777", &cNum{N3: cNumS3{FileMode: 0777}}, true}, -}}, {"type:textUnmarshaler", []readtest{ - {"[section]\nname=value", &cTxUnm{Section: cTxUnmS1{Name: "value"}}, true}, - {"[section]\nname=error", &cTxUnm{}, false}, -}}, -} - -func TestReadStringInto(t *testing.T) { - for _, tg := range readtests { - for i, tt := range tg.tests { - id := fmt.Sprintf("%s:%d", tg.group, i) - testRead(t, id, tt) - } - } -} - -func TestReadStringIntoMultiBlankPreset(t *testing.T) { - tt := readtest{"\n[m1]\nmulti\nmulti=value1\nmulti=value2", &cMulti{M1: cMultiS1{[]string{"value1", "value2"}}}, true} - cfg := &cMulti{M1: cMultiS1{[]string{"preset1", "preset2"}}} - testReadInto(t, "multi:blank", tt, cfg) -} - -func testRead(t *testing.T, id string, tt readtest) { - // get the type of the expected result - restyp := reflect.TypeOf(tt.exp).Elem() - // create a new instance to hold the actual result - res := reflect.New(restyp).Interface() - testReadInto(t, id, tt, res) -} - -func testReadInto(t *testing.T, id string, tt readtest, res interface{}) { - err := ReadStringInto(res, tt.gcfg) - if tt.ok { - if err != nil { - t.Errorf("%s fail: got error %v, wanted ok", id, err) - return - } else if !reflect.DeepEqual(res, tt.exp) { - t.Errorf("%s fail: got value %#v, wanted value %#v", id, res, tt.exp) - return - } - if !testing.Short() { - t.Logf("%s pass: got value %#v", id, res) - } - } else { // !tt.ok - if err == nil { - t.Errorf("%s fail: got value %#v, wanted error", id, res) - return - } - if !testing.Short() { - t.Logf("%s pass: got error %v", id, err) - } - } -} - -func TestReadFileInto(t *testing.T) { - res := &struct{ Section struct{ Name string } }{} - err := ReadFileInto(res, "testdata/gcfg_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "value" != res.Section.Name { - t.Errorf("got %q, wanted %q", res.Section.Name, "value") - } -} - -func TestReadFileIntoUnicode(t *testing.T) { - res := &struct{ X甲 struct{ X乙 string } }{} - err := ReadFileInto(res, "testdata/gcfg_unicode_test.gcfg") - if err != nil { - t.Errorf(err.Error()) - } - if "丙" != res.X甲.X乙 { - t.Errorf("got %q, wanted %q", res.X甲.X乙, "丙") - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_test.go deleted file mode 100644 index 1a15f6b78df..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/example_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. - -package scanner_test - -import ( - "fmt" -) - -import ( - "github.com/scalingdata/gcfg/scanner" - "github.com/scalingdata/gcfg/token" -) - -func ExampleScanner_Scan() { - // src is the input that we want to tokenize. - src := []byte(`[profile "A"] -color = blue ; Comment`) - - // Initialize the scanner. - var s scanner.Scanner - fset := token.NewFileSet() // positions are relative to fset - file := fset.AddFile("", fset.Base(), len(src)) // register input "file" - s.Init(file, src, nil /* no error handler */, scanner.ScanComments) - - // Repeated calls to Scan yield the token sequence found in the input. - for { - pos, tok, lit := s.Scan() - if tok == token.EOF { - break - } - fmt.Printf("%s\t%q\t%q\n", fset.Position(pos), tok, lit) - } - - // output: - // 1:1 "[" "" - // 1:2 "IDENT" "profile" - // 1:10 "STRING" "\"A\"" - // 1:13 "]" "" - // 1:14 "\n" "" - // 2:1 "IDENT" "color" - // 2:7 "=" "" - // 2:9 "STRING" "blue" - // 2:14 "COMMENT" "; Comment" -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go deleted file mode 100644 index e4015736e09..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/scanner/scanner_test.go +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package scanner - -import ( - "os" - "strings" - "testing" -) - -import ( - "github.com/scalingdata/gcfg/token" -) - -var fset = token.NewFileSet() - -const /* class */ ( - special = iota - literal - operator -) - -func tokenclass(tok token.Token) int { - switch { - case tok.IsLiteral(): - return literal - case tok.IsOperator(): - return operator - } - return special -} - -type elt struct { - tok token.Token - lit string - class int - pre string - suf string -} - -var tokens = [...]elt{ - // Special tokens - {token.COMMENT, "; a comment", special, "", "\n"}, - {token.COMMENT, "# a comment", special, "", "\n"}, - - // Operators and delimiters - {token.ASSIGN, "=", operator, "", "value"}, - {token.LBRACK, "[", operator, "", ""}, - {token.RBRACK, "]", operator, "", ""}, - {token.EOL, "\n", operator, "", ""}, - - // Identifiers - {token.IDENT, "foobar", literal, "", ""}, - {token.IDENT, "a۰۱۸", literal, "", ""}, - {token.IDENT, "foo६४", literal, "", ""}, - {token.IDENT, "bar9876", literal, "", ""}, - {token.IDENT, "foo-bar", literal, "", ""}, - {token.IDENT, "foo", literal, ";\n", ""}, - // String literals (subsection names) - {token.STRING, `"foobar"`, literal, "", ""}, - {token.STRING, `"\""`, literal, "", ""}, - // String literals (values) - {token.STRING, `"\n"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foo\nbar"`, literal, "=", ""}, - {token.STRING, `"foo\"bar"`, literal, "=", ""}, - {token.STRING, `"foo\\bar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "=", ""}, - {token.STRING, `"foobar"`, literal, "= ", ""}, - {token.STRING, `"foobar"`, literal, "=", "\n"}, - {token.STRING, `"foobar"`, literal, "=", ";"}, - {token.STRING, `"foobar"`, literal, "=", " ;"}, - {token.STRING, `"foobar"`, literal, "=", "#"}, - {token.STRING, `"foobar"`, literal, "=", " #"}, - {token.STRING, "foobar", literal, "=", ""}, - {token.STRING, "foobar", literal, "= ", ""}, - {token.STRING, "foobar", literal, "=", " "}, - {token.STRING, `"foo" "bar"`, literal, "=", " "}, - {token.STRING, "foo\\\nbar", literal, "=", ""}, - {token.STRING, "foo\\\r\nbar", literal, "=", ""}, -} - -const whitespace = " \t \n\n\n" // to separate tokens - -var source = func() []byte { - var src []byte - for _, t := range tokens { - src = append(src, t.pre...) - src = append(src, t.lit...) - src = append(src, t.suf...) - src = append(src, whitespace...) - } - return src -}() - -func newlineCount(s string) int { - n := 0 - for i := 0; i < len(s); i++ { - if s[i] == '\n' { - n++ - } - } - return n -} - -func checkPos(t *testing.T, lit string, p token.Pos, expected token.Position) { - pos := fset.Position(p) - if pos.Filename != expected.Filename { - t.Errorf("bad filename for %q: got %s, expected %s", lit, pos.Filename, expected.Filename) - } - if pos.Offset != expected.Offset { - t.Errorf("bad position for %q: got %d, expected %d", lit, pos.Offset, expected.Offset) - } - if pos.Line != expected.Line { - t.Errorf("bad line for %q: got %d, expected %d", lit, pos.Line, expected.Line) - } - if pos.Column != expected.Column { - t.Errorf("bad column for %q: got %d, expected %d", lit, pos.Column, expected.Column) - } -} - -// Verify that calling Scan() provides the correct results. -func TestScan(t *testing.T) { - // make source - src_linecount := newlineCount(string(source)) - whitespace_linecount := newlineCount(whitespace) - - index := 0 - - // error handler - eh := func(_ token.Position, msg string) { - t.Errorf("%d: error handler called (msg = %s)", index, msg) - } - - // verify scan - var s Scanner - s.Init(fset.AddFile("", fset.Base(), len(source)), source, eh, ScanComments) - // epos is the expected position - epos := token.Position{ - Filename: "", - Offset: 0, - Line: 1, - Column: 1, - } - for { - pos, tok, lit := s.Scan() - if lit == "" { - // no literal value for non-literal tokens - lit = tok.String() - } - e := elt{token.EOF, "", special, "", ""} - if index < len(tokens) { - e = tokens[index] - } - if tok == token.EOF { - lit = "" - epos.Line = src_linecount - epos.Column = 2 - } - if e.pre != "" && strings.ContainsRune("=;#", rune(e.pre[0])) { - epos.Column = 1 - checkPos(t, lit, pos, epos) - var etok token.Token - if e.pre[0] == '=' { - etok = token.ASSIGN - } else { - etok = token.COMMENT - } - if tok != etok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, etok) - } - pos, tok, lit = s.Scan() - } - epos.Offset += len(e.pre) - if tok != token.EOF { - epos.Column = 1 + len(e.pre) - } - if e.pre != "" && e.pre[len(e.pre)-1] == '\n' { - epos.Offset-- - epos.Column-- - checkPos(t, lit, pos, epos) - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - epos.Line++ - epos.Offset++ - epos.Column = 1 - pos, tok, lit = s.Scan() - } - checkPos(t, lit, pos, epos) - if tok != e.tok { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, e.tok) - } - if e.tok.IsLiteral() { - // no CRs in value string literals - elit := e.lit - if strings.ContainsRune(e.pre, '=') { - elit = string(stripCR([]byte(elit))) - epos.Offset += len(e.lit) - len(lit) // correct position - } - if lit != elit { - t.Errorf("bad literal for %q: got %q, expected %q", lit, lit, elit) - } - } - if tokenclass(tok) != e.class { - t.Errorf("bad class for %q: got %d, expected %d", lit, tokenclass(tok), e.class) - } - epos.Offset += len(lit) + len(e.suf) + len(whitespace) - epos.Line += newlineCount(lit) + newlineCount(e.suf) + whitespace_linecount - index++ - if tok == token.EOF { - break - } - if e.suf == "value" { - pos, tok, lit = s.Scan() - if tok != token.STRING { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.STRING) - } - } else if strings.ContainsRune(e.suf, ';') || strings.ContainsRune(e.suf, '#') { - pos, tok, lit = s.Scan() - if tok != token.COMMENT { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.COMMENT) - } - } - // skip EOLs - for i := 0; i < whitespace_linecount+newlineCount(e.suf); i++ { - pos, tok, lit = s.Scan() - if tok != token.EOL { - t.Errorf("bad token for %q: got %q, expected %q", lit, tok, token.EOL) - } - } - } - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestScanValStringEOF(t *testing.T) { - var s Scanner - src := "= value" - f := fset.AddFile("src", fset.Base(), len(src)) - s.Init(f, []byte(src), nil, 0) - s.Scan() // = - s.Scan() // value - _, tok, _ := s.Scan() // EOF - if tok != token.EOF { - t.Errorf("bad token: got %s, expected %s", tok, token.EOF) - } - if s.ErrorCount > 0 { - t.Error("scanning error") - } -} - -// Verify that initializing the same scanner more then once works correctly. -func TestInit(t *testing.T) { - var s Scanner - - // 1st init - src1 := "\nname = value" - f1 := fset.AddFile("src1", fset.Base(), len(src1)) - s.Init(f1, []byte(src1), nil, 0) - if f1.Size() != len(src1) { - t.Errorf("bad file size: got %d, expected %d", f1.Size(), len(src1)) - } - s.Scan() // \n - s.Scan() // name - _, tok, _ := s.Scan() // = - if tok != token.ASSIGN { - t.Errorf("bad token: got %s, expected %s", tok, token.ASSIGN) - } - - // 2nd init - src2 := "[section]" - f2 := fset.AddFile("src2", fset.Base(), len(src2)) - s.Init(f2, []byte(src2), nil, 0) - if f2.Size() != len(src2) { - t.Errorf("bad file size: got %d, expected %d", f2.Size(), len(src2)) - } - _, tok, _ = s.Scan() // [ - if tok != token.LBRACK { - t.Errorf("bad token: got %s, expected %s", tok, token.LBRACK) - } - - if s.ErrorCount != 0 { - t.Errorf("found %d errors", s.ErrorCount) - } -} - -func TestStdErrorHandler(t *testing.T) { - const src = "@\n" + // illegal character, cause an error - "@ @\n" // two errors on the same line - - var list ErrorList - eh := func(pos token.Position, msg string) { list.Add(pos, msg) } - - var s Scanner - s.Init(fset.AddFile("File1", fset.Base(), len(src)), []byte(src), eh, 0) - for { - if _, tok, _ := s.Scan(); tok == token.EOF { - break - } - } - - if len(list) != s.ErrorCount { - t.Errorf("found %d errors, expected %d", len(list), s.ErrorCount) - } - - if len(list) != 3 { - t.Errorf("found %d raw errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.Sort() - if len(list) != 3 { - t.Errorf("found %d sorted errors, expected 3", len(list)) - PrintError(os.Stderr, list) - } - - list.RemoveMultiples() - if len(list) != 2 { - t.Errorf("found %d one-per-line errors, expected 2", len(list)) - PrintError(os.Stderr, list) - } -} - -type errorCollector struct { - cnt int // number of errors encountered - msg string // last error message encountered - pos token.Position // last error position encountered -} - -func checkError(t *testing.T, src string, tok token.Token, pos int, err string) { - var s Scanner - var h errorCollector - eh := func(pos token.Position, msg string) { - h.cnt++ - h.msg = msg - h.pos = pos - } - s.Init(fset.AddFile("", fset.Base(), len(src)), []byte(src), eh, ScanComments) - if src[0] == '=' { - _, _, _ = s.Scan() - } - _, tok0, _ := s.Scan() - _, tok1, _ := s.Scan() - if tok0 != tok { - t.Errorf("%q: got %s, expected %s", src, tok0, tok) - } - if tok1 != token.EOF { - t.Errorf("%q: got %s, expected EOF", src, tok1) - } - cnt := 0 - if err != "" { - cnt = 1 - } - if h.cnt != cnt { - t.Errorf("%q: got cnt %d, expected %d", src, h.cnt, cnt) - } - if h.msg != err { - t.Errorf("%q: got msg %q, expected %q", src, h.msg, err) - } - if h.pos.Offset != pos { - t.Errorf("%q: got offset %d, expected %d", src, h.pos.Offset, pos) - } -} - -var errors = []struct { - src string - tok token.Token - pos int - err string -}{ - {"\a", token.ILLEGAL, 0, "illegal character U+0007"}, - {"/", token.ILLEGAL, 0, "illegal character U+002F '/'"}, - {"_", token.ILLEGAL, 0, "illegal character U+005F '_'"}, - {`…`, token.ILLEGAL, 0, "illegal character U+2026 '…'"}, - {`""`, token.STRING, 0, ""}, - {`"`, token.STRING, 0, "string not terminated"}, - {"\"\n", token.STRING, 0, "string not terminated"}, - {`="`, token.STRING, 1, "string not terminated"}, - {"=\"\n", token.STRING, 1, "string not terminated"}, - {"=\\", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {"=\\\r", token.STRING, 1, "unquoted '\\' must be followed by new line"}, - {`"\z"`, token.STRING, 2, "unknown escape sequence"}, - {`"\a"`, token.STRING, 2, "unknown escape sequence"}, - {`"\b"`, token.STRING, 2, "unknown escape sequence"}, - {`"\f"`, token.STRING, 2, "unknown escape sequence"}, - {`"\r"`, token.STRING, 2, "unknown escape sequence"}, - {`"\t"`, token.STRING, 2, "unknown escape sequence"}, - {`"\v"`, token.STRING, 2, "unknown escape sequence"}, - {`"\0"`, token.STRING, 2, "unknown escape sequence"}, -} - -func TestScanErrors(t *testing.T) { - for _, e := range errors { - checkError(t, e.src, e.tok, e.pos, e.err) - } -} - -func BenchmarkScan(b *testing.B) { - b.StopTimer() - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(source)) - var s Scanner - b.StartTimer() - for i := b.N - 1; i >= 0; i-- { - s.Init(file, source, nil, ScanComments) - for { - _, tok, _ := s.Scan() - if tok == token.EOF { - break - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg b/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg deleted file mode 100644 index cddff29ab8f..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[section] -name=value # comment diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg b/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg deleted file mode 100644 index 3762a201e76..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/testdata/gcfg_unicode_test.gcfg +++ /dev/null @@ -1,3 +0,0 @@ -; Comment line -[甲] -乙=丙 # comment diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go deleted file mode 100644 index 160107df407..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/position_test.go +++ /dev/null @@ -1,181 +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 token - -import ( - "fmt" - "testing" -) - -func checkPos(t *testing.T, msg string, p, q Position) { - if p.Filename != q.Filename { - t.Errorf("%s: expected filename = %q; got %q", msg, q.Filename, p.Filename) - } - if p.Offset != q.Offset { - t.Errorf("%s: expected offset = %d; got %d", msg, q.Offset, p.Offset) - } - if p.Line != q.Line { - t.Errorf("%s: expected line = %d; got %d", msg, q.Line, p.Line) - } - if p.Column != q.Column { - t.Errorf("%s: expected column = %d; got %d", msg, q.Column, p.Column) - } -} - -func TestNoPos(t *testing.T) { - if NoPos.IsValid() { - t.Errorf("NoPos should not be valid") - } - var fset *FileSet - checkPos(t, "nil NoPos", fset.Position(NoPos), Position{}) - fset = NewFileSet() - checkPos(t, "fset NoPos", fset.Position(NoPos), Position{}) -} - -var tests = []struct { - filename string - source []byte // may be nil - size int - lines []int -}{ - {"a", []byte{}, 0, []int{}}, - {"b", []byte("01234"), 5, []int{0}}, - {"c", []byte("\n\n\n\n\n\n\n\n\n"), 9, []int{0, 1, 2, 3, 4, 5, 6, 7, 8}}, - {"d", nil, 100, []int{0, 5, 10, 20, 30, 70, 71, 72, 80, 85, 90, 99}}, - {"e", nil, 777, []int{0, 80, 100, 120, 130, 180, 267, 455, 500, 567, 620}}, - {"f", []byte("package p\n\nimport \"fmt\""), 23, []int{0, 10, 11}}, - {"g", []byte("package p\n\nimport \"fmt\"\n"), 24, []int{0, 10, 11}}, - {"h", []byte("package p\n\nimport \"fmt\"\n "), 25, []int{0, 10, 11, 24}}, -} - -func linecol(lines []int, offs int) (int, int) { - prevLineOffs := 0 - for line, lineOffs := range lines { - if offs < lineOffs { - return line, offs - prevLineOffs + 1 - } - prevLineOffs = lineOffs - } - return len(lines), offs - prevLineOffs + 1 -} - -func verifyPositions(t *testing.T, fset *FileSet, f *File, lines []int) { - for offs := 0; offs < f.Size(); offs++ { - p := f.Pos(offs) - offs2 := f.Offset(p) - if offs2 != offs { - t.Errorf("%s, Offset: expected offset %d; got %d", f.Name(), offs, offs2) - } - line, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{f.Name(), offs, line, col}) - checkPos(t, msg, fset.Position(p), Position{f.Name(), offs, line, col}) - } -} - -func makeTestSource(size int, lines []int) []byte { - src := make([]byte, size) - for _, offs := range lines { - if offs > 0 { - src[offs-1] = '\n' - } - } - return src -} - -func TestPositions(t *testing.T) { - const delta = 7 // a non-zero base offset increment - fset := NewFileSet() - for _, test := range tests { - // verify consistency of test case - if test.source != nil && len(test.source) != test.size { - t.Errorf("%s: inconsistent test case: expected file size %d; got %d", test.filename, test.size, len(test.source)) - } - - // add file and verify name and size - f := fset.AddFile(test.filename, fset.Base()+delta, test.size) - if f.Name() != test.filename { - t.Errorf("expected filename %q; got %q", test.filename, f.Name()) - } - if f.Size() != test.size { - t.Errorf("%s: expected file size %d; got %d", f.Name(), test.size, f.Size()) - } - if fset.File(f.Pos(0)) != f { - t.Errorf("%s: f.Pos(0) was not found in f", f.Name()) - } - - // add lines individually and verify all positions - for i, offset := range test.lines { - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - // adding the same offset again should be ignored - f.AddLine(offset) - if f.LineCount() != i+1 { - t.Errorf("%s, AddLine: expected unchanged line count %d; got %d", f.Name(), i+1, f.LineCount()) - } - verifyPositions(t, fset, f, test.lines[0:i+1]) - } - - // add lines with SetLines and verify all positions - if ok := f.SetLines(test.lines); !ok { - t.Errorf("%s: SetLines failed", f.Name()) - } - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLines: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - - // add lines with SetLinesForContent and verify all positions - src := test.source - if src == nil { - // no test source available - create one from scratch - src = makeTestSource(test.size, test.lines) - } - f.SetLinesForContent(src) - if f.LineCount() != len(test.lines) { - t.Errorf("%s, SetLinesForContent: expected line count %d; got %d", f.Name(), len(test.lines), f.LineCount()) - } - verifyPositions(t, fset, f, test.lines) - } -} - -func TestLineInfo(t *testing.T) { - fset := NewFileSet() - f := fset.AddFile("foo", fset.Base(), 500) - lines := []int{0, 42, 77, 100, 210, 220, 277, 300, 333, 401} - // add lines individually and provide alternative line information - for _, offs := range lines { - f.AddLine(offs) - f.AddLineInfo(offs, "bar", 42) - } - // verify positions for all offsets - for offs := 0; offs <= f.Size(); offs++ { - p := f.Pos(offs) - _, col := linecol(lines, offs) - msg := fmt.Sprintf("%s (offs = %d, p = %d)", f.Name(), offs, p) - checkPos(t, msg, f.Position(f.Pos(offs)), Position{"bar", offs, 42, col}) - checkPos(t, msg, fset.Position(p), Position{"bar", offs, 42, col}) - } -} - -func TestFiles(t *testing.T) { - fset := NewFileSet() - for i, test := range tests { - fset.AddFile(test.filename, fset.Base(), test.size) - j := 0 - fset.Iterate(func(f *File) bool { - if f.Name() != tests[j].filename { - t.Errorf("expected filename = %s; got %s", tests[j].filename, f.Name()) - } - j++ - return true - }) - if j != i+1 { - t.Errorf("expected %d files; got %d", i+1, j) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go deleted file mode 100644 index 4e925adb6f2..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/token/serialize_test.go +++ /dev/null @@ -1,111 +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 token - -import ( - "bytes" - "encoding/gob" - "fmt" - "testing" -) - -// equal returns nil if p and q describe the same file set; -// otherwise it returns an error describing the discrepancy. -func equal(p, q *FileSet) error { - if p == q { - // avoid deadlock if p == q - return nil - } - - // not strictly needed for the test - p.mutex.Lock() - q.mutex.Lock() - defer q.mutex.Unlock() - defer p.mutex.Unlock() - - if p.base != q.base { - return fmt.Errorf("different bases: %d != %d", p.base, q.base) - } - - if len(p.files) != len(q.files) { - return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) - } - - for i, f := range p.files { - g := q.files[i] - if f.set != p { - return fmt.Errorf("wrong fileset for %q", f.name) - } - if g.set != q { - return fmt.Errorf("wrong fileset for %q", g.name) - } - if f.name != g.name { - return fmt.Errorf("different filenames: %q != %q", f.name, g.name) - } - if f.base != g.base { - return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) - } - if f.size != g.size { - return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) - } - for j, l := range f.lines { - m := g.lines[j] - if l != m { - return fmt.Errorf("different offsets for %q", f.name) - } - } - for j, l := range f.infos { - m := g.infos[j] - if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { - return fmt.Errorf("different infos for %q", f.name) - } - } - } - - // we don't care about .last - it's just a cache - return nil -} - -func checkSerialize(t *testing.T, p *FileSet) { - var buf bytes.Buffer - encode := func(x interface{}) error { - return gob.NewEncoder(&buf).Encode(x) - } - if err := p.Write(encode); err != nil { - t.Errorf("writing fileset failed: %s", err) - return - } - q := NewFileSet() - decode := func(x interface{}) error { - return gob.NewDecoder(&buf).Decode(x) - } - if err := q.Read(decode); err != nil { - t.Errorf("reading fileset failed: %s", err) - return - } - if err := equal(p, q); err != nil { - t.Errorf("filesets not identical: %s", err) - } -} - -func TestSerialization(t *testing.T) { - p := NewFileSet() - checkSerialize(t, p) - // add some files - for i := 0; i < 10; i++ { - f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) - checkSerialize(t, p) - // add some lines and alternative file infos - line := 1000 - for offs := 0; offs < f.Size(); offs += 40 + i { - f.AddLine(offs) - if offs%7 == 0 { - f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) - line += 33 - } - } - checkSerialize(t, p) - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go deleted file mode 100644 index 4bf135e678e..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/enum_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -import ( - "testing" -) - -func TestEnumParserBool(t *testing.T) { - for _, tt := range []struct { - val string - res bool - ok bool - }{ - {val: "tRuE", res: true, ok: true}, - {val: "False", res: false, ok: true}, - {val: "t", ok: false}, - } { - b, err := ParseBool(tt.val) - switch { - case tt.ok && err != nil: - t.Errorf("%q: got error %v, want %v", tt.val, err, tt.res) - case !tt.ok && err == nil: - t.Errorf("%q: got %v, want error", tt.val, b) - case tt.ok && b != tt.res: - t.Errorf("%q: got %v, want %v", tt.val, b, tt.res) - default: - t.Logf("%q: got %v, %v", tt.val, b, err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go deleted file mode 100644 index b63dbcbaefe..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/int_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func elem(p interface{}) interface{} { - return reflect.ValueOf(p).Elem().Interface() -} - -func TestParseInt(t *testing.T) { - for _, tt := range []struct { - val string - mode IntMode - exp interface{} - ok bool - }{ - {"0", Dec, int(0), true}, - {"10", Dec, int(10), true}, - {"-10", Dec, int(-10), true}, - {"x", Dec, int(0), false}, - {"0xa", Hex, int(0xa), true}, - {"a", Hex, int(0xa), true}, - {"10", Hex, int(0x10), true}, - {"-0xa", Hex, int(-0xa), true}, - {"0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-0x", Hex, int(0x0), true}, // Scanf doesn't require digit behind 0x - {"-a", Hex, int(-0xa), true}, - {"-10", Hex, int(-0x10), true}, - {"x", Hex, int(0), false}, - {"10", Oct, int(010), true}, - {"010", Oct, int(010), true}, - {"-10", Oct, int(-010), true}, - {"-010", Oct, int(-010), true}, - {"10", Dec | Hex, int(10), true}, - {"010", Dec | Hex, int(10), true}, - {"0x10", Dec | Hex, int(0x10), true}, - {"10", Dec | Oct, int(10), true}, - {"010", Dec | Oct, int(010), true}, - {"0x10", Dec | Oct, int(0), false}, - {"10", Hex | Oct, int(0), false}, // need prefix to distinguish Hex/Oct - {"010", Hex | Oct, int(010), true}, - {"0x10", Hex | Oct, int(0x10), true}, - {"10", Dec | Hex | Oct, int(10), true}, - {"010", Dec | Hex | Oct, int(010), true}, - {"0x10", Dec | Hex | Oct, int(0x10), true}, - } { - typ := reflect.TypeOf(tt.exp) - res := reflect.New(typ).Interface() - err := ParseInt(res, tt.val, tt.mode) - switch { - case tt.ok && err != nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got error %v, want ok", - typ, tt.val, tt.mode, err) - case !tt.ok && err == nil: - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want error", - typ, tt.val, tt.mode, elem(res)) - case tt.ok && !reflect.DeepEqual(elem(res), tt.exp): - t.Errorf("ParseInt(%v, %#v, %v): fail; got %v, want %v", - typ, tt.val, tt.mode, elem(res), tt.exp) - default: - t.Logf("ParseInt(%v, %#v, %s): pass; got %v, error %v", - typ, tt.val, tt.mode, elem(res), err) - } - } -} diff --git a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go b/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go deleted file mode 100644 index a8083e04fa7..00000000000 --- a/Godeps/_workspace/src/github.com/scalingdata/gcfg/types/scan_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package types - -import ( - "reflect" - "testing" -) - -func TestScanFully(t *testing.T) { - for _, tt := range []struct { - val string - verb byte - res interface{} - ok bool - }{ - {"a", 'v', int(0), false}, - {"0x", 'v', int(0), true}, - {"0x", 'd', int(0), false}, - } { - d := reflect.New(reflect.TypeOf(tt.res)).Interface() - err := ScanFully(d, tt.val, tt.verb) - switch { - case tt.ok && err != nil: - t.Errorf("ScanFully(%T, %q, '%c'): want ok, got error %v", - d, tt.val, tt.verb, err) - case !tt.ok && err == nil: - t.Errorf("ScanFully(%T, %q, '%c'): want error, got %v", - d, tt.val, tt.verb, elem(d)) - case tt.ok && err == nil && !reflect.DeepEqual(tt.res, elem(d)): - t.Errorf("ScanFully(%T, %q, '%c'): want %v, got %v", - d, tt.val, tt.verb, tt.res, elem(d)) - default: - t.Logf("ScanFully(%T, %q, '%c') = %v; *ptr==%v", - d, tt.val, tt.verb, err, elem(d)) - } - } -} diff --git a/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go b/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go deleted file mode 100644 index ad03201cacb..00000000000 --- a/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package sanitized_anchor_name_test - -import ( - "fmt" - - "github.com/shurcooL/sanitized_anchor_name" -) - -func ExampleCreate() { - anchorName := sanitized_anchor_name.Create("This is a header") - - fmt.Println(anchorName) - - // Output: - // this-is-a-header -} - -func ExampleCreate2() { - fmt.Println(sanitized_anchor_name.Create("This is a header")) - fmt.Println(sanitized_anchor_name.Create("This is also a header")) - fmt.Println(sanitized_anchor_name.Create("main.go")) - fmt.Println(sanitized_anchor_name.Create("Article 123")) - fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?")) - fmt.Printf("%q\n", sanitized_anchor_name.Create(" ")) - fmt.Println(sanitized_anchor_name.Create("Hello, 世界")) - - // Output: - // this-is-a-header - // this-is-also-a-header - // main-go - // article-123 - // let-s-try-this-shall-we - // "" - // hello-世界 -} diff --git a/Godeps/_workspace/src/github.com/skynetservices/skydns/msg/service_test.go b/Godeps/_workspace/src/github.com/skynetservices/skydns/msg/service_test.go deleted file mode 100644 index 2c8b418202f..00000000000 --- a/Godeps/_workspace/src/github.com/skynetservices/skydns/msg/service_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) 2015 The SkyDNS Authors. All rights reserved. -// Use of this source code is governed by The MIT License (MIT) that can be -// found in the LICENSE file. - -package msg - -import "testing" - -func TestSplit255(t *testing.T) { - xs := split255("abc") - if len(xs) != 1 && xs[0] != "abc" { - t.Logf("Failure to split abc") - t.Fail() - } - s := "" - for i := 0; i < 255; i++ { - s += "a" - } - xs = split255(s) - if len(xs) != 1 && xs[0] != s { - t.Logf("failure to split 255 char long string") - t.Logf("%s %v\n", s, xs) - t.Fail() - } - s += "b" - xs = split255(s) - if len(xs) != 2 || xs[1] != "b" { - t.Logf("failure to split 256 char long string: %d", len(xs)) - t.Logf("%s %v\n", s, xs) - t.Fail() - } - for i := 0; i < 255; i++ { - s += "a" - } - xs = split255(s) - if len(xs) != 3 || xs[2] != "a" { - t.Logf("failure to split 510 char long string: %d", len(xs)) - t.Logf("%s %v\n", s, xs) - t.Fail() - } -} - -func TestGroup(t *testing.T) { - // Key are in the wrong order, but for this test it does not matter. - - sx := Group( - []Service{ - {Host: "127.0.0.1", Group: "g1", Key: "b/sub/dom1/skydns/test"}, - {Host: "127.0.0.2", Group: "g2", Key: "a/dom1/skydns/test"}, - }, - ) - // Expecting to return the shortest key with a Group attribute. - if len(sx) != 1 { - t.Fatalf("failure to group zeroth set: %v", sx) - } - if sx[0].Key != "a/dom1/skydns/test" { - t.Fatalf("failure to group zeroth set: %v, wrong Key", sx) - } - - // Groups disagree, so we will not do anything. - sx = Group( - []Service{ - {Host: "server1", Group: "g1", Key: "region1/skydns/test"}, - {Host: "server2", Group: "g2", Key: "region1/skydns/test"}, - }, - ) - if len(sx) != 2 { - t.Fatalf("failure to group first set: %v", sx) - } - - // Group is g1, include only the top-level one. - sx = Group( - []Service{ - {Host: "server1", Group: "g1", Key: "a/dom/region1/skydns/test"}, - {Host: "server2", Group: "g2", Key: "a/subdom/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 1 { - t.Fatalf("failure to group second set: %v", sx) - } - - // Groupless services must be included. - sx = Group( - []Service{ - {Host: "server1", Group: "g1", Key: "a/dom/region1/skydns/test"}, - {Host: "server2", Group: "g2", Key: "a/subdom/dom/region1/skydns/test"}, - {Host: "server2", Group: "", Key: "b/subdom/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 2 { - t.Fatalf("failure to group third set: %v", sx) - } - - // Empty group on the highest level: include that one also. - sx = Group( - []Service{ - {Host: "server1", Group: "g1", Key: "a/dom/region1/skydns/test"}, - {Host: "server1", Group: "", Key: "b/dom/region1/skydns/test"}, - {Host: "server2", Group: "g2", Key: "a/subdom/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 2 { - t.Fatalf("failure to group fourth set: %v", sx) - } - - // Empty group on the highest level: include that one also, and the rest. - sx = Group( - []Service{ - {Host: "server1", Group: "g5", Key: "a/dom/region1/skydns/test"}, - {Host: "server1", Group: "", Key: "b/dom/region1/skydns/test"}, - {Host: "server2", Group: "g5", Key: "a/subdom/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 3 { - t.Fatalf("failure to group fith set: %v", sx) - } - - // One group. - sx = Group( - []Service{ - {Host: "server1", Group: "g6", Key: "a/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 1 { - t.Fatalf("failure to group sixth set: %v", sx) - } - - // No group, once service - sx = Group( - []Service{ - {Host: "server1", Key: "a/dom/region1/skydns/test"}, - }, - ) - if len(sx) != 1 { - t.Fatalf("failure to group seventh set: %v", sx) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go deleted file mode 100644 index a1f2b13cb3c..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func checkOmit(t *testing.T, found, unexpected string) { - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected) - } -} - -func check(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } -} - -// World worst custom function, just keep telling you to enter hello! -const ( - bash_completion_func = `__custom_func() { -COMPREPLY=( "hello" ) -} -` -) - -func TestBashCompletions(t *testing.T) { - c := initializeWithRootCmd() - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated) - - // custom completion function - c.BashCompletionFunction = bash_completion_func - - // required flag - c.MarkFlagRequired("introot") - - // valid nouns - validArgs := []string{"pods", "nodes", "services", "replicationControllers"} - c.ValidArgs = validArgs - - // filename - var flagval string - c.Flags().StringVar(&flagval, "filename", "", "Enter a filename") - c.MarkFlagFilename("filename", "json", "yaml", "yml") - - // filename extensions - var flagvalExt string - c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)") - c.MarkFlagFilename("filename-ext") - - // subdirectories in a given directory - var flagvalTheme string - c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)") - c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) - - out := new(bytes.Buffer) - c.GenBashCompletion(out) - str := out.String() - - check(t, str, "_cobra-test") - check(t, str, "_cobra-test_echo") - check(t, str, "_cobra-test_echo_times") - check(t, str, "_cobra-test_print") - - // check for required flags - check(t, str, `must_have_one_flag+=("--introot=")`) - // check for custom completion function - check(t, str, `COMPREPLY=( "hello" )`) - // check for required nouns - check(t, str, `must_have_one_noun+=("pods")`) - // check for filename extension flags - check(t, str, `flags_completion+=("_filedir")`) - // check for filename extension flags - check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`) - // check for subdirs_in_dir flags - check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`) - - checkOmit(t, str, cmdDeprecated.Name()) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go deleted file mode 100644 index f4814ead812..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go +++ /dev/null @@ -1,1058 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "reflect" - "runtime" - "strings" - "testing" - "text/template" - - "github.com/spf13/pflag" -) - -var _ = fmt.Println -var _ = os.Stderr - -var tp, te, tt, t1, tr []string -var rootPersPre, echoPre, echoPersPre, timesPersPre []string -var flagb1, flagb2, flagb3, flagbr, flagbp bool -var flags1, flags2a, flags2b, flags3, outs string -var flagi1, flagi2, flagi3, flagir int -var globalFlag1 bool -var flagEcho, rootcalled bool -var versionUsed int - -const strtwoParentHelp = "help message for parent flag strtwo" -const strtwoChildHelp = "help message for child flag strtwo" - -var cmdHidden = &Command{ - Use: "hide [secret string to print]", - Short: "Print anything to screen (if command is known)", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - outs = "hidden" - }, - Hidden: true, -} - -var cmdPrint = &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an absolutely utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, -} - -var cmdEcho = &Command{ - Use: "echo [string to echo]", - Aliases: []string{"say"}, - Short: "Echo anything to the screen", - Long: `an utterly useless command for testing.`, - Example: "Just run cobra-test echo", - PersistentPreRun: func(cmd *Command, args []string) { - echoPersPre = args - }, - PreRun: func(cmd *Command, args []string) { - echoPre = args - }, - Run: func(cmd *Command, args []string) { - te = args - }, -} - -var cmdEchoSub = &Command{ - Use: "echosub [string to print]", - Short: "second sub command for echo", - Long: `an absolutely utterly useless command for testing gendocs!.`, - Run: func(cmd *Command, args []string) { - }, -} - -var cmdDeprecated = &Command{ - Use: "deprecated [can't do anything here]", - Short: "A command which is deprecated", - Long: `an absolutely utterly useless command for testing deprecation!.`, - Deprecated: "Please use echo instead", - Run: func(cmd *Command, args []string) { - }, -} - -var cmdTimes = &Command{ - Use: "times [# times] [string to echo]", - SuggestFor: []string{"counts"}, - Short: "Echo anything to the screen more times", - Long: `a slightly useless command for testing.`, - PersistentPreRun: func(cmd *Command, args []string) { - timesPersPre = args - }, - Run: func(cmd *Command, args []string) { - tt = args - }, -} - -var cmdRootNoRun = &Command{ - Use: "cobra-test", - Short: "The root can run it's own function", - Long: "The root description for help", - PersistentPreRun: func(cmd *Command, args []string) { - rootPersPre = args - }, -} - -var cmdRootSameName = &Command{ - Use: "print", - Short: "Root with the same name as a subcommand", - Long: "The root description for help", -} - -var cmdRootWithRun = &Command{ - Use: "cobra-test", - Short: "The root can run it's own function", - Long: "The root description for help", - Run: func(cmd *Command, args []string) { - tr = args - rootcalled = true - }, -} - -var cmdSubNoRun = &Command{ - Use: "subnorun", - Short: "A subcommand without a Run function", - Long: "A long output about a subcommand without a Run function", -} - -var cmdVersion1 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `First version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 1 - }, -} - -var cmdVersion2 = &Command{ - Use: "version", - Short: "Print the version number", - Long: `Second version of the version command`, - Run: func(cmd *Command, args []string) { - versionUsed = 2 - }, -} - -func flagInit() { - cmdEcho.ResetFlags() - cmdPrint.ResetFlags() - cmdTimes.ResetFlags() - cmdRootNoRun.ResetFlags() - cmdRootSameName.ResetFlags() - cmdRootWithRun.ResetFlags() - cmdSubNoRun.ResetFlags() - cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp) - cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone") - cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo") - cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree") - cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone") - cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool") - cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp) - cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree") - cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone") - cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo") - cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree") - cmdVersion1.ResetFlags() - cmdVersion2.ResetFlags() -} - -func commandInit() { - cmdEcho.ResetCommands() - cmdPrint.ResetCommands() - cmdTimes.ResetCommands() - cmdRootNoRun.ResetCommands() - cmdRootSameName.ResetCommands() - cmdRootWithRun.ResetCommands() - cmdSubNoRun.ResetCommands() -} - -func initialize() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - - var c = cmdRootNoRun - flagInit() - commandInit() - return c -} - -func initializeWithSameName() *Command { - tt, tp, te = nil, nil, nil - rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil - var c = cmdRootSameName - flagInit() - commandInit() - return c -} - -func initializeWithRootCmd() *Command { - cmdRootWithRun.ResetCommands() - tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false - flagInit() - cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot") - cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot") - commandInit() - return cmdRootWithRun -} - -type resulter struct { - Error error - Output string - Command *Command -} - -func fullSetupTest(input string) resulter { - c := initializeWithRootCmd() - - return fullTester(c, input) -} - -func noRRSetupTest(input string) resulter { - c := initialize() - - return fullTester(c, input) -} - -func rootOnlySetupTest(input string) resulter { - c := initializeWithRootCmd() - - return simpleTester(c, input) -} - -func simpleTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func fullTester(c *Command, input string) resulter { - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated) - c.SetArgs(strings.Split(input, " ")) - - err := c.Execute() - output := buf.String() - - return resulter{err, output, c} -} - -func logErr(t *testing.T, found, expected string) { - out := new(bytes.Buffer) - - _, _, line, ok := runtime.Caller(2) - if ok { - fmt.Fprintf(out, "Line: %d ", line) - } - fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - t.Errorf(out.String()) -} - -func checkStringContains(t *testing.T, found, expected string) { - if !strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultContains(t *testing.T, x resulter, check string) { - checkStringContains(t, x.Output, check) -} - -func checkStringOmits(t *testing.T, found, expected string) { - if strings.Contains(found, expected) { - logErr(t, found, expected) - } -} - -func checkResultOmits(t *testing.T, x resulter, check string) { - checkStringOmits(t, x.Output, check) -} - -func checkOutputContains(t *testing.T, c *Command, check string) { - buf := new(bytes.Buffer) - c.SetOutput(buf) - c.Execute() - - if !strings.Contains(buf.String(), check) { - logErr(t, buf.String(), check) - } -} - -func TestSingleCommand(t *testing.T) { - noRRSetupTest("print one two") - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestChildCommand(t *testing.T) { - noRRSetupTest("echo times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestCommandAlias(t *testing.T) { - noRRSetupTest("say times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("ech times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - - EnablePrefixMatching = false -} - -func TestNoPrefixMatching(t *testing.T) { - EnablePrefixMatching = false - - noRRSetupTest("ech times one two") - - if !(tt == nil && te == nil && tp == nil) { - t.Error("Wrong command called") - } -} - -func TestAliasPrefixMatching(t *testing.T) { - EnablePrefixMatching = true - noRRSetupTest("sa times one two") - - if te != nil || tp != nil { - t.Error("Wrong command called") - } - if tt == nil { - t.Error("Wrong command called") - } - if strings.Join(tt, " ") != "one two" { - t.Error("Command didn't parse correctly") - } - EnablePrefixMatching = false -} - -func TestChildSameName(t *testing.T) { - c := initializeWithSameName() - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(strings.Split("print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestGrandChildSameName(t *testing.T) { - c := initializeWithSameName() - cmdTimes.AddCommand(cmdPrint) - c.AddCommand(cmdTimes) - c.SetArgs(strings.Split("times print one two", " ")) - c.Execute() - - if te != nil || tt != nil { - t.Error("Wrong command called") - } - if tp == nil { - t.Error("Wrong command called") - } - if strings.Join(tp, " ") != "one two" { - t.Error("Command didn't parse correctly") - } -} - -func TestFlagLong(t *testing.T) { - noRRSetupTest("echo --intone=13 something -- here") - - if cmdEcho.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } -} - -func TestFlagShort(t *testing.T) { - noRRSetupTest("echo -i13 -- something here") - - if cmdEcho.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash()) - } - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("echo -i 13 something here") - - if strings.Join(te, " ") != "something here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flagi1 != 13 { - t.Errorf("int flag didn't get correct value, had %d", flagi1) - } - if flagi2 != 234 { - t.Errorf("default flag value changed, 234 expected, %d given", flagi2) - } - - noRRSetupTest("print -i99 one two") - - if strings.Join(tp, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tp) - } - if flagi3 != 99 { - t.Errorf("int flag didn't get correct value, had %d", flagi3) - } - if flagi1 != 123 { - t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2) - } -} - -func TestChildCommandFlags(t *testing.T) { - noRRSetupTest("echo times -j 99 one two") - - if strings.Join(tt, " ") != "one two" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - // Testing with flag that shouldn't be persistent - r := noRRSetupTest("echo times -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Output, "unknown shorthand") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } - - if flagi2 != 99 { - t.Errorf("flag value should be 99, %d given", flagi2) - } - - if flagi1 != 123 { - t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1) - } - - // Testing with flag only existing on child - r = noRRSetupTest("echo -j 99 -i77 one two") - - if r.Error == nil { - t.Errorf("invalid flag should generate error") - } - - if !strings.Contains(r.Output, "unknown shorthand flag") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } - - // Testing with persistent flag overwritten by child - noRRSetupTest("echo times --strtwo=child one two") - - if flags2b != "child" { - t.Errorf("flag value should be child, %s given", flags2b) - } - - if flags2a != "two" { - t.Errorf("unset flag should have default value, expecting two, given %s", flags2a) - } - - // Testing flag with invalid input - r = noRRSetupTest("echo -i10E") - - if r.Error == nil { - t.Errorf("invalid input should generate error") - } - - if !strings.Contains(r.Output, "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", r.Output) - } -} - -func TestTrailingCommandFlags(t *testing.T) { - x := fullSetupTest("echo two -x") - - if x.Error == nil { - t.Errorf("invalid flag should generate error") - } -} - -func TestInvalidSubcommandFlags(t *testing.T) { - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - result := simpleTester(cmd, "times --inttwo=2 --badflag=bar") - - checkResultContains(t, result, "unknown flag: --badflag") - - if strings.Contains(result.Output, "unknown flag: --inttwo") { - t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag") - } - -} - -func TestSubcommandArgEvaluation(t *testing.T) { - cmd := initializeWithRootCmd() - - first := &Command{ - Use: "first", - Run: func(cmd *Command, args []string) { - }, - } - cmd.AddCommand(first) - - second := &Command{ - Use: "second", - Run: func(cmd *Command, args []string) { - fmt.Fprintf(cmd.Out(), "%v", args) - }, - } - first.AddCommand(second) - - result := simpleTester(cmd, "first second first third") - - expectedOutput := fmt.Sprintf("%v", []string{"first third"}) - if result.Output != expectedOutput { - t.Errorf("exptected %v, got %v", expectedOutput, result.Output) - } -} - -func TestPersistentFlags(t *testing.T) { - fullSetupTest("echo -s something -p more here") - - // persistentFlag should act like normal flag on it's own command - if strings.Join(te, " ") != "more here" { - t.Errorf("flags didn't leave proper args remaining..%s given", te) - } - if flags1 != "something" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } - - // persistentFlag should act like normal flag on it's own command - fullSetupTest("echo times -s again -c -p test here") - - if strings.Join(tt, " ") != "test here" { - t.Errorf("flags didn't leave proper args remaining..%s given", tt) - } - - if flags1 != "again" { - t.Errorf("string flag didn't get correct value, had %v", flags1) - } - - if !flagb2 { - t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2) - } - if !flagbp { - t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp) - } -} - -func TestHelpCommand(t *testing.T) { - x := fullSetupTest("help") - checkResultContains(t, x, cmdRootWithRun.Long) - - x = fullSetupTest("help echo") - checkResultContains(t, x, cmdEcho.Long) - - x = fullSetupTest("help echo times") - checkResultContains(t, x, cmdTimes.Long) -} - -func TestChildCommandHelp(t *testing.T) { - c := noRRSetupTest("print --help") - checkResultContains(t, c, strtwoParentHelp) - r := noRRSetupTest("echo times --help") - checkResultContains(t, r, strtwoChildHelp) -} - -func TestNonRunChildHelp(t *testing.T) { - x := noRRSetupTest("subnorun") - checkResultContains(t, x, cmdSubNoRun.Long) -} - -func TestRunnableRootCommand(t *testing.T) { - x := fullSetupTest("") - - if rootcalled != true { - t.Errorf("Root Function was not called\n out:%v", x.Error) - } -} - -func TestRunnableRootCommandNilInput(t *testing.T) { - empty_arg := make([]string, 0) - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(empty_arg) - - err := c.Execute() - if err != nil { - t.Errorf("Execute() failed with %v", err) - } - - if rootcalled != true { - t.Errorf("Root Function was not called") - } -} - -func TestRunnableRootCommandEmptyInput(t *testing.T) { - args := make([]string, 3) - args[0] = "" - args[1] = "--introot=12" - args[2] = "" - c := initializeWithRootCmd() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if rootcalled != true { - t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf) - } -} - -func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) { - fullSetupTest("echo invalid-sub") - - if te[0] != "invalid-sub" { - t.Errorf("Subcommand didn't work...") - } -} - -func TestRootFlags(t *testing.T) { - fullSetupTest("-i 17 -b") - - if flagbr != true { - t.Errorf("flag value should be true, %v given", flagbr) - } - - if flagir != 17 { - t.Errorf("flag value should be 17, %d given", flagir) - } -} - -func TestRootHelp(t *testing.T) { - x := fullSetupTest("--help") - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - if strings.Contains(x.Output, cmdEcho.Use) { - t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output) - } - - x = fullSetupTest("echo --help") - - if strings.Contains(x.Output, cmdTimes.Use) { - t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output) - } - - checkResultContains(t, x, "Available Commands:") - checkResultContains(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - -} - -func TestFlagAccess(t *testing.T) { - initialize() - - local := cmdTimes.LocalFlags() - inherited := cmdTimes.InheritedFlags() - - for _, f := range []string{"inttwo", "strtwo", "booltwo"} { - if local.Lookup(f) == nil { - t.Errorf("LocalFlags expected to contain %s, Got: nil", f) - } - } - if inherited.Lookup("strone") == nil { - t.Errorf("InheritedFlags expected to contain strone, Got: nil") - } - if inherited.Lookup("strtwo") != nil { - t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo") - - } -} - -func TestNoNRunnableRootCommandNilInput(t *testing.T) { - args := make([]string, 0) - c := initialize() - - buf := new(bytes.Buffer) - // Testing flag with invalid input - c.SetOutput(buf) - cmdEcho.AddCommand(cmdTimes) - c.AddCommand(cmdPrint, cmdEcho) - c.SetArgs(args) - - c.Execute() - - if !strings.Contains(buf.String(), cmdRootNoRun.Long) { - t.Errorf("Expected to get help output, Got: \n %s", buf) - } -} - -func TestRootNoCommandHelp(t *testing.T) { - x := rootOnlySetupTest("--help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } - - x = rootOnlySetupTest("echo --help") - - checkResultOmits(t, x, "Available Commands:") - checkResultOmits(t, x, "for more information about a command") - - if strings.Contains(x.Output, "unknown flag: --help") { - t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output) - } -} - -func TestRootUnknownCommand(t *testing.T) { - r := noRRSetupTest("bogus") - s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } - - r = noRRSetupTest("--strtwo=a bogus") - if r.Output != s { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output) - } -} - -func TestRootSuggestions(t *testing.T) { - outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n" - outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n" - - cmd := initializeWithRootCmd() - cmd.AddCommand(cmdTimes) - - tests := map[string]string{ - "time": "times", - "tiems": "times", - "tims": "times", - "timeS": "times", - "rimes": "times", - "ti": "times", - "t": "times", - "timely": "times", - "ri": "", - "timezone": "", - "foo": "", - "counts": "times", - } - - for typo, suggestion := range tests { - for _, suggestionsDisabled := range []bool{false, true} { - cmd.DisableSuggestions = suggestionsDisabled - result := simpleTester(cmd, typo) - expected := "" - if len(suggestion) == 0 || suggestionsDisabled { - expected = fmt.Sprintf(outputWithoutSuggestions, typo) - } else { - expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion) - } - if result.Output != expected { - t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output) - } - } - } -} - -func TestFlagsBeforeCommand(t *testing.T) { - // short without space - x := fullSetupTest("-i10 echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - // short (int) with equals - // It appears that pflags doesn't support this... - // Commenting out until support can be added - - //x = noRRSetupTest("echo -i=10") - //if x.Error != nil { - //t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - //} - - // long with equals - x = noRRSetupTest("--intone=123 echo one two") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error) - } - - // With parsing error properly reported - x = fullSetupTest("-i10E echo") - if !strings.Contains(x.Output, "invalid argument \"10E\" for i10E") { - t.Errorf("Wrong error message displayed, \n %s", x.Output) - } - - //With quotes - x = fullSetupTest("-s=\"walking\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With inner quote - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - - //With quotes and space - x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - } - -} - -func TestRemoveCommand(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - x := fullTester(c, "version") - if x.Error == nil { - t.Errorf("Removed command should not have been called\n") - return - } -} - -func TestCommandWithoutSubcommands(t *testing.T) { - c := initializeWithRootCmd() - - x := simpleTester(c, "") - if x.Error != nil { - t.Errorf("Calling command without subcommands should not have error: %v", x.Error) - return - } -} - -func TestCommandWithoutSubcommandsWithArg(t *testing.T) { - c := initializeWithRootCmd() - expectedArgs := []string{"arg"} - - x := simpleTester(c, "arg") - if x.Error != nil { - t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error) - return - } - if !reflect.DeepEqual(expectedArgs, tr) { - t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr) - return - } -} - -func TestReplaceCommandWithRemove(t *testing.T) { - versionUsed = 0 - c := initializeWithRootCmd() - c.AddCommand(cmdVersion1) - c.RemoveCommand(cmdVersion1) - c.AddCommand(cmdVersion2) - x := fullTester(c, "version") - if x.Error != nil { - t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error) - return - } - if versionUsed == 1 { - t.Errorf("Removed command shouldn't be called\n") - } - if versionUsed != 2 { - t.Errorf("Replacing command should have been called but didn't\n") - } -} - -func TestDeprecatedSub(t *testing.T) { - c := fullSetupTest("deprecated") - - checkResultContains(t, c, cmdDeprecated.Deprecated) -} - -func TestPreRun(t *testing.T) { - noRRSetupTest("echo one two") - if echoPre == nil || echoPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if rootPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("echo times one two") - if timesPersPre == nil { - t.Error("PreRun or PersistentPreRun not called") - } - if echoPre != nil || echoPersPre != nil || rootPersPre != nil { - t.Error("Wrong *Pre functions called!") - } - - noRRSetupTest("print one two") - if rootPersPre == nil { - t.Error("Parent PersistentPreRun not called but should not have been") - } - if echoPre != nil || echoPersPre != nil || timesPersPre != nil { - t.Error("Wrong *Pre functions called!") - } -} - -// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last -func TestPeristentPreRunPropagation(t *testing.T) { - rootCmd := initialize() - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - - rootCmd.SetArgs(strings.Split("print echosub lala", " ")) - rootCmd.Execute() - - if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" { - t.Error("RootCmd PersistentPreRun not called but should have been") - } -} - -func TestGlobalNormFuncPropagation(t *testing.T) { - normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName { - return pflag.NormalizedName(name) - } - - rootCmd := initialize() - rootCmd.SetGlobalNormalizationFunc(normFunc) - if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) { - t.Error("rootCmd seems to have a wrong normalization function") - } - - // First add the cmdEchoSub to cmdPrint - cmdPrint.AddCommand(cmdEchoSub) - if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil { - t.Error("cmdPrint and cmdEchoSub should had no normalization functions") - } - - // Now add cmdPrint to rootCmd - rootCmd.AddCommand(cmdPrint) - if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() || - reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() { - t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") - } -} - -func TestFlagOnPflagCommandLine(t *testing.T) { - flagName := "flagOnCommandLine" - pflag.CommandLine.String(flagName, "", "about my flag") - r := fullSetupTest("--help") - - checkResultContains(t, r, flagName) -} - -func TestAddTemplateFunctions(t *testing.T) { - AddTemplateFunc("t", func() bool { return true }) - AddTemplateFuncs(template.FuncMap{ - "f": func() bool { return false }, - "h": func() string { return "Hello," }, - "w": func() string { return "world." }}) - - const usage = "Hello, world." - - c := &Command{} - c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) - - if us := c.UsageString(); us != usage { - t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go deleted file mode 100644 index 43ed7a34fcc..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/command_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package cobra - -import ( - "reflect" - "testing" -) - -// test to ensure hidden commands run as intended -func TestHiddenCommandExecutes(t *testing.T) { - - // ensure that outs does not already equal what the command will be setting it - // to, if it did this test would not actually be testing anything... - if outs == "hidden" { - t.Errorf("outs should NOT EQUAL hidden") - } - - cmdHidden.Execute() - - // upon running the command, the value of outs should now be 'hidden' - if outs != "hidden" { - t.Errorf("Hidden command failed to run!") - } -} - -// test to ensure hidden commands do not show up in usage/help text -func TestHiddenCommandIsHidden(t *testing.T) { - if cmdHidden.IsAvailableCommand() { - t.Errorf("Hidden command found!") - } -} - -func TestStripFlags(t *testing.T) { - tests := []struct { - input []string - output []string - }{ - { - []string{"foo", "bar"}, - []string{"foo", "bar"}, - }, - { - []string{"foo", "--bar", "-b"}, - []string{"foo"}, - }, - { - []string{"-b", "foo", "--bar", "bar"}, - []string{}, - }, - { - []string{"-i10", "echo"}, - []string{"echo"}, - }, - { - []string{"-i=10", "echo"}, - []string{"echo"}, - }, - { - []string{"--int=100", "echo"}, - []string{"echo"}, - }, - { - []string{"-ib", "echo", "-bfoo", "baz"}, - []string{"echo", "baz"}, - }, - { - []string{"-i=baz", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--int=baz", "-bbar", "-i", "foo", "blah"}, - []string{"blah"}, - }, - { - []string{"--cat", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"-c", "bar", "-i", "foo", "blah"}, - []string{"bar", "blah"}, - }, - { - []string{"--persist", "bar"}, - []string{"bar"}, - }, - { - []string{"-p", "bar"}, - []string{"bar"}, - }, - } - - cmdPrint := &Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `an utterly useless command for testing.`, - Run: func(cmd *Command, args []string) { - tp = args - }, - } - - var flagi int - var flagstr string - var flagbool bool - cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one") - cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int") - cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string") - cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool") - - for _, test := range tests { - output := stripFlags(test.input, cmdPrint) - if !reflect.DeepEqual(test.output, output) { - t.Errorf("expected: %v, got: %v", test.output, output) - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go deleted file mode 100644 index 10da9850eae..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package cobra_test - -import ( - "bytes" - "fmt" - - "github.com/spf13/cobra" -) - -func ExampleCommand_GenManTree() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &cobra.GenManHeader{ - Title: "MINE", - Section: "3", - } - cmd.GenManTree(header, "/tmp") -} - -func ExampleCommand_GenMan() { - cmd := &cobra.Command{ - Use: "test", - Short: "my test program", - } - header := &cobra.GenManHeader{ - Title: "MINE", - Section: "3", - } - out := new(bytes.Buffer) - cmd.GenMan(header, out) - fmt.Print(out.String()) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go deleted file mode 100644 index 1c121d6c9ae..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func translate(in string) string { - return strings.Replace(in, "-", "\\-", -1) -} - -func TestGenManDoc(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - - out := new(bytes.Buffer) - - header := &GenManHeader{ - Title: "Project", - Section: "2", - } - // We generate on a subcommand so we have both subcommands and parents - cmdEcho.GenMan(header, out) - found := out.String() - - // Make sure parent has - in CommandPath() in SEE ALSO: - parentPath := cmdEcho.Parent().CommandPath() - dashParentPath := strings.Replace(parentPath, " ", "-", -1) - expected := translate(dashParentPath) - expected = expected + "(" + header.Section + ")" - checkStringContains(t, found, expected) - - // Our description - expected = translate(cmdEcho.Name()) - checkStringContains(t, found, expected) - - // Better have our example - expected = translate(cmdEcho.Name()) - checkStringContains(t, found, expected) - - // A local flag - expected = "boolone" - checkStringContains(t, found, expected) - - // persistent flag on parent - expected = "rootflag" - checkStringContains(t, found, expected) - - // We better output info about our parent - expected = translate(cmdRootWithRun.Name()) - checkStringContains(t, found, expected) - - // And about subcommands - expected = translate(cmdEchoSub.Name()) - checkStringContains(t, found, expected) - - unexpected := translate(cmdDeprecated.Name()) - checkStringOmits(t, found, unexpected) -} diff --git a/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go b/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go deleted file mode 100644 index defc9411525..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" -) - -var _ = fmt.Println -var _ = os.Stderr - -func TestGenMdDoc(t *testing.T) { - c := initializeWithRootCmd() - // Need two commands to run the command alphabetical sort - cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated) - c.AddCommand(cmdPrint, cmdEcho) - cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp) - - out := new(bytes.Buffer) - - // We generate on s subcommand so we have both subcommands and parents - GenMarkdown(cmdEcho, out) - found := out.String() - - // Our description - expected := cmdEcho.Long - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // Better have our example - expected = cmdEcho.Example - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // A local flag - expected = "boolone" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // persistent flag on parent - expected = "rootflag" - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // We better output info about our parent - expected = cmdRootWithRun.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - // And about subcommands - expected = cmdEchoSub.Short - if !strings.Contains(found, expected) { - t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found) - } - - unexpected := cmdDeprecated.Short - if strings.Contains(found, unexpected) { - t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go deleted file mode 100644 index afd25ae2f1d..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "bytes" - "fmt" - "strconv" - "testing" -) - -// This value can be a boolean ("true", "false") or "maybe" -type triStateValue int - -const ( - triStateFalse triStateValue = 0 - triStateTrue triStateValue = 1 - triStateMaybe triStateValue = 2 -) - -const strTriStateMaybe = "maybe" - -func (v *triStateValue) IsBoolFlag() bool { - return true -} - -func (v *triStateValue) Get() interface{} { - return triStateValue(*v) -} - -func (v *triStateValue) Set(s string) error { - if s == strTriStateMaybe { - *v = triStateMaybe - return nil - } - boolVal, err := strconv.ParseBool(s) - if boolVal { - *v = triStateTrue - } else { - *v = triStateFalse - } - return err -} - -func (v *triStateValue) String() string { - if *v == triStateMaybe { - return strTriStateMaybe - } - return fmt.Sprintf("%v", bool(*v == triStateTrue)) -} - -// The type of the flag as required by the pflag.Value interface -func (v *triStateValue) Type() string { - return "version" -} - -func setUpFlagSet(tristate *triStateValue) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - *tristate = triStateFalse - flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)") - flag.NoOptDefVal = "true" - return f -} - -func TestExplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=true"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestImplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlag(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"-t"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlagExtraArgument(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - // The"maybe"turns into an arg, since short boolean options will only do true/false - err := f.Parse([]string{"-t", "maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } - args := f.Args() - if len(args) != 1 || args[0] != "maybe" { - t.Fatal("expected an extra 'maybe' argument to stick around") - } -} - -func TestExplicitMaybe(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateMaybe { - t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead") - } -} - -func TestExplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=false"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestImplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestInvalidValue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - var buf bytes.Buffer - f.SetOutput(&buf) - err := f.Parse([]string{"--tristate=invalid"}) - if err == nil { - t.Fatal("expected an error but did not get any, tristate has value", tristate) - } -} - -func TestBoolP(t *testing.T) { - b := BoolP("bool", "b", false, "bool value in CommandLine") - c := BoolP("c", "c", false, "other bool value") - args := []string{"--bool"} - if err := CommandLine.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if *b != true { - t.Errorf("expected b=true got b=%s", b) - } - if *c != false { - t.Errorf("expect c=false got c=%s", c) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go deleted file mode 100644 index 716765cba1e..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/count_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package pflag - -import ( - "fmt" - "os" - "testing" -) - -var _ = fmt.Printf - -func setUpCount(c *int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.CountVarP(c, "verbose", "v", "a counter") - return f -} - -func TestCount(t *testing.T) { - testCases := []struct { - input []string - success bool - expected int - }{ - {[]string{"-vvv"}, true, 3}, - {[]string{"-v", "-v", "-v"}, true, 3}, - {[]string{"-v", "--verbose", "-v"}, true, 3}, - {[]string{"-v=3", "-v"}, true, 4}, - {[]string{"-v=a"}, false, 0}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var count int - f := setUpCount(&count) - - tc := &testCases[i] - - err := f.Parse(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure, got success") - continue - } else if tc.success { - c, err := f.GetCount("verbose") - if err != nil { - t.Errorf("Got error trying to fetch the counter flag") - } - if c != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, c) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/example_test.go deleted file mode 100644 index 9be7a49f26f..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/example_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. - -// These examples demonstrate more intricate uses of the flag package. -package pflag_test - -import ( - "errors" - "fmt" - "strings" - "time" - - flag "github.com/spf13/pflag" -) - -// Example 1: A single string flag called "species" with default value "gopher". -var species = flag.String("species", "gopher", "the species we are studying") - -// Example 2: A flag with a shorthand letter. -var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher") - -// Example 3: A user-defined flag type, a slice of durations. -type interval []time.Duration - -// String is the method to format the flag's value, part of the flag.Value interface. -// The String method's output will be used in diagnostics. -func (i *interval) String() string { - return fmt.Sprint(*i) -} - -func (i *interval) Type() string { - return "interval" -} - -// Set is the method to set the flag value, part of the flag.Value interface. -// Set's argument is a string to be parsed to set the flag. -// It's a comma-separated list, so we split it. -func (i *interval) Set(value string) error { - // If we wanted to allow the flag to be set multiple times, - // accumulating values, we would delete this if statement. - // That would permit usages such as - // -deltaT 10s -deltaT 15s - // and other combinations. - if len(*i) > 0 { - return errors.New("interval flag already set") - } - for _, dt := range strings.Split(value, ",") { - duration, err := time.ParseDuration(dt) - if err != nil { - return err - } - *i = append(*i, duration) - } - return nil -} - -// Define a flag to accumulate durations. Because it has a special type, -// we need to use the Var function and therefore create the flag during -// init. - -var intervalFlag interval - -func init() { - // Tie the command-line flag to the intervalFlag variable and - // set a usage message. - flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") -} - -func Example() { - // All the interesting pieces are with the variables declared above, but - // to enable the flag package to see the flags defined there, one must - // execute, typically at the start of main (not init!): - // flag.Parse() - // We don't run it here because this is not a main function and - // the testing suite has already parsed the flags. -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go deleted file mode 100644 index 9318fee00e1..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/export_test.go +++ /dev/null @@ -1,29 +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 pflag - -import ( - "io/ioutil" - "os" -) - -// Additional routines compiled into the package only during testing. - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = &FlagSet{ - name: os.Args[0], - errorHandling: ContinueOnError, - output: ioutil.Discard, - } - Usage = usage -} - -// GetCommandLine returns the default FlagSet. -func GetCommandLine() *FlagSet { - return CommandLine -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go deleted file mode 100644 index e17b2aad8e3..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go +++ /dev/null @@ -1,874 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "reflect" - "sort" - "strings" - "testing" - "time" -) - -var ( - testBool = Bool("test_bool", false, "bool value") - testInt = Int("test_int", 0, "int value") - testInt64 = Int64("test_int64", 0, "int64 value") - testUint = Uint("test_uint", 0, "uint value") - testUint64 = Uint64("test_uint64", 0, "uint64 value") - testString = String("test_string", "0", "string value") - testFloat = Float64("test_float64", 0, "float64 value") - testDuration = Duration("test_duration", 0, "time.Duration value") - testOptionalInt = Int("test_optional_int", 0, "optional int value") - normalizeFlagNameInvocations = 0 -) - -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - m[f.Name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case f.Name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case f.Name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", f.Name) - } - } - } - VisitAll(visitor) - if len(m) != 9 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - Set("test_optional_int", "1") - desired = "1" - Visit(visitor) - if len(m) != 9 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestUsage(t *testing.T) { - called := false - ResetForTesting(func() { called = true }) - if GetCommandLine().Parse([]string{"--x"}) == nil { - t.Error("parse did not fail for unknown flag") - } - if !called { - t.Error("did not call Usage for unknown flag") - } -} - -func TestAddFlagSet(t *testing.T) { - oldSet := NewFlagSet("old", ContinueOnError) - newSet := NewFlagSet("new", ContinueOnError) - - oldSet.String("flag1", "flag1", "flag1") - oldSet.String("flag2", "flag2", "flag2") - - newSet.String("flag2", "flag2", "flag2") - newSet.String("flag3", "flag3", "flag3") - - oldSet.AddFlagSet(newSet) - - if len(oldSet.formal) != 3 { - t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) - } -} - -func TestAnnotation(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - - if err := f.SetAnnotation("missing-flag", "key", nil); err == nil { - t.Errorf("Expected error setting annotation on non-existent flag") - } - - f.StringP("stringa", "a", "", "string value") - if err := f.SetAnnotation("stringa", "key", nil); err != nil { - t.Errorf("Unexpected error setting new nil annotation: %v", err) - } - if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil { - t.Errorf("Unexpected annotation: %v", annotation) - } - - f.StringP("stringb", "b", "", "string2 value") - if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil { - t.Errorf("Unexpected error setting new annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } - - if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil { - t.Errorf("Unexpected error updating annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - bool3Flag := f.Bool("bool3", false, "bool3 value") - intFlag := f.Int("int", 0, "int value") - int8Flag := f.Int8("int8", 0, "int value") - int32Flag := f.Int32("int32", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint8Flag := f.Uint8("uint8", 0, "uint value") - uint16Flag := f.Uint16("uint16", 0, "uint value") - uint32Flag := f.Uint32("uint32", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float32Flag := f.Float32("float32", 0, "float32 value") - float64Flag := f.Float64("float64", 0, "float64 value") - ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value") - maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - extra := "one-extra-argument" - args := []string{ - "--bool", - "--bool2=true", - "--bool3=false", - "--int=22", - "--int8=-8", - "--int32=-32", - "--int64=0x23", - "--uint", "24", - "--uint8=8", - "--uint16=16", - "--uint32=32", - "--uint64=25", - "--string=hello", - "--float32=-172e12", - "--float64=2718e28", - "--ip=10.11.12.13", - "--mask=255.255.255.0", - "--duration=2m", - "--optional-int-no-value", - "--optional-int-with-value=42", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if v, err := f.GetBool("bool"); err != nil || v != *boolFlag { - t.Error("GetBool does not work.") - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *bool3Flag != false { - t.Error("bool3 flag should be false, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if v, err := f.GetInt("int"); err != nil || v != *intFlag { - t.Error("GetInt does not work.") - } - if *int8Flag != -8 { - t.Error("int8 flag should be 0x23, is ", *int8Flag) - } - if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { - t.Error("GetInt8 does not work.") - } - if *int32Flag != -32 { - t.Error("int32 flag should be 0x23, is ", *int32Flag) - } - if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag { - t.Error("GetInt32 does not work.") - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag { - t.Error("GetInt64 does not work.") - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if v, err := f.GetUint("uint"); err != nil || v != *uintFlag { - t.Error("GetUint does not work.") - } - if *uint8Flag != 8 { - t.Error("uint8 flag should be 8, is ", *uint8Flag) - } - if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag { - t.Error("GetUint8 does not work.") - } - if *uint16Flag != 16 { - t.Error("uint16 flag should be 16, is ", *uint16Flag) - } - if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag { - t.Error("GetUint16 does not work.") - } - if *uint32Flag != 32 { - t.Error("uint32 flag should be 32, is ", *uint32Flag) - } - if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag { - t.Error("GetUint32 does not work.") - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag { - t.Error("GetUint64 does not work.") - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if v, err := f.GetString("string"); err != nil || v != *stringFlag { - t.Error("GetString does not work.") - } - if *float32Flag != -172e12 { - t.Error("float32 flag should be -172e12, is ", *float32Flag) - } - if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag { - t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag { - t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag) - } - if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) { - t.Error("ip flag should be 10.11.12.13, is ", *ipFlag) - } - if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) { - t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag) - } - if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() { - t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) - } - if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag { - t.Error("GetDuration does not work.") - } - if _, err := f.GetInt("duration"); err == nil { - t.Error("GetInt parsed a time.Duration?!?!") - } - if *optionalIntNoValueFlag != 9 { - t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag) - } - if *optionalIntWithValueFlag != 42 { - t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func TestShorthand(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolaFlag := f.BoolP("boola", "a", false, "bool value") - boolbFlag := f.BoolP("boolb", "b", false, "bool2 value") - boolcFlag := f.BoolP("boolc", "c", false, "bool3 value") - booldFlag := f.BoolP("boold", "d", false, "bool4 value") - stringaFlag := f.StringP("stringa", "s", "0", "string value") - stringzFlag := f.StringP("stringz", "z", "0", "string value") - extra := "interspersed-argument" - notaflag := "--i-look-like-a-flag" - args := []string{ - "-ab", - extra, - "-cs", - "hello", - "-z=something", - "-d=true", - "--", - notaflag, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolaFlag != true { - t.Error("boola flag should be true, is ", *boolaFlag) - } - if *boolbFlag != true { - t.Error("boolb flag should be true, is ", *boolbFlag) - } - if *boolcFlag != true { - t.Error("boolc flag should be true, is ", *boolcFlag) - } - if *booldFlag != true { - t.Error("boold flag should be true, is ", *booldFlag) - } - if *stringaFlag != "hello" { - t.Error("stringa flag should be `hello`, is ", *stringaFlag) - } - if *stringzFlag != "something" { - t.Error("stringz flag should be `something`, is ", *stringzFlag) - } - if len(f.Args()) != 2 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } else if f.Args()[1] != notaflag { - t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) - } - if f.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) - } -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(GetCommandLine(), t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -func TestChangedHelper(t *testing.T) { - f := NewFlagSet("changedtest", ContinueOnError) - _ = f.Bool("changed", false, "changed bool") - _ = f.Bool("settrue", true, "true to true") - _ = f.Bool("setfalse", false, "false to false") - _ = f.Bool("unchanged", false, "unchanged bool") - - args := []string{"--changed", "--settrue", "--setfalse=false"} - if err := f.Parse(args); err != nil { - t.Error("f.Parse() = false after Parse") - } - if !f.Changed("changed") { - t.Errorf("--changed wasn't changed!") - } - if !f.Changed("settrue") { - t.Errorf("--settrue wasn't changed!") - } - if !f.Changed("setfalse") { - t.Errorf("--setfalse wasn't changed!") - } - if f.Changed("unchanged") { - t.Errorf("--unchanged was changed!") - } - if f.Changed("invalid") { - t.Errorf("--invalid was changed!") - } - if f.ArgsLenAtDash() != -1 { - t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) - } -} - -func replaceSeparators(name string, from []string, to string) string { - result := name - for _, sep := range from { - result = strings.Replace(result, sep, to, -1) - } - // Type convert to indicate normalization has been done. - return result -} - -func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - name = replaceSeparators(name, seps, ".") - normalizeFlagNameInvocations++ - - return NormalizedName(name) -} - -func testWordSepNormalizedNames(args []string, t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - withDashFlag := f.Bool("with-dash-flag", false, "bool value") - // Set this after some flags have been added and before others. - f.SetNormalizeFunc(wordSepNormalizeFunc) - withUnderFlag := f.Bool("with_under_flag", false, "bool value") - withBothFlag := f.Bool("with-both_flag", false, "bool value") - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *withDashFlag != true { - t.Error("withDashFlag flag should be true, is ", *withDashFlag) - } - if *withUnderFlag != true { - t.Error("withUnderFlag flag should be true, is ", *withUnderFlag) - } - if *withBothFlag != true { - t.Error("withBothFlag flag should be true, is ", *withBothFlag) - } -} - -func TestWordSepNormalizedNames(t *testing.T) { - args := []string{ - "--with-dash-flag", - "--with-under-flag", - "--with-both-flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with_dash_flag", - "--with_under_flag", - "--with_both_flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with-dash_flag", - "--with-under_flag", - "--with-both_flag", - } - testWordSepNormalizedNames(args, t) -} - -func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - - oldName := replaceSeparators("old-valid_flag", seps, ".") - newName := replaceSeparators("valid-flag", seps, ".") - - name = replaceSeparators(name, seps, ".") - switch name { - case oldName: - name = newName - break - } - - return NormalizedName(name) -} - -func TestCustomNormalizedNames(t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - - validFlag := f.Bool("valid-flag", false, "bool value") - f.SetNormalizeFunc(aliasAndWordSepFlagNames) - someOtherFlag := f.Bool("some-other-flag", false, "bool value") - - args := []string{"--old_valid_flag", "--some-other_flag"} - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - - if *validFlag != true { - t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag) - } - if *someOtherFlag != true { - t.Error("someOtherFlag should be true, is ", *someOtherFlag) - } -} - -// Every flag we add, the name (displayed also in usage) should normalized -func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { - // Test normalization after addition - f := NewFlagSet("normalized", ContinueOnError) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid_flag" { - t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name) - } - - f.SetNormalizeFunc(wordSepNormalizeFunc) - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } - - // Test normalization before addition - f = NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func (f *flagVar) Type() string { - return "flagVar" -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.VarP(&v, "v", "v", "usage") - if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"--unknown"}) - if out := buf.String(); !strings.Contains(out, "--unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "--before", "subcmd"} - before := Bool("before", false, "") - if err := GetCommandLine().Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = []string{"subcmd", "--after", "args"} - after := Bool("after", false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, "flag", false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"--flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by --flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"--help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, "help", false, "help flag") - helpCalled = false - err = fs.Parse([]string{"--help"}) - if err != nil { - t.Fatal("expected no error for defined --help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -func TestNoInterspersed(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - f.SetInterspersed(false) - f.Bool("true", true, "always true") - f.Bool("false", false, "always false") - err := f.Parse([]string{"--true", "break", "--false"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - args := f.Args() - if len(args) != 2 || args[0] != "break" || args[1] != "--false" { - t.Fatal("expected interspersed options/non-options to fail") - } -} - -func TestTermination(t *testing.T) { - f := NewFlagSet("termination", ContinueOnError) - boolFlag := f.BoolP("bool", "l", false, "bool value") - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - arg1 := "ls" - arg2 := "-l" - args := []string{ - "--", - arg1, - arg2, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Fatal("expected no error; got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag { - t.Error("expected boolFlag=false, got true") - } - if len(f.Args()) != 2 { - t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args()) - } - if f.Args()[0] != arg1 { - t.Errorf("expected argument %q got %q", arg1, f.Args()[0]) - } - if f.Args()[1] != arg2 { - t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) - } - if f.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) - } -} - -func TestDeprecatedFlagInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - f.MarkDeprecated("badflag", "use --good-flag instead") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "badflag") { - t.Errorf("found deprecated flag in usage!") - } -} - -func TestDeprecatedFlagShorthandInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "-n,") { - t.Errorf("found deprecated flag shorthand in usage!") - } -} - -func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { - oldStderr := os.Stderr - r, w, _ := os.Pipe() - os.Stderr = w - - err := f.Parse(args) - - outC := make(chan string) - // copy the output in a separate goroutine so printing can't block indefinitely - go func() { - var buf bytes.Buffer - io.Copy(&buf, r) - outC <- buf.String() - }() - - w.Close() - os.Stderr = oldStderr - out := <-outC - - return out, err -} - -func TestDeprecatedFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - usageMsg := "use --good-flag instead" - f.MarkDeprecated("badflag", usageMsg) - - args := []string{"--badflag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagShorthandUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - usageMsg := fmt.Sprintf("use --%s instead", name) - f.MarkShorthandDeprecated(name, usageMsg) - - args := []string{"-n"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagUsageNormalized(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("bad-double_flag", true, "always true") - f.SetNormalizeFunc(wordSepNormalizeFunc) - usageMsg := "use --good-flag instead" - f.MarkDeprecated("bad_double-flag", usageMsg) - - args := []string{"--bad_double_flag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -// Name normalization function should be called only once on flag addition -func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { - normalizeFlagNameInvocations = 0 - - f := NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - f.Bool("with_under_flag", false, "bool value") - - if normalizeFlagNameInvocations != 1 { - t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) - } -} - -// -func TestHiddenFlagInUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "secretFlag") { - t.Errorf("found hidden flag in usage!") - } -} - -// -func TestHiddenFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - args := []string{"--secretFlag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if strings.Contains(out, "shhh") { - t.Errorf("usage message printed when using a hidden flag!") - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go deleted file mode 100644 index 77e2d7d80a3..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/golangflag_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "testing" -) - -func TestGoflags(t *testing.T) { - goflag.String("stringFlag", "stringFlag", "stringFlag") - goflag.Bool("boolFlag", false, "boolFlag") - - f := NewFlagSet("test", ContinueOnError) - - f.AddGoFlagSet(goflag.CommandLine) - err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) - if err != nil { - t.Fatal("expected no error; get", err) - } - - getString, err := f.GetString("stringFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getString != "bob" { - t.Fatalf("expected getString=bob but got getString=%s", getString) - } - - getBool, err := f.GetBool("boolFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getBool != true { - t.Fatalf("expected getBool=true but got getBool=%v", getBool) - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go deleted file mode 100644 index 5f2eee66a43..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/int_slice_test.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpISFlagSet(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{}, "Command separated list!") - return f -} - -func setUpISFlagSetWithDefault(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!") - return f -} - -func TestEmptyIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if len(getIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS)) - } -} - -func TestIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v) - } - } - getIS, err := f.GetIntSlice("is") - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v) - } - } -} - -func TestISDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISWithDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISCalledTwice(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--is=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - if expected[i] != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go deleted file mode 100644 index 1fec50e4252..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/ip_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIP(ip *net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address") - return f -} - -func TestIP(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0", true, "0.0.0.0"}, - {" 0.0.0.0 ", true, "0.0.0.0"}, - {"1.2.3.4", true, "1.2.3.4"}, - {"127.0.0.1", true, "127.0.0.1"}, - {"255.255.255.255", true, "255.255.255.255"}, - {"", false, ""}, - {"0", false, ""}, - {"localhost", false, ""}, - {"0.0.0", false, ""}, - {"0.0.0.", false, ""}, - {"0.0.0.0.", false, ""}, - {"0.0.0.256", false, ""}, - {"0 . 0 . 0 . 0", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IP - f := setUpIP(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIP("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go deleted file mode 100644 index 335b6fa156d..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/ipnet_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIPNet(ip *net.IPNet) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - _, def, _ := net.ParseCIDR("0.0.0.0/0") - f.IPNetVar(ip, "address", *def, "IP Address") - return f -} - -func TestIPNet(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0/0", true, "0.0.0.0/0"}, - {" 0.0.0.0/0 ", true, "0.0.0.0/0"}, - {"1.2.3.4/8", true, "1.0.0.0/8"}, - {"127.0.0.1/16", true, "127.0.0.0/16"}, - {"255.255.255.255/19", true, "255.255.224.0/19"}, - {"255.255.255.255/32", true, "255.255.255.255/32"}, - {"", false, ""}, - {"/0", false, ""}, - {"0", false, ""}, - {"0/0", false, ""}, - {"localhost/0", false, ""}, - {"0.0.0/4", false, ""}, - {"0.0.0./8", false, ""}, - {"0.0.0.0./12", false, ""}, - {"0.0.0.256/16", false, ""}, - {"0.0.0.0 /20", false, ""}, - {"0.0.0.0/ 24", false, ""}, - {"0 . 0 . 0 . 0 / 28", false, ""}, - {"0.0.0.0/33", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IPNet - f := setUpIPNet(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIPNet("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go b/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go deleted file mode 100644 index 97602de591e..00000000000 --- a/Godeps/_workspace/src/github.com/spf13/pflag/string_slice_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - "fmt" - "strings" - "testing" -) - -func setUpSSFlagSet(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!") - return f -} - -func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestSS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSWithDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSCalledTwice(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{"one,two", "three"} - expected := []string{"one", "two", "three"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go deleted file mode 100644 index ce5d8e4aa1a..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/accessors_test.go +++ /dev/null @@ -1,145 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestAccessorsAccessGetSingleField(t *testing.T) { - - current := map[string]interface{}{"name": "Tyler"} - assert.Equal(t, "Tyler", access(current, "name", nil, false, true)) - -} -func TestAccessorsAccessGetDeep(t *testing.T) { - - current := map[string]interface{}{"name": map[string]interface{}{"first": "Tyler", "last": "Bunnell"}} - assert.Equal(t, "Tyler", access(current, "name.first", nil, false, true)) - assert.Equal(t, "Bunnell", access(current, "name.last", nil, false, true)) - -} -func TestAccessorsAccessGetDeepDeep(t *testing.T) { - - current := map[string]interface{}{"one": map[string]interface{}{"two": map[string]interface{}{"three": map[string]interface{}{"four": 4}}}} - assert.Equal(t, 4, access(current, "one.two.three.four", nil, false, true)) - -} -func TestAccessorsAccessGetInsideArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}}} - assert.Equal(t, "Tyler", access(current, "names[0].first", nil, false, true)) - assert.Equal(t, "Bunnell", access(current, "names[0].last", nil, false, true)) - assert.Equal(t, "Capitol", access(current, "names[1].first", nil, false, true)) - assert.Equal(t, "Bollocks", access(current, "names[1].last", nil, false, true)) - - assert.Panics(t, func() { - access(current, "names[2]", nil, false, true) - }) - assert.Nil(t, access(current, "names[2]", nil, false, false)) - -} - -func TestAccessorsAccessGetFromArrayWithInt(t *testing.T) { - - current := []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}} - one := access(current, 0, nil, false, false) - two := access(current, 1, nil, false, false) - three := access(current, 2, nil, false, false) - - assert.Equal(t, "Tyler", one.(map[string]interface{})["first"]) - assert.Equal(t, "Capitol", two.(map[string]interface{})["first"]) - assert.Nil(t, three) - -} - -func TestAccessorsGet(t *testing.T) { - - current := New(map[string]interface{}{"name": "Tyler"}) - assert.Equal(t, "Tyler", current.Get("name").data) - -} - -func TestAccessorsAccessSetSingleField(t *testing.T) { - - current := map[string]interface{}{"name": "Tyler"} - access(current, "name", "Mat", true, false) - assert.Equal(t, current["name"], "Mat") - - access(current, "age", 29, true, true) - assert.Equal(t, current["age"], 29) - -} - -func TestAccessorsAccessSetSingleFieldNotExisting(t *testing.T) { - - current := map[string]interface{}{} - access(current, "name", "Mat", true, false) - assert.Equal(t, current["name"], "Mat") - -} - -func TestAccessorsAccessSetDeep(t *testing.T) { - - current := map[string]interface{}{"name": map[string]interface{}{"first": "Tyler", "last": "Bunnell"}} - - access(current, "name.first", "Mat", true, true) - access(current, "name.last", "Ryer", true, true) - - assert.Equal(t, "Mat", access(current, "name.first", nil, false, true)) - assert.Equal(t, "Ryer", access(current, "name.last", nil, false, true)) - -} -func TestAccessorsAccessSetDeepDeep(t *testing.T) { - - current := map[string]interface{}{"one": map[string]interface{}{"two": map[string]interface{}{"three": map[string]interface{}{"four": 4}}}} - - access(current, "one.two.three.four", 5, true, true) - - assert.Equal(t, 5, access(current, "one.two.three.four", nil, false, true)) - -} -func TestAccessorsAccessSetArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{"Tyler"}} - - access(current, "names[0]", "Mat", true, true) - - assert.Equal(t, "Mat", access(current, "names[0]", nil, false, true)) - -} -func TestAccessorsAccessSetInsideArray(t *testing.T) { - - current := map[string]interface{}{"names": []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}}} - - access(current, "names[0].first", "Mat", true, true) - access(current, "names[0].last", "Ryer", true, true) - access(current, "names[1].first", "Captain", true, true) - access(current, "names[1].last", "Underpants", true, true) - - assert.Equal(t, "Mat", access(current, "names[0].first", nil, false, true)) - assert.Equal(t, "Ryer", access(current, "names[0].last", nil, false, true)) - assert.Equal(t, "Captain", access(current, "names[1].first", nil, false, true)) - assert.Equal(t, "Underpants", access(current, "names[1].last", nil, false, true)) - -} - -func TestAccessorsAccessSetFromArrayWithInt(t *testing.T) { - - current := []interface{}{map[string]interface{}{"first": "Tyler", "last": "Bunnell"}, map[string]interface{}{"first": "Capitol", "last": "Bollocks"}} - one := access(current, 0, nil, false, false) - two := access(current, 1, nil, false, false) - three := access(current, 2, nil, false, false) - - assert.Equal(t, "Tyler", one.(map[string]interface{})["first"]) - assert.Equal(t, "Capitol", two.(map[string]interface{})["first"]) - assert.Nil(t, three) - -} - -func TestAccessorsSet(t *testing.T) { - - current := New(map[string]interface{}{"name": "Tyler"}) - current.Set("name", "Mat") - assert.Equal(t, "Mat", current.Get("name").data) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go deleted file mode 100644 index e9ccd2987b6..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestConversionJSON(t *testing.T) { - - jsonString := `{"name":"Mat"}` - o := MustFromJSON(jsonString) - - result, err := o.JSON() - - if assert.NoError(t, err) { - assert.Equal(t, jsonString, result) - } - - assert.Equal(t, jsonString, o.MustJSON()) - -} - -func TestConversionJSONWithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustJSON() - }) - - _, err := o.JSON() - - assert.Error(t, err) - -} - -func TestConversionBase64(t *testing.T) { - - o := New(map[string]interface{}{"name": "Mat"}) - - result, err := o.Base64() - - if assert.NoError(t, err) { - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", result) - } - - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", o.MustBase64()) - -} - -func TestConversionBase64WithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustBase64() - }) - - _, err := o.Base64() - - assert.Error(t, err) - -} - -func TestConversionSignedBase64(t *testing.T) { - - o := New(map[string]interface{}{"name": "Mat"}) - - result, err := o.SignedBase64("key") - - if assert.NoError(t, err) { - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", result) - } - - assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", o.MustSignedBase64("key")) - -} - -func TestConversionSignedBase64WithError(t *testing.T) { - - o := MSI() - o["test"] = func() {} - - assert.Panics(t, func() { - o.MustSignedBase64("key") - }) - - _, err := o.SignedBase64("key") - - assert.Error(t, err) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go deleted file mode 100644 index 27f7d9049a0..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -var fixtures = []struct { - // name is the name of the fixture (used for reporting - // failures) - name string - // data is the JSON data to be worked on - data string - // get is the argument(s) to pass to Get - get interface{} - // output is the expected output - output interface{} -}{ - { - name: "Simple get", - data: `{"name": "Mat"}`, - get: "name", - output: "Mat", - }, - { - name: "Get with dot notation", - data: `{"address": {"city": "Boulder"}}`, - get: "address.city", - output: "Boulder", - }, - { - name: "Deep get with dot notation", - data: `{"one": {"two": {"three": {"four": "hello"}}}}`, - get: "one.two.three.four", - output: "hello", - }, - { - name: "Get missing with dot notation", - data: `{"one": {"two": {"three": {"four": "hello"}}}}`, - get: "one.ten", - output: nil, - }, - { - name: "Get with array notation", - data: `{"tags": ["one", "two", "three"]}`, - get: "tags[1]", - output: "two", - }, - { - name: "Get with array and dot notation", - data: `{"types": { "tags": ["one", "two", "three"]}}`, - get: "types.tags[1]", - output: "two", - }, - { - name: "Get with array and dot notation - field after array", - data: `{"tags": [{"name":"one"}, {"name":"two"}, {"name":"three"}]}`, - get: "tags[1].name", - output: "two", - }, - { - name: "Complex get with array and dot notation", - data: `{"tags": [{"list": [{"one":"pizza"}]}]}`, - get: "tags[0].list[0].one", - output: "pizza", - }, - { - name: "Get field from within string should be nil", - data: `{"name":"Tyler"}`, - get: "name.something", - output: nil, - }, - { - name: "Get field from within string (using array accessor) should be nil", - data: `{"numbers":["one", "two", "three"]}`, - get: "numbers[0].nope", - output: nil, - }, -} - -func TestFixtures(t *testing.T) { - - for _, fixture := range fixtures { - - m := MustFromJSON(fixture.data) - - // get the value - t.Logf("Running get fixture: \"%s\" (%v)", fixture.name, fixture) - value := m.Get(fixture.get.(string)) - - // make sure it matches - assert.Equal(t, fixture.output, value.data, - "Get fixture \"%s\" failed: %v", fixture.name, fixture, - ) - - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go deleted file mode 100644 index 6beb5067569..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go +++ /dev/null @@ -1,10 +0,0 @@ -package objx - -var TestMap map[string]interface{} = map[string]interface{}{ - "name": "Tyler", - "address": map[string]interface{}{ - "city": "Salt Lake City", - "state": "UT", - }, - "numbers": []interface{}{"one", "two", "three", "four", "five"}, -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go deleted file mode 100644 index 1f8b45c6170..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go +++ /dev/null @@ -1,147 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -type Convertable struct { - name string -} - -func (c *Convertable) MSI() map[string]interface{} { - return map[string]interface{}{"name": c.name} -} - -type Unconvertable struct { - name string -} - -func TestMapCreation(t *testing.T) { - - o := New(nil) - assert.Nil(t, o) - - o = New("Tyler") - assert.Nil(t, o) - - unconvertable := &Unconvertable{name: "Tyler"} - o = New(unconvertable) - assert.Nil(t, o) - - convertable := &Convertable{name: "Tyler"} - o = New(convertable) - if assert.NotNil(t, convertable) { - assert.Equal(t, "Tyler", o["name"], "Tyler") - } - - o = MSI() - if assert.NotNil(t, o) { - assert.NotNil(t, o) - } - - o = MSI("name", "Tyler") - if assert.NotNil(t, o) { - if assert.NotNil(t, o) { - assert.Equal(t, o["name"], "Tyler") - } - } - -} - -func TestMapMustFromJSONWithError(t *testing.T) { - - _, err := FromJSON(`"name":"Mat"}`) - assert.Error(t, err) - -} - -func TestMapFromJSON(t *testing.T) { - - o := MustFromJSON(`{"name":"Mat"}`) - - if assert.NotNil(t, o) { - if assert.NotNil(t, o) { - assert.Equal(t, "Mat", o["name"]) - } - } - -} - -func TestMapFromJSONWithError(t *testing.T) { - - var m Map - - assert.Panics(t, func() { - m = MustFromJSON(`"name":"Mat"}`) - }) - - assert.Nil(t, m) - -} - -func TestMapFromBase64String(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWF0In0=" - - o, err := FromBase64(base64String) - - if assert.NoError(t, err) { - assert.Equal(t, o.Get("name").Str(), "Mat") - } - - assert.Equal(t, MustFromBase64(base64String).Get("name").Str(), "Mat") - -} - -func TestMapFromBase64StringWithError(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWFasd0In0=" - - _, err := FromBase64(base64String) - - assert.Error(t, err) - - assert.Panics(t, func() { - MustFromBase64(base64String) - }) - -} - -func TestMapFromSignedBase64String(t *testing.T) { - - base64String := "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" - - o, err := FromSignedBase64(base64String, "key") - - if assert.NoError(t, err) { - assert.Equal(t, o.Get("name").Str(), "Mat") - } - - assert.Equal(t, MustFromSignedBase64(base64String, "key").Get("name").Str(), "Mat") - -} - -func TestMapFromSignedBase64StringWithError(t *testing.T) { - - base64String := "eyJuYW1lasdIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" - - _, err := FromSignedBase64(base64String, "key") - - assert.Error(t, err) - - assert.Panics(t, func() { - MustFromSignedBase64(base64String, "key") - }) - -} - -func TestMapFromURLQuery(t *testing.T) { - - m, err := FromURLQuery("name=tyler&state=UT") - if assert.NoError(t, err) && assert.NotNil(t, m) { - assert.Equal(t, "tyler", m.Get("name").Str()) - assert.Equal(t, "UT", m.Get("state").Str()) - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go deleted file mode 100644 index e20ee23bc4b..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestExclude(t *testing.T) { - - d := make(Map) - d["name"] = "Mat" - d["age"] = 29 - d["secret"] = "ABC" - - excluded := d.Exclude([]string{"secret"}) - - assert.Equal(t, d["name"], excluded["name"]) - assert.Equal(t, d["age"], excluded["age"]) - assert.False(t, excluded.Has("secret"), "secret should be excluded") - -} - -func TestCopy(t *testing.T) { - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - d1Obj := New(d1) - d2Obj := d1Obj.Copy() - - d2Obj["name"] = "Mat" - - assert.Equal(t, d1Obj.Get("name").Str(), "Tyler") - assert.Equal(t, d2Obj.Get("name").Str(), "Mat") - -} - -func TestMerge(t *testing.T) { - - d := make(map[string]interface{}) - d["name"] = "Mat" - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - dObj := New(d) - d1Obj := New(d1) - - merged := dObj.Merge(d1Obj) - - assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) - assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) - assert.Empty(t, dObj.Get("location").Str()) - -} - -func TestMergeHere(t *testing.T) { - - d := make(map[string]interface{}) - d["name"] = "Mat" - - d1 := make(map[string]interface{}) - d1["name"] = "Tyler" - d1["location"] = "UT" - - dObj := New(d) - d1Obj := New(d1) - - merged := dObj.MergeHere(d1Obj) - - assert.Equal(t, dObj, merged, "With MergeHere, it should return the first modified map") - assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) - assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) - assert.Equal(t, merged.Get("location").Str(), dObj.Get("location").Str()) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go deleted file mode 100644 index 8f0898f62ca..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestHashWithKey(t *testing.T) { - - assert.Equal(t, "0ce84d8d01f2c7b6e0882b784429c54d280ea2d9", HashWithKey("abc", "def")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go deleted file mode 100644 index 5408c7fd3d3..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestSimpleExample(t *testing.T) { - - // build a map from a JSON object - o := MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`) - - // Map can be used as a straight map[string]interface{} - assert.Equal(t, o["name"], "Mat") - - // Get an Value object - v := o.Get("name") - assert.Equal(t, v, &Value{data: "Mat"}) - - // Test the contained value - assert.False(t, v.IsInt()) - assert.False(t, v.IsBool()) - assert.True(t, v.IsStr()) - - // Get the contained value - assert.Equal(t, v.Str(), "Mat") - - // Get a default value if the contained value is not of the expected type or does not exist - assert.Equal(t, 1, v.Int(1)) - - // Get a value by using array notation - assert.Equal(t, "indian", o.Get("foods[0]").Data()) - - // Set a value by using array notation - o.Set("foods[0]", "italian") - assert.Equal(t, "italian", o.Get("foods[0]").Str()) - - // Get a value by using dot notation - assert.Equal(t, "hobbiton", o.Get("location.county").Str()) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go deleted file mode 100644 index bcc1eb03d08..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package objx - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestHas(t *testing.T) { - - m := New(TestMap) - - assert.True(t, m.Has("name")) - assert.True(t, m.Has("address.state")) - assert.True(t, m.Has("numbers[4]")) - - assert.False(t, m.Has("address.state.nope")) - assert.False(t, m.Has("address.nope")) - assert.False(t, m.Has("nope")) - assert.False(t, m.Has("numbers[5]")) - - m = nil - assert.False(t, m.Has("nothing")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go deleted file mode 100644 index f7a4fceea3b..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/type_specific_codegen_test.go +++ /dev/null @@ -1,2867 +0,0 @@ -package objx - -import ( - "fmt" - "github.com/stretchr/testify/assert" - "testing" -) - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInter(t *testing.T) { - - val := interface{}("something") - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Inter()) - assert.Equal(t, val, New(m).Get("value").MustInter()) - assert.Equal(t, interface{}(nil), New(m).Get("nothing").Inter()) - assert.Equal(t, val, New(m).Get("nothing").Inter("something")) - - assert.Panics(t, func() { - New(m).Get("age").MustInter() - }) - -} - -func TestInterSlice(t *testing.T) { - - val := interface{}("something") - m := map[string]interface{}{"value": []interface{}{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").InterSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInterSlice()[0]) - assert.Equal(t, []interface{}(nil), New(m).Get("nothing").InterSlice()) - assert.Equal(t, val, New(m).Get("nothing").InterSlice([]interface{}{interface{}("something")})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInterSlice() - }) - -} - -func TestIsInter(t *testing.T) { - - var v *Value - - v = &Value{data: interface{}("something")} - assert.True(t, v.IsInter()) - - v = &Value{data: []interface{}{interface{}("something")}} - assert.True(t, v.IsInterSlice()) - -} - -func TestEachInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - count := 0 - replacedVals := make([]interface{}, 0) - assert.Equal(t, v, v.EachInter(func(i int, val interface{}) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInterSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustInterSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustInterSlice()[2]) - -} - -func TestWhereInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - selected := v.WhereInter(func(i int, val interface{}) bool { - return i%2 == 0 - }).MustInterSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - grouped := v.GroupInter(func(i int, val interface{}) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]interface{}) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - rawArr := v.MustInterSlice() - - replaced := v.ReplaceInter(func(index int, val interface{}) interface{} { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInterSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInter(t *testing.T) { - - v := &Value{data: []interface{}{interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something"), interface{}("something")}} - - collected := v.CollectInter(func(index int, val interface{}) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestMSI(t *testing.T) { - - val := map[string]interface{}(map[string]interface{}{"name": "Tyler"}) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").MSI()) - assert.Equal(t, val, New(m).Get("value").MustMSI()) - assert.Equal(t, map[string]interface{}(nil), New(m).Get("nothing").MSI()) - assert.Equal(t, val, New(m).Get("nothing").MSI(map[string]interface{}{"name": "Tyler"})) - - assert.Panics(t, func() { - New(m).Get("age").MustMSI() - }) - -} - -func TestMSISlice(t *testing.T) { - - val := map[string]interface{}(map[string]interface{}{"name": "Tyler"}) - m := map[string]interface{}{"value": []map[string]interface{}{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").MSISlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustMSISlice()[0]) - assert.Equal(t, []map[string]interface{}(nil), New(m).Get("nothing").MSISlice()) - assert.Equal(t, val, New(m).Get("nothing").MSISlice([]map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"})})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustMSISlice() - }) - -} - -func TestIsMSI(t *testing.T) { - - var v *Value - - v = &Value{data: map[string]interface{}(map[string]interface{}{"name": "Tyler"})} - assert.True(t, v.IsMSI()) - - v = &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - assert.True(t, v.IsMSISlice()) - -} - -func TestEachMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - count := 0 - replacedVals := make([]map[string]interface{}, 0) - assert.Equal(t, v, v.EachMSI(func(i int, val map[string]interface{}) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustMSISlice()[0]) - assert.Equal(t, replacedVals[1], v.MustMSISlice()[1]) - assert.Equal(t, replacedVals[2], v.MustMSISlice()[2]) - -} - -func TestWhereMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - selected := v.WhereMSI(func(i int, val map[string]interface{}) bool { - return i%2 == 0 - }).MustMSISlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - grouped := v.GroupMSI(func(i int, val map[string]interface{}) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]map[string]interface{}) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - rawArr := v.MustMSISlice() - - replaced := v.ReplaceMSI(func(index int, val map[string]interface{}) map[string]interface{} { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustMSISlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectMSI(t *testing.T) { - - v := &Value{data: []map[string]interface{}{map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"}), map[string]interface{}(map[string]interface{}{"name": "Tyler"})}} - - collected := v.CollectMSI(func(index int, val map[string]interface{}) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestObjxMap(t *testing.T) { - - val := (Map)(New(1)) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").ObjxMap()) - assert.Equal(t, val, New(m).Get("value").MustObjxMap()) - assert.Equal(t, (Map)(New(nil)), New(m).Get("nothing").ObjxMap()) - assert.Equal(t, val, New(m).Get("nothing").ObjxMap(New(1))) - - assert.Panics(t, func() { - New(m).Get("age").MustObjxMap() - }) - -} - -func TestObjxMapSlice(t *testing.T) { - - val := (Map)(New(1)) - m := map[string]interface{}{"value": [](Map){val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").ObjxMapSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustObjxMapSlice()[0]) - assert.Equal(t, [](Map)(nil), New(m).Get("nothing").ObjxMapSlice()) - assert.Equal(t, val, New(m).Get("nothing").ObjxMapSlice([](Map){(Map)(New(1))})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustObjxMapSlice() - }) - -} - -func TestIsObjxMap(t *testing.T) { - - var v *Value - - v = &Value{data: (Map)(New(1))} - assert.True(t, v.IsObjxMap()) - - v = &Value{data: [](Map){(Map)(New(1))}} - assert.True(t, v.IsObjxMapSlice()) - -} - -func TestEachObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - count := 0 - replacedVals := make([](Map), 0) - assert.Equal(t, v, v.EachObjxMap(func(i int, val Map) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustObjxMapSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustObjxMapSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustObjxMapSlice()[2]) - -} - -func TestWhereObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - selected := v.WhereObjxMap(func(i int, val Map) bool { - return i%2 == 0 - }).MustObjxMapSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - grouped := v.GroupObjxMap(func(i int, val Map) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][](Map)) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - rawArr := v.MustObjxMapSlice() - - replaced := v.ReplaceObjxMap(func(index int, val Map) Map { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustObjxMapSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectObjxMap(t *testing.T) { - - v := &Value{data: [](Map){(Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1)), (Map)(New(1))}} - - collected := v.CollectObjxMap(func(index int, val Map) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestBool(t *testing.T) { - - val := bool(true) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Bool()) - assert.Equal(t, val, New(m).Get("value").MustBool()) - assert.Equal(t, bool(false), New(m).Get("nothing").Bool()) - assert.Equal(t, val, New(m).Get("nothing").Bool(true)) - - assert.Panics(t, func() { - New(m).Get("age").MustBool() - }) - -} - -func TestBoolSlice(t *testing.T) { - - val := bool(true) - m := map[string]interface{}{"value": []bool{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").BoolSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustBoolSlice()[0]) - assert.Equal(t, []bool(nil), New(m).Get("nothing").BoolSlice()) - assert.Equal(t, val, New(m).Get("nothing").BoolSlice([]bool{bool(true)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustBoolSlice() - }) - -} - -func TestIsBool(t *testing.T) { - - var v *Value - - v = &Value{data: bool(true)} - assert.True(t, v.IsBool()) - - v = &Value{data: []bool{bool(true)}} - assert.True(t, v.IsBoolSlice()) - -} - -func TestEachBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true)}} - count := 0 - replacedVals := make([]bool, 0) - assert.Equal(t, v, v.EachBool(func(i int, val bool) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustBoolSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustBoolSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustBoolSlice()[2]) - -} - -func TestWhereBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - selected := v.WhereBool(func(i int, val bool) bool { - return i%2 == 0 - }).MustBoolSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - grouped := v.GroupBool(func(i int, val bool) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]bool) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - rawArr := v.MustBoolSlice() - - replaced := v.ReplaceBool(func(index int, val bool) bool { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustBoolSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectBool(t *testing.T) { - - v := &Value{data: []bool{bool(true), bool(true), bool(true), bool(true), bool(true), bool(true)}} - - collected := v.CollectBool(func(index int, val bool) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestStr(t *testing.T) { - - val := string("hello") - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Str()) - assert.Equal(t, val, New(m).Get("value").MustStr()) - assert.Equal(t, string(""), New(m).Get("nothing").Str()) - assert.Equal(t, val, New(m).Get("nothing").Str("hello")) - - assert.Panics(t, func() { - New(m).Get("age").MustStr() - }) - -} - -func TestStrSlice(t *testing.T) { - - val := string("hello") - m := map[string]interface{}{"value": []string{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").StrSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustStrSlice()[0]) - assert.Equal(t, []string(nil), New(m).Get("nothing").StrSlice()) - assert.Equal(t, val, New(m).Get("nothing").StrSlice([]string{string("hello")})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustStrSlice() - }) - -} - -func TestIsStr(t *testing.T) { - - var v *Value - - v = &Value{data: string("hello")} - assert.True(t, v.IsStr()) - - v = &Value{data: []string{string("hello")}} - assert.True(t, v.IsStrSlice()) - -} - -func TestEachStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - count := 0 - replacedVals := make([]string, 0) - assert.Equal(t, v, v.EachStr(func(i int, val string) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustStrSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustStrSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustStrSlice()[2]) - -} - -func TestWhereStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - selected := v.WhereStr(func(i int, val string) bool { - return i%2 == 0 - }).MustStrSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - grouped := v.GroupStr(func(i int, val string) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]string) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - rawArr := v.MustStrSlice() - - replaced := v.ReplaceStr(func(index int, val string) string { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustStrSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectStr(t *testing.T) { - - v := &Value{data: []string{string("hello"), string("hello"), string("hello"), string("hello"), string("hello"), string("hello")}} - - collected := v.CollectStr(func(index int, val string) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt(t *testing.T) { - - val := int(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int()) - assert.Equal(t, val, New(m).Get("value").MustInt()) - assert.Equal(t, int(0), New(m).Get("nothing").Int()) - assert.Equal(t, val, New(m).Get("nothing").Int(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt() - }) - -} - -func TestIntSlice(t *testing.T) { - - val := int(1) - m := map[string]interface{}{"value": []int{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").IntSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustIntSlice()[0]) - assert.Equal(t, []int(nil), New(m).Get("nothing").IntSlice()) - assert.Equal(t, val, New(m).Get("nothing").IntSlice([]int{int(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustIntSlice() - }) - -} - -func TestIsInt(t *testing.T) { - - var v *Value - - v = &Value{data: int(1)} - assert.True(t, v.IsInt()) - - v = &Value{data: []int{int(1)}} - assert.True(t, v.IsIntSlice()) - -} - -func TestEachInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1)}} - count := 0 - replacedVals := make([]int, 0) - assert.Equal(t, v, v.EachInt(func(i int, val int) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustIntSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustIntSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustIntSlice()[2]) - -} - -func TestWhereInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - selected := v.WhereInt(func(i int, val int) bool { - return i%2 == 0 - }).MustIntSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - grouped := v.GroupInt(func(i int, val int) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - rawArr := v.MustIntSlice() - - replaced := v.ReplaceInt(func(index int, val int) int { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustIntSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt(t *testing.T) { - - v := &Value{data: []int{int(1), int(1), int(1), int(1), int(1), int(1)}} - - collected := v.CollectInt(func(index int, val int) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt8(t *testing.T) { - - val := int8(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int8()) - assert.Equal(t, val, New(m).Get("value").MustInt8()) - assert.Equal(t, int8(0), New(m).Get("nothing").Int8()) - assert.Equal(t, val, New(m).Get("nothing").Int8(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt8() - }) - -} - -func TestInt8Slice(t *testing.T) { - - val := int8(1) - m := map[string]interface{}{"value": []int8{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int8Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt8Slice()[0]) - assert.Equal(t, []int8(nil), New(m).Get("nothing").Int8Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int8Slice([]int8{int8(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt8Slice() - }) - -} - -func TestIsInt8(t *testing.T) { - - var v *Value - - v = &Value{data: int8(1)} - assert.True(t, v.IsInt8()) - - v = &Value{data: []int8{int8(1)}} - assert.True(t, v.IsInt8Slice()) - -} - -func TestEachInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1)}} - count := 0 - replacedVals := make([]int8, 0) - assert.Equal(t, v, v.EachInt8(func(i int, val int8) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt8Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt8Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt8Slice()[2]) - -} - -func TestWhereInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - selected := v.WhereInt8(func(i int, val int8) bool { - return i%2 == 0 - }).MustInt8Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - grouped := v.GroupInt8(func(i int, val int8) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int8) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - rawArr := v.MustInt8Slice() - - replaced := v.ReplaceInt8(func(index int, val int8) int8 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt8Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt8(t *testing.T) { - - v := &Value{data: []int8{int8(1), int8(1), int8(1), int8(1), int8(1), int8(1)}} - - collected := v.CollectInt8(func(index int, val int8) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt16(t *testing.T) { - - val := int16(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int16()) - assert.Equal(t, val, New(m).Get("value").MustInt16()) - assert.Equal(t, int16(0), New(m).Get("nothing").Int16()) - assert.Equal(t, val, New(m).Get("nothing").Int16(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt16() - }) - -} - -func TestInt16Slice(t *testing.T) { - - val := int16(1) - m := map[string]interface{}{"value": []int16{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int16Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt16Slice()[0]) - assert.Equal(t, []int16(nil), New(m).Get("nothing").Int16Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int16Slice([]int16{int16(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt16Slice() - }) - -} - -func TestIsInt16(t *testing.T) { - - var v *Value - - v = &Value{data: int16(1)} - assert.True(t, v.IsInt16()) - - v = &Value{data: []int16{int16(1)}} - assert.True(t, v.IsInt16Slice()) - -} - -func TestEachInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1)}} - count := 0 - replacedVals := make([]int16, 0) - assert.Equal(t, v, v.EachInt16(func(i int, val int16) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt16Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt16Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt16Slice()[2]) - -} - -func TestWhereInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - selected := v.WhereInt16(func(i int, val int16) bool { - return i%2 == 0 - }).MustInt16Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - grouped := v.GroupInt16(func(i int, val int16) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int16) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - rawArr := v.MustInt16Slice() - - replaced := v.ReplaceInt16(func(index int, val int16) int16 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt16Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt16(t *testing.T) { - - v := &Value{data: []int16{int16(1), int16(1), int16(1), int16(1), int16(1), int16(1)}} - - collected := v.CollectInt16(func(index int, val int16) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt32(t *testing.T) { - - val := int32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int32()) - assert.Equal(t, val, New(m).Get("value").MustInt32()) - assert.Equal(t, int32(0), New(m).Get("nothing").Int32()) - assert.Equal(t, val, New(m).Get("nothing").Int32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt32() - }) - -} - -func TestInt32Slice(t *testing.T) { - - val := int32(1) - m := map[string]interface{}{"value": []int32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt32Slice()[0]) - assert.Equal(t, []int32(nil), New(m).Get("nothing").Int32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int32Slice([]int32{int32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt32Slice() - }) - -} - -func TestIsInt32(t *testing.T) { - - var v *Value - - v = &Value{data: int32(1)} - assert.True(t, v.IsInt32()) - - v = &Value{data: []int32{int32(1)}} - assert.True(t, v.IsInt32Slice()) - -} - -func TestEachInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1)}} - count := 0 - replacedVals := make([]int32, 0) - assert.Equal(t, v, v.EachInt32(func(i int, val int32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt32Slice()[2]) - -} - -func TestWhereInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - selected := v.WhereInt32(func(i int, val int32) bool { - return i%2 == 0 - }).MustInt32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - grouped := v.GroupInt32(func(i int, val int32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - rawArr := v.MustInt32Slice() - - replaced := v.ReplaceInt32(func(index int, val int32) int32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt32(t *testing.T) { - - v := &Value{data: []int32{int32(1), int32(1), int32(1), int32(1), int32(1), int32(1)}} - - collected := v.CollectInt32(func(index int, val int32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestInt64(t *testing.T) { - - val := int64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int64()) - assert.Equal(t, val, New(m).Get("value").MustInt64()) - assert.Equal(t, int64(0), New(m).Get("nothing").Int64()) - assert.Equal(t, val, New(m).Get("nothing").Int64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustInt64() - }) - -} - -func TestInt64Slice(t *testing.T) { - - val := int64(1) - m := map[string]interface{}{"value": []int64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Int64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustInt64Slice()[0]) - assert.Equal(t, []int64(nil), New(m).Get("nothing").Int64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Int64Slice([]int64{int64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustInt64Slice() - }) - -} - -func TestIsInt64(t *testing.T) { - - var v *Value - - v = &Value{data: int64(1)} - assert.True(t, v.IsInt64()) - - v = &Value{data: []int64{int64(1)}} - assert.True(t, v.IsInt64Slice()) - -} - -func TestEachInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1)}} - count := 0 - replacedVals := make([]int64, 0) - assert.Equal(t, v, v.EachInt64(func(i int, val int64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustInt64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustInt64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustInt64Slice()[2]) - -} - -func TestWhereInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - selected := v.WhereInt64(func(i int, val int64) bool { - return i%2 == 0 - }).MustInt64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - grouped := v.GroupInt64(func(i int, val int64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]int64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - rawArr := v.MustInt64Slice() - - replaced := v.ReplaceInt64(func(index int, val int64) int64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustInt64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectInt64(t *testing.T) { - - v := &Value{data: []int64{int64(1), int64(1), int64(1), int64(1), int64(1), int64(1)}} - - collected := v.CollectInt64(func(index int, val int64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint(t *testing.T) { - - val := uint(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint()) - assert.Equal(t, val, New(m).Get("value").MustUint()) - assert.Equal(t, uint(0), New(m).Get("nothing").Uint()) - assert.Equal(t, val, New(m).Get("nothing").Uint(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint() - }) - -} - -func TestUintSlice(t *testing.T) { - - val := uint(1) - m := map[string]interface{}{"value": []uint{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").UintSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUintSlice()[0]) - assert.Equal(t, []uint(nil), New(m).Get("nothing").UintSlice()) - assert.Equal(t, val, New(m).Get("nothing").UintSlice([]uint{uint(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUintSlice() - }) - -} - -func TestIsUint(t *testing.T) { - - var v *Value - - v = &Value{data: uint(1)} - assert.True(t, v.IsUint()) - - v = &Value{data: []uint{uint(1)}} - assert.True(t, v.IsUintSlice()) - -} - -func TestEachUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1)}} - count := 0 - replacedVals := make([]uint, 0) - assert.Equal(t, v, v.EachUint(func(i int, val uint) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUintSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustUintSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustUintSlice()[2]) - -} - -func TestWhereUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - selected := v.WhereUint(func(i int, val uint) bool { - return i%2 == 0 - }).MustUintSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - grouped := v.GroupUint(func(i int, val uint) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - rawArr := v.MustUintSlice() - - replaced := v.ReplaceUint(func(index int, val uint) uint { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUintSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint(t *testing.T) { - - v := &Value{data: []uint{uint(1), uint(1), uint(1), uint(1), uint(1), uint(1)}} - - collected := v.CollectUint(func(index int, val uint) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint8(t *testing.T) { - - val := uint8(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint8()) - assert.Equal(t, val, New(m).Get("value").MustUint8()) - assert.Equal(t, uint8(0), New(m).Get("nothing").Uint8()) - assert.Equal(t, val, New(m).Get("nothing").Uint8(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint8() - }) - -} - -func TestUint8Slice(t *testing.T) { - - val := uint8(1) - m := map[string]interface{}{"value": []uint8{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint8Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint8Slice()[0]) - assert.Equal(t, []uint8(nil), New(m).Get("nothing").Uint8Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint8Slice([]uint8{uint8(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint8Slice() - }) - -} - -func TestIsUint8(t *testing.T) { - - var v *Value - - v = &Value{data: uint8(1)} - assert.True(t, v.IsUint8()) - - v = &Value{data: []uint8{uint8(1)}} - assert.True(t, v.IsUint8Slice()) - -} - -func TestEachUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - count := 0 - replacedVals := make([]uint8, 0) - assert.Equal(t, v, v.EachUint8(func(i int, val uint8) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint8Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint8Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint8Slice()[2]) - -} - -func TestWhereUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - selected := v.WhereUint8(func(i int, val uint8) bool { - return i%2 == 0 - }).MustUint8Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - grouped := v.GroupUint8(func(i int, val uint8) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint8) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - rawArr := v.MustUint8Slice() - - replaced := v.ReplaceUint8(func(index int, val uint8) uint8 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint8Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint8(t *testing.T) { - - v := &Value{data: []uint8{uint8(1), uint8(1), uint8(1), uint8(1), uint8(1), uint8(1)}} - - collected := v.CollectUint8(func(index int, val uint8) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint16(t *testing.T) { - - val := uint16(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint16()) - assert.Equal(t, val, New(m).Get("value").MustUint16()) - assert.Equal(t, uint16(0), New(m).Get("nothing").Uint16()) - assert.Equal(t, val, New(m).Get("nothing").Uint16(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint16() - }) - -} - -func TestUint16Slice(t *testing.T) { - - val := uint16(1) - m := map[string]interface{}{"value": []uint16{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint16Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint16Slice()[0]) - assert.Equal(t, []uint16(nil), New(m).Get("nothing").Uint16Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint16Slice([]uint16{uint16(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint16Slice() - }) - -} - -func TestIsUint16(t *testing.T) { - - var v *Value - - v = &Value{data: uint16(1)} - assert.True(t, v.IsUint16()) - - v = &Value{data: []uint16{uint16(1)}} - assert.True(t, v.IsUint16Slice()) - -} - -func TestEachUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - count := 0 - replacedVals := make([]uint16, 0) - assert.Equal(t, v, v.EachUint16(func(i int, val uint16) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint16Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint16Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint16Slice()[2]) - -} - -func TestWhereUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - selected := v.WhereUint16(func(i int, val uint16) bool { - return i%2 == 0 - }).MustUint16Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - grouped := v.GroupUint16(func(i int, val uint16) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint16) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - rawArr := v.MustUint16Slice() - - replaced := v.ReplaceUint16(func(index int, val uint16) uint16 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint16Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint16(t *testing.T) { - - v := &Value{data: []uint16{uint16(1), uint16(1), uint16(1), uint16(1), uint16(1), uint16(1)}} - - collected := v.CollectUint16(func(index int, val uint16) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint32(t *testing.T) { - - val := uint32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint32()) - assert.Equal(t, val, New(m).Get("value").MustUint32()) - assert.Equal(t, uint32(0), New(m).Get("nothing").Uint32()) - assert.Equal(t, val, New(m).Get("nothing").Uint32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint32() - }) - -} - -func TestUint32Slice(t *testing.T) { - - val := uint32(1) - m := map[string]interface{}{"value": []uint32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint32Slice()[0]) - assert.Equal(t, []uint32(nil), New(m).Get("nothing").Uint32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint32Slice([]uint32{uint32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint32Slice() - }) - -} - -func TestIsUint32(t *testing.T) { - - var v *Value - - v = &Value{data: uint32(1)} - assert.True(t, v.IsUint32()) - - v = &Value{data: []uint32{uint32(1)}} - assert.True(t, v.IsUint32Slice()) - -} - -func TestEachUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - count := 0 - replacedVals := make([]uint32, 0) - assert.Equal(t, v, v.EachUint32(func(i int, val uint32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint32Slice()[2]) - -} - -func TestWhereUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - selected := v.WhereUint32(func(i int, val uint32) bool { - return i%2 == 0 - }).MustUint32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - grouped := v.GroupUint32(func(i int, val uint32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - rawArr := v.MustUint32Slice() - - replaced := v.ReplaceUint32(func(index int, val uint32) uint32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint32(t *testing.T) { - - v := &Value{data: []uint32{uint32(1), uint32(1), uint32(1), uint32(1), uint32(1), uint32(1)}} - - collected := v.CollectUint32(func(index int, val uint32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUint64(t *testing.T) { - - val := uint64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint64()) - assert.Equal(t, val, New(m).Get("value").MustUint64()) - assert.Equal(t, uint64(0), New(m).Get("nothing").Uint64()) - assert.Equal(t, val, New(m).Get("nothing").Uint64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUint64() - }) - -} - -func TestUint64Slice(t *testing.T) { - - val := uint64(1) - m := map[string]interface{}{"value": []uint64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uint64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUint64Slice()[0]) - assert.Equal(t, []uint64(nil), New(m).Get("nothing").Uint64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Uint64Slice([]uint64{uint64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUint64Slice() - }) - -} - -func TestIsUint64(t *testing.T) { - - var v *Value - - v = &Value{data: uint64(1)} - assert.True(t, v.IsUint64()) - - v = &Value{data: []uint64{uint64(1)}} - assert.True(t, v.IsUint64Slice()) - -} - -func TestEachUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - count := 0 - replacedVals := make([]uint64, 0) - assert.Equal(t, v, v.EachUint64(func(i int, val uint64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUint64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustUint64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustUint64Slice()[2]) - -} - -func TestWhereUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - selected := v.WhereUint64(func(i int, val uint64) bool { - return i%2 == 0 - }).MustUint64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - grouped := v.GroupUint64(func(i int, val uint64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uint64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - rawArr := v.MustUint64Slice() - - replaced := v.ReplaceUint64(func(index int, val uint64) uint64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUint64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUint64(t *testing.T) { - - v := &Value{data: []uint64{uint64(1), uint64(1), uint64(1), uint64(1), uint64(1), uint64(1)}} - - collected := v.CollectUint64(func(index int, val uint64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestUintptr(t *testing.T) { - - val := uintptr(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Uintptr()) - assert.Equal(t, val, New(m).Get("value").MustUintptr()) - assert.Equal(t, uintptr(0), New(m).Get("nothing").Uintptr()) - assert.Equal(t, val, New(m).Get("nothing").Uintptr(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustUintptr() - }) - -} - -func TestUintptrSlice(t *testing.T) { - - val := uintptr(1) - m := map[string]interface{}{"value": []uintptr{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").UintptrSlice()[0]) - assert.Equal(t, val, New(m).Get("value").MustUintptrSlice()[0]) - assert.Equal(t, []uintptr(nil), New(m).Get("nothing").UintptrSlice()) - assert.Equal(t, val, New(m).Get("nothing").UintptrSlice([]uintptr{uintptr(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustUintptrSlice() - }) - -} - -func TestIsUintptr(t *testing.T) { - - var v *Value - - v = &Value{data: uintptr(1)} - assert.True(t, v.IsUintptr()) - - v = &Value{data: []uintptr{uintptr(1)}} - assert.True(t, v.IsUintptrSlice()) - -} - -func TestEachUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - count := 0 - replacedVals := make([]uintptr, 0) - assert.Equal(t, v, v.EachUintptr(func(i int, val uintptr) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustUintptrSlice()[0]) - assert.Equal(t, replacedVals[1], v.MustUintptrSlice()[1]) - assert.Equal(t, replacedVals[2], v.MustUintptrSlice()[2]) - -} - -func TestWhereUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - selected := v.WhereUintptr(func(i int, val uintptr) bool { - return i%2 == 0 - }).MustUintptrSlice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - grouped := v.GroupUintptr(func(i int, val uintptr) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]uintptr) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - rawArr := v.MustUintptrSlice() - - replaced := v.ReplaceUintptr(func(index int, val uintptr) uintptr { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustUintptrSlice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectUintptr(t *testing.T) { - - v := &Value{data: []uintptr{uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1), uintptr(1)}} - - collected := v.CollectUintptr(func(index int, val uintptr) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestFloat32(t *testing.T) { - - val := float32(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float32()) - assert.Equal(t, val, New(m).Get("value").MustFloat32()) - assert.Equal(t, float32(0), New(m).Get("nothing").Float32()) - assert.Equal(t, val, New(m).Get("nothing").Float32(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustFloat32() - }) - -} - -func TestFloat32Slice(t *testing.T) { - - val := float32(1) - m := map[string]interface{}{"value": []float32{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float32Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustFloat32Slice()[0]) - assert.Equal(t, []float32(nil), New(m).Get("nothing").Float32Slice()) - assert.Equal(t, val, New(m).Get("nothing").Float32Slice([]float32{float32(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustFloat32Slice() - }) - -} - -func TestIsFloat32(t *testing.T) { - - var v *Value - - v = &Value{data: float32(1)} - assert.True(t, v.IsFloat32()) - - v = &Value{data: []float32{float32(1)}} - assert.True(t, v.IsFloat32Slice()) - -} - -func TestEachFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1)}} - count := 0 - replacedVals := make([]float32, 0) - assert.Equal(t, v, v.EachFloat32(func(i int, val float32) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustFloat32Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustFloat32Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustFloat32Slice()[2]) - -} - -func TestWhereFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - selected := v.WhereFloat32(func(i int, val float32) bool { - return i%2 == 0 - }).MustFloat32Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - grouped := v.GroupFloat32(func(i int, val float32) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]float32) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - rawArr := v.MustFloat32Slice() - - replaced := v.ReplaceFloat32(func(index int, val float32) float32 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustFloat32Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectFloat32(t *testing.T) { - - v := &Value{data: []float32{float32(1), float32(1), float32(1), float32(1), float32(1), float32(1)}} - - collected := v.CollectFloat32(func(index int, val float32) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestFloat64(t *testing.T) { - - val := float64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float64()) - assert.Equal(t, val, New(m).Get("value").MustFloat64()) - assert.Equal(t, float64(0), New(m).Get("nothing").Float64()) - assert.Equal(t, val, New(m).Get("nothing").Float64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustFloat64() - }) - -} - -func TestFloat64Slice(t *testing.T) { - - val := float64(1) - m := map[string]interface{}{"value": []float64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Float64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustFloat64Slice()[0]) - assert.Equal(t, []float64(nil), New(m).Get("nothing").Float64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Float64Slice([]float64{float64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustFloat64Slice() - }) - -} - -func TestIsFloat64(t *testing.T) { - - var v *Value - - v = &Value{data: float64(1)} - assert.True(t, v.IsFloat64()) - - v = &Value{data: []float64{float64(1)}} - assert.True(t, v.IsFloat64Slice()) - -} - -func TestEachFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1)}} - count := 0 - replacedVals := make([]float64, 0) - assert.Equal(t, v, v.EachFloat64(func(i int, val float64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustFloat64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustFloat64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustFloat64Slice()[2]) - -} - -func TestWhereFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - selected := v.WhereFloat64(func(i int, val float64) bool { - return i%2 == 0 - }).MustFloat64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - grouped := v.GroupFloat64(func(i int, val float64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]float64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - rawArr := v.MustFloat64Slice() - - replaced := v.ReplaceFloat64(func(index int, val float64) float64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustFloat64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectFloat64(t *testing.T) { - - v := &Value{data: []float64{float64(1), float64(1), float64(1), float64(1), float64(1), float64(1)}} - - collected := v.CollectFloat64(func(index int, val float64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestComplex64(t *testing.T) { - - val := complex64(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex64()) - assert.Equal(t, val, New(m).Get("value").MustComplex64()) - assert.Equal(t, complex64(0), New(m).Get("nothing").Complex64()) - assert.Equal(t, val, New(m).Get("nothing").Complex64(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustComplex64() - }) - -} - -func TestComplex64Slice(t *testing.T) { - - val := complex64(1) - m := map[string]interface{}{"value": []complex64{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex64Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustComplex64Slice()[0]) - assert.Equal(t, []complex64(nil), New(m).Get("nothing").Complex64Slice()) - assert.Equal(t, val, New(m).Get("nothing").Complex64Slice([]complex64{complex64(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustComplex64Slice() - }) - -} - -func TestIsComplex64(t *testing.T) { - - var v *Value - - v = &Value{data: complex64(1)} - assert.True(t, v.IsComplex64()) - - v = &Value{data: []complex64{complex64(1)}} - assert.True(t, v.IsComplex64Slice()) - -} - -func TestEachComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - count := 0 - replacedVals := make([]complex64, 0) - assert.Equal(t, v, v.EachComplex64(func(i int, val complex64) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustComplex64Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustComplex64Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustComplex64Slice()[2]) - -} - -func TestWhereComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - selected := v.WhereComplex64(func(i int, val complex64) bool { - return i%2 == 0 - }).MustComplex64Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - grouped := v.GroupComplex64(func(i int, val complex64) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]complex64) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - rawArr := v.MustComplex64Slice() - - replaced := v.ReplaceComplex64(func(index int, val complex64) complex64 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustComplex64Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectComplex64(t *testing.T) { - - v := &Value{data: []complex64{complex64(1), complex64(1), complex64(1), complex64(1), complex64(1), complex64(1)}} - - collected := v.CollectComplex64(func(index int, val complex64) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} - -// ************************************************************ -// TESTS -// ************************************************************ - -func TestComplex128(t *testing.T) { - - val := complex128(1) - m := map[string]interface{}{"value": val, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex128()) - assert.Equal(t, val, New(m).Get("value").MustComplex128()) - assert.Equal(t, complex128(0), New(m).Get("nothing").Complex128()) - assert.Equal(t, val, New(m).Get("nothing").Complex128(1)) - - assert.Panics(t, func() { - New(m).Get("age").MustComplex128() - }) - -} - -func TestComplex128Slice(t *testing.T) { - - val := complex128(1) - m := map[string]interface{}{"value": []complex128{val}, "nothing": nil} - assert.Equal(t, val, New(m).Get("value").Complex128Slice()[0]) - assert.Equal(t, val, New(m).Get("value").MustComplex128Slice()[0]) - assert.Equal(t, []complex128(nil), New(m).Get("nothing").Complex128Slice()) - assert.Equal(t, val, New(m).Get("nothing").Complex128Slice([]complex128{complex128(1)})[0]) - - assert.Panics(t, func() { - New(m).Get("nothing").MustComplex128Slice() - }) - -} - -func TestIsComplex128(t *testing.T) { - - var v *Value - - v = &Value{data: complex128(1)} - assert.True(t, v.IsComplex128()) - - v = &Value{data: []complex128{complex128(1)}} - assert.True(t, v.IsComplex128Slice()) - -} - -func TestEachComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - count := 0 - replacedVals := make([]complex128, 0) - assert.Equal(t, v, v.EachComplex128(func(i int, val complex128) bool { - - count++ - replacedVals = append(replacedVals, val) - - // abort early - if i == 2 { - return false - } - - return true - - })) - - assert.Equal(t, count, 3) - assert.Equal(t, replacedVals[0], v.MustComplex128Slice()[0]) - assert.Equal(t, replacedVals[1], v.MustComplex128Slice()[1]) - assert.Equal(t, replacedVals[2], v.MustComplex128Slice()[2]) - -} - -func TestWhereComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - selected := v.WhereComplex128(func(i int, val complex128) bool { - return i%2 == 0 - }).MustComplex128Slice() - - assert.Equal(t, 3, len(selected)) - -} - -func TestGroupComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - grouped := v.GroupComplex128(func(i int, val complex128) string { - return fmt.Sprintf("%v", i%2 == 0) - }).data.(map[string][]complex128) - - assert.Equal(t, 2, len(grouped)) - assert.Equal(t, 3, len(grouped["true"])) - assert.Equal(t, 3, len(grouped["false"])) - -} - -func TestReplaceComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - rawArr := v.MustComplex128Slice() - - replaced := v.ReplaceComplex128(func(index int, val complex128) complex128 { - if index < len(rawArr)-1 { - return rawArr[index+1] - } - return rawArr[0] - }) - - replacedArr := replaced.MustComplex128Slice() - if assert.Equal(t, 6, len(replacedArr)) { - assert.Equal(t, replacedArr[0], rawArr[1]) - assert.Equal(t, replacedArr[1], rawArr[2]) - assert.Equal(t, replacedArr[2], rawArr[3]) - assert.Equal(t, replacedArr[3], rawArr[4]) - assert.Equal(t, replacedArr[4], rawArr[5]) - assert.Equal(t, replacedArr[5], rawArr[0]) - } - -} - -func TestCollectComplex128(t *testing.T) { - - v := &Value{data: []complex128{complex128(1), complex128(1), complex128(1), complex128(1), complex128(1), complex128(1)}} - - collected := v.CollectComplex128(func(index int, val complex128) interface{} { - return index - }) - - collectedArr := collected.MustInterSlice() - if assert.Equal(t, 6, len(collectedArr)) { - assert.Equal(t, collectedArr[0], 0) - assert.Equal(t, collectedArr[1], 1) - assert.Equal(t, collectedArr[2], 2) - assert.Equal(t, collectedArr[3], 3) - assert.Equal(t, collectedArr[4], 4) - assert.Equal(t, collectedArr[5], 5) - } - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go b/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go deleted file mode 100644 index 0bc65d92c1b..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go +++ /dev/null @@ -1 +0,0 @@ -package objx diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go deleted file mode 100644 index 36c671eefef..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/assertions_test.go +++ /dev/null @@ -1,813 +0,0 @@ -package assert - -import ( - "errors" - "io" - "math" - "regexp" - "testing" - "time" -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -func TestObjectsAreEqual(t *testing.T) { - - if !ObjectsAreEqual("Hello World", "Hello World") { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123, 123) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(123.5, 123.5) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { - t.Error("objectsAreEqual should return true") - } - if !ObjectsAreEqual(nil, nil) { - t.Error("objectsAreEqual should return true") - } - if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual('x', "x") { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual("x", 'x') { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0, 0.1) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(0.1, 0) { - t.Error("objectsAreEqual should return false") - } - if ObjectsAreEqual(uint32(10), int32(10)) { - t.Error("objectsAreEqual should return false") - } - if !ObjectsAreEqualValues(uint32(10), int32(10)) { - t.Error("ObjectsAreEqualValues should return true") - } - -} - -func TestImplements(t *testing.T) { - - mockT := new(testing.T) - - if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } - -} - -func TestIsType(t *testing.T) { - - mockT := new(testing.T) - - if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqual(t *testing.T) { - - mockT := new(testing.T) - - if !Equal(mockT, "Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !Equal(mockT, 123, 123) { - t.Error("Equal should return true") - } - if !Equal(mockT, 123.5, 123.5) { - t.Error("Equal should return true") - } - if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !Equal(mockT, nil, nil) { - t.Error("Equal should return true") - } - if !Equal(mockT, int32(123), int32(123)) { - t.Error("Equal should return true") - } - if !Equal(mockT, uint64(123), uint64(123)) { - t.Error("Equal should return true") - } - -} - -func TestNotNil(t *testing.T) { - - mockT := new(testing.T) - - if !NotNil(mockT, new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if NotNil(mockT, nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNil(t *testing.T) { - - mockT := new(testing.T) - - if !Nil(mockT, nil) { - t.Error("Nil should return true: object is nil") - } - if Nil(mockT, new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrue(t *testing.T) { - - mockT := new(testing.T) - - if !True(mockT, true) { - t.Error("True should return true") - } - if True(mockT, false) { - t.Error("True should return false") - } - -} - -func TestFalse(t *testing.T) { - - mockT := new(testing.T) - - if !False(mockT, false) { - t.Error("False should return true") - } - if False(mockT, true) { - t.Error("False should return false") - } - -} - -func TestExactly(t *testing.T) { - - mockT := new(testing.T) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if Exactly(mockT, a, b) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, d) { - t.Error("Exactly should return false") - } - if !Exactly(mockT, a, c) { - t.Error("Exactly should return true") - } - - if Exactly(mockT, nil, a) { - t.Error("Exactly should return false") - } - if Exactly(mockT, a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqual(t *testing.T) { - - mockT := new(testing.T) - - if !NotEqual(mockT, "Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123, 1234) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, 123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } - funcA := func() int { return 23 } - funcB := func() int { return 42 } - if !NotEqual(mockT, funcA, funcB) { - t.Error("NotEqual should return true") - } - - if NotEqual(mockT, "Hello World", "Hello World") { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123, 123) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, 123.5, 123.5) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { - t.Error("NotEqual should return false") - } - if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return false") - } -} - -type A struct { - Name, Value string -} - -func TestContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - complexList := []*A{ - {"b", "c"}, - {"d", "e"}, - {"g", "h"}, - {"j", "k"}, - } - - if !Contains(mockT, "Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if Contains(mockT, "Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !Contains(mockT, list, "Bar") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") - } - if Contains(mockT, list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - if !Contains(mockT, complexList, &A{"g", "h"}) { - t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") - } - if Contains(mockT, complexList, &A{"g", "e"}) { - t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") - } -} - -func TestNotContains(t *testing.T) { - - mockT := new(testing.T) - list := []string{"Foo", "Bar"} - - if !NotContains(mockT, "Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if NotContains(mockT, "Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !NotContains(mockT, list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if NotContains(mockT, list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func Test_includeElement(t *testing.T) { - - list1 := []string{"Foo", "Bar"} - list2 := []int{1, 2} - - ok, found := includeElement("Hello World", "World") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo") - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Bar") - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 1) - True(t, ok) - True(t, found) - - ok, found = includeElement(list2, 2) - True(t, ok) - True(t, found) - - ok, found = includeElement(list1, "Foo!") - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, 3) - True(t, ok) - False(t, found) - - ok, found = includeElement(list2, "1") - True(t, ok) - False(t, found) - - ok, found = includeElement(1433, "1") - False(t, ok) - False(t, found) - -} - -func TestCondition(t *testing.T) { - mockT := new(testing.T) - - if !Condition(mockT, func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if Condition(mockT, func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanic(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanics(t *testing.T) { - - mockT := new(testing.T) - - if !Panics(mockT, func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if Panics(mockT, func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanics(t *testing.T) { - - mockT := new(testing.T) - - if !NotPanics(mockT, func() { - }) { - t.Error("NotPanics should return true") - } - - if NotPanics(mockT, func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - True(t, NoError(mockT, err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("some error") - - False(t, NoError(mockT, err), "NoError with error should return False") - -} - -func TestError(t *testing.T) { - - mockT := new(testing.T) - - // start with a nil error - var err error - - False(t, Error(mockT, err), "Error should return False for nil arg") - - // now set an error - err = errors.New("some error") - - True(t, Error(mockT, err), "Error with error should return True") - -} - -func TestEqualError(t *testing.T) { - mockT := new(testing.T) - - // start with a nil error - var err error - False(t, EqualError(mockT, err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - False(t, EqualError(mockT, err, "Not some error"), - "EqualError should return false for different error string") - True(t, EqualError(mockT, err, "some error"), - "EqualError should return true") -} - -func Test_isEmpty(t *testing.T) { - - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, isEmpty("")) - True(t, isEmpty(nil)) - True(t, isEmpty([]string{})) - True(t, isEmpty(0)) - True(t, isEmpty(int32(0))) - True(t, isEmpty(int64(0))) - True(t, isEmpty(false)) - True(t, isEmpty(map[string]string{})) - True(t, isEmpty(new(time.Time))) - True(t, isEmpty(make(chan struct{}))) - False(t, isEmpty("something")) - False(t, isEmpty(errors.New("something"))) - False(t, isEmpty([]string{"something"})) - False(t, isEmpty(1)) - False(t, isEmpty(true)) - False(t, isEmpty(map[string]string{"Hello": "World"})) - False(t, isEmpty(chWithValue)) - -} - -func TestEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - True(t, Empty(mockT, ""), "Empty string is empty") - True(t, Empty(mockT, nil), "Nil is empty") - True(t, Empty(mockT, []string{}), "Empty string array is empty") - True(t, Empty(mockT, 0), "Zero int value is empty") - True(t, Empty(mockT, false), "False value is empty") - True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") - - False(t, Empty(mockT, "something"), "Non Empty string is not empty") - False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") - False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") - False(t, Empty(mockT, 1), "Non-zero int value is not empty") - False(t, Empty(mockT, true), "True value is not empty") - False(t, Empty(mockT, chWithValue), "Channel with values is not empty") -} - -func TestNotEmpty(t *testing.T) { - - mockT := new(testing.T) - chWithValue := make(chan struct{}, 1) - chWithValue <- struct{}{} - - False(t, NotEmpty(mockT, ""), "Empty string is empty") - False(t, NotEmpty(mockT, nil), "Nil is empty") - False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") - False(t, NotEmpty(mockT, 0), "Zero int value is empty") - False(t, NotEmpty(mockT, false), "False value is empty") - False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") - - True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") - True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") - True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") - True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") - True(t, NotEmpty(mockT, true), "True value is not empty") - True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") -} - -func Test_getLen(t *testing.T) { - falseCases := []interface{}{ - nil, - 0, - true, - false, - 'A', - struct{}{}, - } - for _, v := range falseCases { - ok, l := getLen(v) - False(t, ok, "Expected getLen fail to get length of %#v", v) - Equal(t, 0, l, "getLen should return 0 for %#v", v) - } - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - trueCases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range trueCases { - ok, l := getLen(c.v) - True(t, ok, "Expected getLen success to get length of %#v", c.v) - Equal(t, c.l, l) - } -} - -func TestLen(t *testing.T) { - mockT := new(testing.T) - - False(t, Len(mockT, nil, 0), "nil does not have length") - False(t, Len(mockT, 0, 0), "int does not have length") - False(t, Len(mockT, true, 0), "true does not have length") - False(t, Len(mockT, false, 0), "false does not have length") - False(t, Len(mockT, 'A', 0), "Rune does not have length") - False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } - - cases = []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 4}, - {[...]int{1, 2, 3}, 2}, - {"ABC", 2}, - {map[int]int{1: 2, 2: 4, 3: 6}, 4}, - {ch, 2}, - - {[]int{}, 1}, - {map[int]int{}, 1}, - {make(chan int), 1}, - - {[]int(nil), 1}, - {map[int]int(nil), 1}, - {(chan int)(nil), 1}, - } - - for _, c := range cases { - False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDuration(t *testing.T) { - - mockT := new(testing.T) - a := time.Now() - b := a.Add(10 * time.Second) - - True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDelta(t *testing.T) { - mockT := new(testing.T) - - True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") - False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") - False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") - False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInDeltaSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InDeltaSlice(mockT, - []float64{1.001, 0.999}, - []float64{1, 1}, - 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") - - True(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 1), "{1, 2} is element-wise close to {0, 3} in delta=1") - - False(t, InDeltaSlice(mockT, - []float64{1, 2}, - []float64{0, 3}, - 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") - - False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestInEpsilon(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - -} - -func TestInEpsilonSlice(t *testing.T) { - mockT := new(testing.T) - - True(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") - - False(t, InEpsilonSlice(mockT, - []float64{2.2, 2.0}, - []float64{2.1, 2.1}, - 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") - - False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") -} - -func TestRegexp(t *testing.T) { - mockT := new(testing.T) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, Regexp(mockT, tc.rx, tc.str)) - True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - False(t, NotRegexp(mockT, tc.rx, tc.str)) - False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - True(t, NotRegexp(mockT, tc.rx, tc.str)) - True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) - } -} - -func testAutogeneratedFunction() { - defer func() { - if err := recover(); err == nil { - panic("did not panic") - } - CallerInfo() - }() - t := struct { - io.Closer - }{} - var c io.Closer - c = t - c.Close() -} - -func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { - NotPanics(t, func() { - testAutogeneratedFunction() - }) -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go deleted file mode 100644 index 3df3f3917ac..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/forward_assertions_test.go +++ /dev/null @@ -1,511 +0,0 @@ -package assert - -import ( - "errors" - "regexp" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { - t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") - } - if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { - t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") - } -} - -func TestIsTypeWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { - t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") - } - if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { - t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") - } - -} - -func TestEqualWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Equal("Hello World", "Hello World") { - t.Error("Equal should return true") - } - if !assert.Equal(123, 123) { - t.Error("Equal should return true") - } - if !assert.Equal(123.5, 123.5) { - t.Error("Equal should return true") - } - if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { - t.Error("Equal should return true") - } - if !assert.Equal(nil, nil) { - t.Error("Equal should return true") - } -} - -func TestEqualValuesWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.EqualValues(uint32(10), int32(10)) { - t.Error("EqualValues should return true") - } -} - -func TestNotNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.NotNil(new(AssertionTesterConformingObject)) { - t.Error("NotNil should return true: object is not nil") - } - if assert.NotNil(nil) { - t.Error("NotNil should return false: object is nil") - } - -} - -func TestNilWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.Nil(nil) { - t.Error("Nil should return true: object is nil") - } - if assert.Nil(new(AssertionTesterConformingObject)) { - t.Error("Nil should return false: object is not nil") - } - -} - -func TestTrueWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.True(true) { - t.Error("True should return true") - } - if assert.True(false) { - t.Error("True should return false") - } - -} - -func TestFalseWrapper(t *testing.T) { - assert := New(new(testing.T)) - - if !assert.False(false) { - t.Error("False should return true") - } - if assert.False(true) { - t.Error("False should return false") - } - -} - -func TestExactlyWrapper(t *testing.T) { - assert := New(new(testing.T)) - - a := float32(1) - b := float64(1) - c := float32(1) - d := float32(2) - - if assert.Exactly(a, b) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, d) { - t.Error("Exactly should return false") - } - if !assert.Exactly(a, c) { - t.Error("Exactly should return true") - } - - if assert.Exactly(nil, a) { - t.Error("Exactly should return false") - } - if assert.Exactly(a, nil) { - t.Error("Exactly should return false") - } - -} - -func TestNotEqualWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotEqual("Hello World", "Hello World!") { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123, 1234) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(123.5, 123.55) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { - t.Error("NotEqual should return true") - } - if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { - t.Error("NotEqual should return true") - } -} - -func TestContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.Contains("Hello World", "Hello") { - t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") - } - if assert.Contains("Hello World", "Salut") { - t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") - } - - if !assert.Contains(list, "Foo") { - t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - if assert.Contains(list, "Salut") { - t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") - } - -} - -func TestNotContainsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - list := []string{"Foo", "Bar"} - - if !assert.NotContains("Hello World", "Hello!") { - t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") - } - if assert.NotContains("Hello World", "Hello") { - t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") - } - - if !assert.NotContains(list, "Foo!") { - t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") - } - if assert.NotContains(list, "Foo") { - t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") - } - -} - -func TestConditionWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Condition(func() bool { return true }, "Truth") { - t.Error("Condition should return true") - } - - if assert.Condition(func() bool { return false }, "Lie") { - t.Error("Condition should return false") - } - -} - -func TestDidPanicWrapper(t *testing.T) { - - if funcDidPanic, _ := didPanic(func() { - panic("Panic!") - }); !funcDidPanic { - t.Error("didPanic should return true") - } - - if funcDidPanic, _ := didPanic(func() { - }); funcDidPanic { - t.Error("didPanic should return false") - } - -} - -func TestPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.Panics(func() { - panic("Panic!") - }) { - t.Error("Panics should return true") - } - - if assert.Panics(func() { - }) { - t.Error("Panics should return false") - } - -} - -func TestNotPanicsWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - if !assert.NotPanics(func() { - }) { - t.Error("NotPanics should return true") - } - - if assert.NotPanics(func() { - panic("Panic!") - }) { - t.Error("NotPanics should return false") - } - -} - -func TestNoErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.False(mockAssert.NoError(err), "NoError with error should return False") - -} - -func TestErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - - assert.False(mockAssert.Error(err), "Error should return False for nil arg") - - // now set an error - err = errors.New("Some error") - - assert.True(mockAssert.Error(err), "Error with error should return True") - -} - -func TestEqualErrorWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - // start with a nil error - var err error - assert.False(mockAssert.EqualError(err, ""), - "EqualError should return false for nil arg") - - // now set an error - err = errors.New("some error") - assert.False(mockAssert.EqualError(err, "Not some error"), - "EqualError should return false for different error string") - assert.True(mockAssert.EqualError(err, "some error"), - "EqualError should return true") -} - -func TestEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.Empty(""), "Empty string is empty") - assert.True(mockAssert.Empty(nil), "Nil is empty") - assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") - assert.True(mockAssert.Empty(0), "Zero int value is empty") - assert.True(mockAssert.Empty(false), "False value is empty") - - assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") - assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") - assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") - assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") - assert.False(mockAssert.Empty(true), "True value is not empty") - -} - -func TestNotEmptyWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.NotEmpty(""), "Empty string is empty") - assert.False(mockAssert.NotEmpty(nil), "Nil is empty") - assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") - assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") - assert.False(mockAssert.NotEmpty(false), "False value is empty") - - assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") - assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") - assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") - assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") - assert.True(mockAssert.NotEmpty(true), "True value is not empty") - -} - -func TestLenWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.False(mockAssert.Len(nil, 0), "nil does not have length") - assert.False(mockAssert.Len(0, 0), "int does not have length") - assert.False(mockAssert.Len(true, 0), "true does not have length") - assert.False(mockAssert.Len(false, 0), "false does not have length") - assert.False(mockAssert.Len('A', 0), "Rune does not have length") - assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") - - ch := make(chan int, 5) - ch <- 1 - ch <- 2 - ch <- 3 - - cases := []struct { - v interface{} - l int - }{ - {[]int{1, 2, 3}, 3}, - {[...]int{1, 2, 3}, 3}, - {"ABC", 3}, - {map[int]int{1: 2, 2: 4, 3: 6}, 3}, - {ch, 3}, - - {[]int{}, 0}, - {map[int]int{}, 0}, - {make(chan int), 0}, - - {[]int(nil), 0}, - {map[int]int(nil), 0}, - {(chan int)(nil), 0}, - } - - for _, c := range cases { - assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) - } -} - -func TestWithinDurationWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - a := time.Now() - b := a.Add(10 * time.Second) - - assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") - assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") - - assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") - - assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") - assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") -} - -func TestInDeltaWrapper(t *testing.T) { - assert := New(new(testing.T)) - - True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") - True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") - True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") - False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") - False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") - False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") - - cases := []struct { - a, b interface{} - delta float64 - }{ - {uint8(2), uint8(1), 1}, - {uint16(2), uint16(1), 1}, - {uint32(2), uint32(1), 1}, - {uint64(2), uint64(1), 1}, - - {int(2), int(1), 1}, - {int8(2), int8(1), 1}, - {int16(2), int16(1), 1}, - {int32(2), int32(1), 1}, - {int64(2), int64(1), 1}, - - {float32(2), float32(1), 1}, - {float64(2), float64(1), 1}, - } - - for _, tc := range cases { - True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) - } -} - -func TestInEpsilonWrapper(t *testing.T) { - assert := New(new(testing.T)) - - cases := []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), uint16(2), .001}, - {2.1, 2.2, 0.1}, - {2.2, 2.1, 0.1}, - {-2.1, -2.2, 0.1}, - {-2.2, -2.1, 0.1}, - {uint64(100), uint8(101), 0.01}, - {0.1, -0.1, 2}, - } - - for _, tc := range cases { - True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } - - cases = []struct { - a, b interface{} - epsilon float64 - }{ - {uint8(2), int16(-2), .001}, - {uint64(100), uint8(102), 0.01}, - {2.1, 2.2, 0.001}, - {2.2, 2.1, 0.001}, - {2.1, -2.2, 1}, - {2.1, "bla-bla", 0}, - {0.1, -0.1, 1.99}, - } - - for _, tc := range cases { - False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) - } -} - -func TestRegexpWrapper(t *testing.T) { - - assert := New(new(testing.T)) - - cases := []struct { - rx, str string - }{ - {"^start", "start of the line"}, - {"end$", "in the end"}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, - } - - for _, tc := range cases { - True(t, assert.Regexp(tc.rx, tc.str)) - True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - False(t, assert.NotRegexp(tc.rx, tc.str)) - False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } - - cases = []struct { - rx, str string - }{ - {"^asdfastart", "Not the start of the line"}, - {"end$", "in the end."}, - {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, - } - - for _, tc := range cases { - False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) - False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) - True(t, assert.NotRegexp(tc.rx, tc.str)) - True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go deleted file mode 100644 index 684c2d5d1c5..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/url" - "testing" -) - -func httpOK(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) -} - -func httpRedirect(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTemporaryRedirect) -} - -func httpError(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusInternalServerError) -} - -func TestHTTPStatuses(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) - assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) - assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) - - assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) - assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) -} - -func TestHTTPStatusesWrapper(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) - assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) - - assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) - assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) -} - -func httpHelloName(w http.ResponseWriter, r *http.Request) { - name := r.FormValue("name") - w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) -} - -func TestHttpBody(t *testing.T) { - assert := New(t) - mockT := new(testing.T) - - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) -} - -func TestHttpBodyWrappers(t *testing.T) { - assert := New(t) - mockAssert := New(new(testing.T)) - - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) - assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) - assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go deleted file mode 100644 index b1ee9545165..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/mock/mock_test.go +++ /dev/null @@ -1,908 +0,0 @@ -package mock - -import ( - "errors" - "github.com/stretchr/testify/assert" - "testing" - "time" -) - -/* - Test objects -*/ - -// ExampleInterface represents an example interface. -type ExampleInterface interface { - TheExampleMethod(a, b, c int) (int, error) -} - -// TestExampleImplementation is a test implementation of ExampleInterface -type TestExampleImplementation struct { - Mock -} - -func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { - args := i.Called(a, b, c) - return args.Int(0), errors.New("Whoops") -} - -func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { - i.Called(yesorno) -} - -type ExampleType struct { - ran bool -} - -func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { - args := i.Called(et) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { - args := i.Called(fn) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { - args := i.Called(a) - return args.Error(0) -} - -func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { - args := i.Called(a) - return args.Error(0) -} - -type ExampleFuncType func(string) error - -func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { - args := i.Called(fn) - return args.Error(0) -} - -/* - Mock -*/ - -func Test_Mock_TestData(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - if assert.NotNil(t, mockedService.TestData()) { - - mockedService.TestData().Set("something", 123) - assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) - - } - -} - -func Test_Mock_On(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod"), &mockedService.Mock) - assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) - -} - -func Test_Mock_On_WithArgs(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", 1, 2, 3), &mockedService.Mock) - assert.Equal(t, "TheExampleMethod", mockedService.onMethodName) - assert.Equal(t, 1, mockedService.onMethodArguments[0]) - assert.Equal(t, 2, mockedService.onMethodArguments[1]) - assert.Equal(t, 3, mockedService.onMethodArguments[2]) - -} - -func Test_Mock_On_WithFuncArg(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethodFunc", AnythingOfType("func(string) error")).Return(nil), &mockedService.Mock) - assert.Equal(t, "TheExampleMethodFunc", mockedService.onMethodName) - assert.Equal(t, AnythingOfType("func(string) error"), mockedService.onMethodArguments[0]) - - fn := func(string) error { return nil } - mockedService.TheExampleMethodFunc(fn) - -} - -func Test_Mock_On_WithVariadicFunc(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethodVariadic", []int{1, 2, 3}).Return(nil), &mockedService.Mock) - assert.Equal(t, "TheExampleMethodVariadic", mockedService.onMethodName) - assert.Equal(t, []int{1, 2, 3}, mockedService.onMethodArguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadic(1, 2, 3) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadic(1, 2) - }) - -} - -func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}).Return(nil), &mockedService.Mock) - assert.Equal(t, "TheExampleMethodVariadicInterface", mockedService.onMethodName) - assert.Equal(t, []interface{}{1, 2, 3}, mockedService.onMethodArguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2, 3) - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2) - }) - -} - -func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - var expected []interface{} - assert.Equal(t, mockedService.On("TheExampleMethodVariadicInterface", expected).Return(nil), &mockedService.Mock) - assert.Equal(t, "TheExampleMethodVariadicInterface", mockedService.onMethodName) - assert.Equal(t, expected, mockedService.onMethodArguments[0]) - - assert.NotPanics(t, func() { - mockedService.TheExampleMethodVariadicInterface() - }) - assert.Panics(t, func() { - mockedService.TheExampleMethodVariadicInterface(1, 2) - }) - -} - -func Test_Mock_On_WithFuncPanics(t *testing.T) { - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Panics(t, func() { - mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) - }) -} - -func Test_Mock_On_WithFuncTypeArg(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).Return(nil), &mockedService.Mock) - assert.Equal(t, "TheExampleMethodFuncType", mockedService.onMethodName) - assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), mockedService.onMethodArguments[0]) - - fn := func(string) error { return nil } - mockedService.TheExampleMethodFuncType(fn) - -} - -func Test_Mock_Return(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.Nil(t, call.WaitFor) - - } - -} - -func Test_Mock_Return_WaitUntil(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - ch := time.After(time.Second) - - assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).WaitUntil(ch), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) { - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.Equal(t, ch, call.WaitFor) - - } - -} - -func Test_Mock_Return_After(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.Mock.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).After(time.Second), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) { - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 0, call.Repeatability) - assert.NotEqual(t, nil, call.WaitFor) - - } - -} - -func Test_Mock_Return_Run(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.Mock.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Run(func(args Arguments) { - arg := args.Get(0).(*ExampleType) - arg.ran = true - }), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.Mock.ExpectedCalls)) { - call := mockedService.Mock.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod3", call.Method) - assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) - assert.Equal(t, nil, call.ReturnArguments[0]) - assert.Equal(t, 0, call.Repeatability) - assert.NotEqual(t, nil, call.WaitFor) - assert.NotNil(t, call.Run) - - } - - et := ExampleType{} - assert.Equal(t, false, et.ran) - mockedService.TheExampleMethod3(&et) - assert.Equal(t, true, et.ran) - -} - -func Test_Mock_Return_Once(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Once() - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 1, call.Repeatability) - assert.Nil(t, call.WaitFor) - - } - -} - -func Test_Mock_Return_Twice(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Twice() - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 2, call.Repeatability) - assert.Nil(t, call.WaitFor) - - } - -} - -func Test_Mock_Return_Times(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", "A", "B", true).Return(1, "two", true).Times(5) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 1, call.ReturnArguments[0]) - assert.Equal(t, "two", call.ReturnArguments[1]) - assert.Equal(t, true, call.ReturnArguments[2]) - assert.Equal(t, 5, call.Repeatability) - assert.Nil(t, call.WaitFor) - - } - -} - -func Test_Mock_Return_Nothing(t *testing.T) { - - // make a test impl object - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - assert.Equal(t, mockedService.On("TheExampleMethod", "A", "B", true).Return(), &mockedService.Mock) - - // ensure the call was created - if assert.Equal(t, 1, len(mockedService.ExpectedCalls)) { - call := mockedService.ExpectedCalls[0] - - assert.Equal(t, "TheExampleMethod", call.Method) - assert.Equal(t, "A", call.Arguments[0]) - assert.Equal(t, "B", call.Arguments[1]) - assert.Equal(t, true, call.Arguments[2]) - assert.Equal(t, 0, len(call.ReturnArguments)) - - } - -} - -func Test_Mock_findExpectedCall(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two") - m.On("Two", 3).Return("three") - - f, _ := m.findExpectedCall("Two") - - assert.Equal(t, -1, f) - -} - -func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { - - m := new(Mock) - m.On("One", 1).Return("one") - m.On("Two", 2).Return("two").Once() - m.On("Two", 3).Return("three").Twice() - m.On("Two", 3).Return("three").Times(8) - - f, c := m.findExpectedCall("Two", 3) - - if assert.Equal(t, 2, f) { - if assert.NotNil(t, c) { - assert.Equal(t, "Two", c.Method) - assert.Equal(t, 3, c.Arguments[0]) - assert.Equal(t, "three", c.ReturnArguments[0]) - } - } - -} - -func Test_callString(t *testing.T) { - - assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) - -} - -func Test_Mock_Called(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) - - returnArguments := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 1, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments)) { - assert.Equal(t, 5, returnArguments[0]) - assert.Equal(t, "6", returnArguments[1]) - assert.Equal(t, true, returnArguments[2]) - } - -} - -func asyncCall(m *Mock, ch chan Arguments) { - ch <- m.Called(1, 2, 3) -} - -func Test_Mock_Called_blocks(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) - - ch := make(chan Arguments) - - go asyncCall(&mockedService.Mock, ch) - - select { - case <-ch: - t.Fatal("should have waited") - case <-time.After(1 * time.Millisecond): - } - - returnArguments := <-ch - - if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { - assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) - assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments)) { - assert.Equal(t, 5, returnArguments[0]) - assert.Equal(t, "6", returnArguments[1]) - assert.Equal(t, true, returnArguments[2]) - } - -} - -func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(5, "6", true).Once() - mockedService.On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).Return(-1, "hi", false) - - returnArguments1 := mockedService.Called(1, 2, 3) - returnArguments2 := mockedService.Called(1, 2, 3) - - if assert.Equal(t, 2, len(mockedService.Calls)) { - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) - assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) - - assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) - assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) - assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) - assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) - } - - if assert.Equal(t, 3, len(returnArguments1)) { - assert.Equal(t, 5, returnArguments1[0]) - assert.Equal(t, "6", returnArguments1[1]) - assert.Equal(t, true, returnArguments1[2]) - } - - if assert.Equal(t, 3, len(returnArguments2)) { - assert.Equal(t, -1, returnArguments2[0]) - assert.Equal(t, "hi", returnArguments2[1]) - assert.Equal(t, false, returnArguments2[2]) - } - -} - -func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) - - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - mockedService.TheExampleMethod(1, 2, 3) - assert.Panics(t, func() { - mockedService.TheExampleMethod(1, 2, 3) - }) - -} - -func Test_Mock_Called_Unexpected(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - // make sure it panics if no expectation was made - assert.Panics(t, func() { - mockedService.Called(1, 2, 3) - }, "Calling unexpected method should panic") - -} - -func Test_AssertExpectationsForObjects_Helper(t *testing.T) { - - var mockedService1 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService2 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService3 *TestExampleImplementation = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() - - mockedService1.Called(1) - mockedService2.Called(2) - mockedService3.Called(3) - - assert.True(t, AssertExpectationsForObjects(t, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) - -} - -func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { - - var mockedService1 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService2 *TestExampleImplementation = new(TestExampleImplementation) - var mockedService3 *TestExampleImplementation = new(TestExampleImplementation) - - mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() - mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() - mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() - - mockedService1.Called(1) - mockedService3.Called(3) - - tt := new(testing.T) - assert.False(t, AssertExpectationsForObjects(tt, mockedService1.Mock, mockedService2.Mock, mockedService3.Mock)) - -} - -func Test_Mock_AssertExpectations(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectationsCustomType(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.TheExampleMethod3(&ExampleType{}) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() - - tt := new(testing.T) - assert.False(t, mockedService.AssertExpectations(tt)) - - // make the call now - mockedService.Called(1, 2, 3) - - assert.False(t, mockedService.AssertExpectations(tt)) - - mockedService.Called(1, 2, 3) - - // now assert expectations - assert.True(t, mockedService.AssertExpectations(tt)) - -} - -func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) - mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) - - args1 := mockedService.Called(1, 2, 3) - assert.Equal(t, 5, args1.Int(0)) - assert.Equal(t, 6, args1.Int(1)) - assert.Equal(t, 7, args1.Int(2)) - - args2 := mockedService.Called(4, 5, 6) - assert.Equal(t, 5, args2.Int(0)) - assert.Equal(t, 6, args2.Int(1)) - assert.Equal(t, 7, args2.Int(2)) - -} - -func Test_Mock_AssertNumberOfCalls(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) - - mockedService.Called(1, 2, 3) - assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) - -} - -func Test_Mock_AssertCalled(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) - -} - -func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).Return() - - mockedService.Called(1, "two", []uint8("three")) - - assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) - -} - -func Test_Mock_AssertCalled_WithArguments(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) - -} - -func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() - mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() - - mockedService.Called(1, 2, 3) - mockedService.Called(2, 3, 4) - - tt := new(testing.T) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) - assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) - assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) - -} - -func Test_Mock_AssertNotCalled(t *testing.T) { - - var mockedService *TestExampleImplementation = new(TestExampleImplementation) - - mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) - - mockedService.Called(1, 2, 3) - - assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) - -} - -/* - Arguments helper methods -*/ -func Test_Arguments_Get(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.Equal(t, "string", args.Get(0).(string)) - assert.Equal(t, 123, args.Get(1).(int)) - assert.Equal(t, true, args.Get(2).(bool)) - -} - -func Test_Arguments_Is(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.True(t, args.Is("string", 123, true)) - assert.False(t, args.Is("wrong", 456, false)) - -} - -func Test_Arguments_Diff(t *testing.T) { - - var args Arguments = []interface{}{"Hello World", 123, true} - var diff string - var count int - diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) - - assert.Equal(t, 2, count) - assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) - assert.Contains(t, diff, `false != %!s(bool=true)`) - -} - -func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - var diff string - var count int - diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) - - assert.Equal(t, 3, count) - assert.Contains(t, diff, `extra != (Missing)`) - -} - -func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - var count int - _, count = args.Diff([]interface{}{"string", Anything, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { - - var args Arguments = []interface{}{"string", Anything, true} - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { - - var args Arguments = []interface{}{"string", AnythingOfType("int"), true} - var count int - _, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 0, count) - -} - -func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { - - var args Arguments = []interface{}{"string", AnythingOfType("string"), true} - var count int - var diff string - diff, count = args.Diff([]interface{}{"string", 123, true}) - - assert.Equal(t, 1, count) - assert.Contains(t, diff, `string != type int - %!s(int=123)`) - -} - -func Test_Arguments_Assert(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - - assert.True(t, args.Assert(t, "string", 123, true)) - -} - -func Test_Arguments_String_Representation(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, `string,int,bool`, args.String()) - -} - -func Test_Arguments_String(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, "string", args.String(0)) - -} - -func Test_Arguments_Error(t *testing.T) { - - var err error = errors.New("An Error") - var args Arguments = []interface{}{"string", 123, true, err} - assert.Equal(t, err, args.Error(3)) - -} - -func Test_Arguments_Error_Nil(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true, nil} - assert.Equal(t, nil, args.Error(3)) - -} - -func Test_Arguments_Int(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, 123, args.Int(1)) - -} - -func Test_Arguments_Bool(t *testing.T) { - - var args Arguments = []interface{}{"string", 123, true} - assert.Equal(t, true, args.Bool(2)) - -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go deleted file mode 100644 index 02be2916e7c..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/forward_requirements_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package require - -import ( - "errors" - "testing" - "time" -) - -func TestImplementsWrapper(t *testing.T) { - require := New(t) - - require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsTypeWrapper(t *testing.T) { - require := New(t) - require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualWrapper(t *testing.T) { - require := New(t) - require.Equal(1, 1) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Equal(1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEqualWrapper(t *testing.T) { - require := New(t) - require.NotEqual(1, 2) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEqual(2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactlyWrapper(t *testing.T) { - require := New(t) - - a := float32(1) - b := float32(1) - c := float64(1) - - require.Exactly(a, b) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Exactly(a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNilWrapper(t *testing.T) { - require := New(t) - require.NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotNil(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNilWrapper(t *testing.T) { - require := New(t) - require.Nil(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Nil(new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrueWrapper(t *testing.T) { - require := New(t) - require.True(true) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.True(false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalseWrapper(t *testing.T) { - require := New(t) - require.False(false) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.False(true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContainsWrapper(t *testing.T) { - require := New(t) - require.Contains("Hello World", "Hello") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Contains("Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContainsWrapper(t *testing.T) { - require := New(t) - require.NotContains("Hello World", "Hello!") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotContains("Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanicsWrapper(t *testing.T) { - require := New(t) - require.Panics(func() { - panic("Panic!") - }) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Panics(func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanicsWrapper(t *testing.T) { - require := New(t) - require.NotPanics(func() {}) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotPanics(func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoErrorWrapper(t *testing.T) { - require := New(t) - require.NoError(nil) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NoError(errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestErrorWrapper(t *testing.T) { - require := New(t) - require.Error(errors.New("some error")) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Error(nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualErrorWrapper(t *testing.T) { - require := New(t) - require.EqualError(errors.New("some error"), "some error") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.EqualError(errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmptyWrapper(t *testing.T) { - require := New(t) - require.Empty("") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.Empty("x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmptyWrapper(t *testing.T) { - require := New(t) - require.NotEmpty("x") - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.NotEmpty("") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDurationWrapper(t *testing.T) { - require := New(t) - a := time.Now() - b := a.Add(10 * time.Second) - - require.WithinDuration(a, b, 15*time.Second) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.WithinDuration(a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDeltaWrapper(t *testing.T) { - require := New(t) - require.InDelta(1.001, 1, 0.01) - - mockT := new(MockT) - mockRequire := New(mockT) - mockRequire.InDelta(1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} diff --git a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go b/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go deleted file mode 100644 index 9131b2f4d4e..00000000000 --- a/Godeps/_workspace/src/github.com/stretchr/testify/require/requirements_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package require - -import ( - "errors" - "testing" - "time" -) - -// AssertionTesterInterface defines an interface to be used for testing assertion methods -type AssertionTesterInterface interface { - TestMethod() -} - -// AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface -type AssertionTesterConformingObject struct { -} - -func (a *AssertionTesterConformingObject) TestMethod() { -} - -// AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface -type AssertionTesterNonConformingObject struct { -} - -type MockT struct { - Failed bool -} - -func (t *MockT) FailNow() { - t.Failed = true -} - -func (t *MockT) Errorf(format string, args ...interface{}) { - _, _ = format, args -} - -func TestImplements(t *testing.T) { - - Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestIsType(t *testing.T) { - - IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) - - mockT := new(MockT) - IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqual(t *testing.T) { - - Equal(t, 1, 1) - - mockT := new(MockT) - Equal(mockT, 1, 2) - if !mockT.Failed { - t.Error("Check should fail") - } - -} - -func TestNotEqual(t *testing.T) { - - NotEqual(t, 1, 2) - mockT := new(MockT) - NotEqual(mockT, 2, 2) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestExactly(t *testing.T) { - - a := float32(1) - b := float32(1) - c := float64(1) - - Exactly(t, a, b) - - mockT := new(MockT) - Exactly(mockT, a, c) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotNil(t *testing.T) { - - NotNil(t, new(AssertionTesterConformingObject)) - - mockT := new(MockT) - NotNil(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNil(t *testing.T) { - - Nil(t, nil) - - mockT := new(MockT) - Nil(mockT, new(AssertionTesterConformingObject)) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestTrue(t *testing.T) { - - True(t, true) - - mockT := new(MockT) - True(mockT, false) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestFalse(t *testing.T) { - - False(t, false) - - mockT := new(MockT) - False(mockT, true) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestContains(t *testing.T) { - - Contains(t, "Hello World", "Hello") - - mockT := new(MockT) - Contains(mockT, "Hello World", "Salut") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotContains(t *testing.T) { - - NotContains(t, "Hello World", "Hello!") - - mockT := new(MockT) - NotContains(mockT, "Hello World", "Hello") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestPanics(t *testing.T) { - - Panics(t, func() { - panic("Panic!") - }) - - mockT := new(MockT) - Panics(mockT, func() {}) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotPanics(t *testing.T) { - - NotPanics(t, func() {}) - - mockT := new(MockT) - NotPanics(mockT, func() { - panic("Panic!") - }) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNoError(t *testing.T) { - - NoError(t, nil) - - mockT := new(MockT) - NoError(mockT, errors.New("some error")) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestError(t *testing.T) { - - Error(t, errors.New("some error")) - - mockT := new(MockT) - Error(mockT, nil) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEqualError(t *testing.T) { - - EqualError(t, errors.New("some error"), "some error") - - mockT := new(MockT) - EqualError(mockT, errors.New("some error"), "Not some error") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestEmpty(t *testing.T) { - - Empty(t, "") - - mockT := new(MockT) - Empty(mockT, "x") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestNotEmpty(t *testing.T) { - - NotEmpty(t, "x") - - mockT := new(MockT) - NotEmpty(mockT, "") - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestWithinDuration(t *testing.T) { - - a := time.Now() - b := a.Add(10 * time.Second) - - WithinDuration(t, a, b, 15*time.Second) - - mockT := new(MockT) - WithinDuration(mockT, a, b, 5*time.Second) - if !mockT.Failed { - t.Error("Check should fail") - } -} - -func TestInDelta(t *testing.T) { - - InDelta(t, 1.001, 1, 0.01) - - mockT := new(MockT) - InDelta(mockT, 1, 2, 0.5) - if !mockT.Failed { - t.Error("Check should fail") - } -} diff --git a/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go b/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go deleted file mode 100644 index 8108655c05f..00000000000 --- a/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -import "testing" - -func TestState(t *testing.T) { - testEmpty := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Empty(i) { - t.Errorf(name+": capabilities set %q wasn't empty", i) - } - } - } - testFull := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Full(i) { - t.Errorf(name+": capabilities set %q wasn't full", i) - } - } - } - testPartial := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && (c.Empty(i) || c.Full(i)) { - t.Errorf(name+": capabilities set %q wasn't partial", i) - } - } - } - testGet := func(name string, c Capabilities, whats CapType, max Cap) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i & whats) == 0 { - continue - } - for j := Cap(0); j <= max; j++ { - if !c.Get(i, j) { - t.Errorf(name+": capability %q wasn't found on %q", j, i) - } - } - } - } - - capf := new(capsFile) - capf.data.version = 2 - for _, tc := range []struct { - name string - c Capabilities - sets CapType - max Cap - }{ - {"v1", new(capsV1), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"v3", new(capsV3), EFFECTIVE | PERMITTED | BOUNDING, CAP_LAST_CAP}, - {"file_v1", new(capsFile), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"file_v2", capf, EFFECTIVE | PERMITTED, CAP_LAST_CAP}, - } { - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Fill(CAPS | BOUNDS) - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Set(i, j) - } - } - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Unset(i, j) - } - } - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Set(PERMITTED, CAP_CHOWN) - testPartial(tc.name, tc.c, PERMITTED) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - } -} 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 205dffa7d15..00000000000 --- 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 d9583a9b139..00000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codec_test.go +++ /dev/null @@ -1,1175 +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 -} - -func doTestMapEncodeForCanonical(t *testing.T, name string, h Handle) { - v1 := map[string]interface{}{ - "a": 1, - "b": "hello", - "c": map[string]interface{}{ - "c/a": 1, - "c/b": "world", - "c/c": []int{1, 2, 3, 4}, - "c/d": map[string]interface{}{ - "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda", - "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa", - "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw", - "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag", - "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb", - "c/d/f": "", - }, - "c/e": map[int]string{ - 1: "1", - 22: "22", - 333: "333", - 4444: "4444", - 55555: "55555", - }, - "c/f": map[string]int{ - "1": 1, - "22": 22, - "333": 333, - "4444": 4444, - "55555": 55555, - }, - }, - } - var v2 map[string]interface{} - var b1, b2 []byte - - // encode v1 into b1, decode b1 into v2, encode v2 into b2, compare b1 and b2 - - bh := h.getBasicHandle() - canonical0 := bh.Canonical - bh.Canonical = true - defer func() { bh.Canonical = canonical0 }() - - e1 := NewEncoderBytes(&b1, h) - e1.MustEncode(v1) - d1 := NewDecoderBytes(b1, h) - d1.MustDecode(&v2) - e2 := NewEncoderBytes(&b2, h) - e2.MustEncode(v2) - if !bytes.Equal(b1, b2) { - logT(t, "Unequal bytes: %v VS %v", b1, b2) - t.FailNow() - } -} - -// 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 TestCborMapEncodeForCanonical(t *testing.T) { - doTestMapEncodeForCanonical(t, "cbor", 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_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go deleted file mode 100644 index bb7e0bfcfeb..00000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/codecgen_test.go +++ /dev/null @@ -1,23 +0,0 @@ -//+build x,codecgen - -package codec - -import ( - "fmt" - "testing" -) - -func TestCodecgenJson1(t *testing.T) { - // This is just a simplistic test for codecgen. - 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/helper_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/helper_test.go deleted file mode 100644 index 685c576c4e3..00000000000 --- 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/py_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go deleted file mode 100644 index bedd7b0dcf9..00000000000 --- a/Godeps/_workspace/src/github.com/ugorji/go/codec/py_test.go +++ /dev/null @@ -1,30 +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 running: go test -tags=x . -// Look at test.py for how to setup your environment. - -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/values_test.go b/Godeps/_workspace/src/github.com/ugorji/go/codec/values_test.go deleted file mode 100644 index 4ec28e131c8..00000000000 --- 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 38a6f0004cf..00000000000 --- 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 06a4d05eaf0..00000000000 --- 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/github.com/xyproto/simpleredis/simpleredis_test.go b/Godeps/_workspace/src/github.com/xyproto/simpleredis/simpleredis_test.go deleted file mode 100644 index cd9e4bf2d0e..00000000000 --- a/Godeps/_workspace/src/github.com/xyproto/simpleredis/simpleredis_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package simpleredis - -import ( - "testing" -) - -var pool *ConnectionPool - -func TestLocalConnection(t *testing.T) { - if err := TestConnection(); err != nil { - t.Errorf(err.Error()) - } -} - -func TestRemoteConnection(t *testing.T) { - if err := TestConnectionHost("foobared@ :6379"); err != nil { - t.Errorf(err.Error()) - } -} - -func TestConnectionPool(t *testing.T) { - pool = NewConnectionPool() -} - -func TestConnectionPoolHost(t *testing.T) { - pool = NewConnectionPoolHost("localhost:6379") -} - -// Tests with password "foobared" if the previous connection test -// did not result in a connection that responds to PING. -func TestConnectionPoolHostPassword(t *testing.T) { - if !pool.Ping() { - // Try connecting with the default password - pool = NewConnectionPoolHost("foobared@localhost:6379") - } -} - -func TestList(t *testing.T) { - const ( - listname = "abc123_test_test_test_123abc" - testdata = "123abc" - ) - list := NewList(pool, listname) - list.SelectDatabase(1) - if err := list.Add(testdata); err != nil { - t.Errorf("Error, could not add item to list! %s", err.Error()) - } - items, err := list.GetAll() - if len(items) != 1 { - t.Errorf("Error, wrong list length! %v", len(items)) - } - if (len(items) > 0) && (items[0] != testdata) { - t.Errorf("Error, wrong list contents! %v", items) - } - err = list.Remove() - if err != nil { - t.Errorf("Error, could not remove list! %s", err.Error()) - } -} - -func TestTwoFields(t *testing.T) { - test, test23, ok := twoFields("test1@test2@test3", "@") - if ok && ((test != "test1") || (test23 != "test2@test3")) { - t.Error("Error in twoFields functions") - } -} 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 80e2c2c3820..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/agent/client_test.go +++ /dev/null @@ -1,278 +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) { - agent, _, cleanup := startAgent(t) - defer cleanup() - - testAgentInterface(t, agent, key, cert) -} - -func testAgentInterface(t *testing.T, agent Agent, key interface{}, cert *ssh.Certificate) { - 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(key, cert, "comment") - pubKey = cert - } else { - err = agent.Add(key, nil, "comment") - 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) - } -} - -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) -} - -// 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(testPrivateKeys["rsa"], nil, "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(testPrivateKeys["rsa"], nil, "comment 1"); err != nil { - t.Errorf("Add: %v", err) - } - if err := agent.Add(testPrivateKeys["dsa"], nil, "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 def5f8ccc31..00000000000 --- 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) -} - -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) - 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 b7a8781e1a5..00000000000 --- 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 d9f7eb9b60a..00000000000 --- 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 d5781cb3da9..00000000000 --- 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 7d1b00f6d13..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/certs_test.go +++ /dev/null @@ -1,156 +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" - "testing" - "time" -) - -// Cert generated by ssh-keygen 6.0p1 Debian-4. -// % ssh-keygen -s ca-key -I test user-key -var 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, want *Certificate", 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) - } -} - -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() - - go func() { - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(certSigner) - _, _, _, err := NewServerConn(c1, &conf) - if err != nil { - t.Fatalf("NewServerConn: %v", 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) - } - } -} 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 2fb75d0d735..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/cipher_test.go +++ /dev/null @@ -1,64 +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) - } - } -} 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 c92b58786b8..00000000000 --- 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 1fe790cb494..00000000000 --- 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/example_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/example_test.go deleted file mode 100644 index dfd9dcab606..00000000000 --- 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_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go deleted file mode 100644 index 613c4982243..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/handshake_test.go +++ /dev/null @@ -1,311 +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" - "fmt" - "net" - "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.SetDefaults() - server = newServerTransport(trS, v, v, serverConf) - - return client, server, nil -} - -func TestHandshakeBasic(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() - - 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 -} 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 0db5f9be1c1..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/kex_test.go +++ /dev/null @@ -1,48 +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) - c <- kexResultErr{r, e} - }() - go func() { - r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) - 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_test.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/keys_test.go deleted file mode 100644 index 36b97ad225c..00000000000 --- 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 92519dd6bdb..00000000000 --- 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 21d52daf264..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/messages_test.go +++ /dev/null @@ -1,244 +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 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 523038960f2..00000000000 --- 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 88e66bf48a5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/session_test.go +++ /dev/null @@ -1,680 +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" - "io" - "io/ioutil" - "math/rand" - "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.") - } -} 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 f1265cb4964..00000000000 --- 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 a663fe41b77..00000000000 --- 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 502e24febb8..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/agent_unix_test.go +++ /dev/null @@ -1,50 +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() - keyring.Add(testPrivateKeys["dsa"], nil, "") - 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 364790f17d7..00000000000 --- 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 877a88cde3d..00000000000 --- 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 fbd1044f527..00000000000 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/test/session_test.go +++ /dev/null @@ -1,321 +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) - } - } -} 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 a2eb9358d02..00000000000 --- 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 f1fc50b2e48..00000000000 --- 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 ae48c7516cb..00000000000 --- 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 ae7bd8b89ec..00000000000 --- 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 5ff1c0e0358..00000000000 --- 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 f2828c1b5fb..00000000000 --- 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 92d83abf93f..00000000000 --- 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/exp/inotify/inotify_linux_test.go b/Godeps/_workspace/src/golang.org/x/exp/inotify/inotify_linux_test.go deleted file mode 100644 index 1685b772ec1..00000000000 --- a/Godeps/_workspace/src/golang.org/x/exp/inotify/inotify_linux_test.go +++ /dev/null @@ -1,107 +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. - -// +build linux - -package inotify - -import ( - "io/ioutil" - "os" - "sync/atomic" - "testing" - "time" -) - -func TestInotifyEvents(t *testing.T) { - // Create an inotify watcher instance and initialize it - watcher, err := NewWatcher() - if err != nil { - t.Fatalf("NewWatcher failed: %s", err) - } - - dir, err := ioutil.TempDir("", "inotify") - if err != nil { - t.Fatalf("TempDir failed: %s", err) - } - defer os.RemoveAll(dir) - - // Add a watch for "_test" - err = watcher.Watch(dir) - if err != nil { - t.Fatalf("Watch failed: %s", err) - } - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Error { - t.Fatalf("error received: %s", err) - } - }() - - testFile := dir + "/TestInotifyEvents.testfile" - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Event - var eventsReceived int32 = 0 - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == testFile { - atomic.AddInt32(&eventsReceived, 1) - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the inotify event queue - _, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 1 s to be sure - time.Sleep(1 * time.Second) - if atomic.AddInt32(&eventsReceived, 0) == 0 { - t.Fatal("inotify event hasn't been received after 1 second") - } - - // Try closing the inotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(1 * time.Second): - t.Fatal("event stream was not closed after 1 second") - } -} - -func TestInotifyClose(t *testing.T) { - watcher, _ := NewWatcher() - watcher.Close() - - done := make(chan bool) - go func() { - watcher.Close() - done <- true - }() - - select { - case <-done: - case <-time.After(50 * time.Millisecond): - t.Fatal("double Close() test failed: second Close() call didn't return") - } - - err := watcher.Watch(os.TempDir()) - if err == nil { - t.Fatal("expected error on Watch() after Close(), got nil") - } -} 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 e64afa64c66..00000000000 --- 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 47b53d7f18c..00000000000 --- 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 a6754dc3689..00000000000 --- 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/net/html/atom/atom_test.go b/Godeps/_workspace/src/golang.org/x/net/html/atom/atom_test.go deleted file mode 100644 index 6e33704dd5e..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/atom/atom_test.go +++ /dev/null @@ -1,109 +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 atom - -import ( - "sort" - "testing" -) - -func TestKnown(t *testing.T) { - for _, s := range testAtomList { - if atom := Lookup([]byte(s)); atom.String() != s { - t.Errorf("Lookup(%q) = %#x (%q)", s, uint32(atom), atom.String()) - } - } -} - -func TestHits(t *testing.T) { - for _, a := range table { - if a == 0 { - continue - } - got := Lookup([]byte(a.String())) - if got != a { - t.Errorf("Lookup(%q) = %#x, want %#x", a.String(), uint32(got), uint32(a)) - } - } -} - -func TestMisses(t *testing.T) { - testCases := []string{ - "", - "\x00", - "\xff", - "A", - "DIV", - "Div", - "dIV", - "aa", - "a\x00", - "ab", - "abb", - "abbr0", - "abbr ", - " abbr", - " a", - "acceptcharset", - "acceptCharset", - "accept_charset", - "h0", - "h1h2", - "h7", - "onClick", - "λ", - // The following string has the same hash (0xa1d7fab7) as "onmouseover". - "\x00\x00\x00\x00\x00\x50\x18\xae\x38\xd0\xb7", - } - for _, tc := range testCases { - got := Lookup([]byte(tc)) - if got != 0 { - t.Errorf("Lookup(%q): got %d, want 0", tc, got) - } - } -} - -func TestForeignObject(t *testing.T) { - const ( - afo = Foreignobject - afO = ForeignObject - sfo = "foreignobject" - sfO = "foreignObject" - ) - if got := Lookup([]byte(sfo)); got != afo { - t.Errorf("Lookup(%q): got %#v, want %#v", sfo, got, afo) - } - if got := Lookup([]byte(sfO)); got != afO { - t.Errorf("Lookup(%q): got %#v, want %#v", sfO, got, afO) - } - if got := afo.String(); got != sfo { - t.Errorf("Atom(%#v).String(): got %q, want %q", afo, got, sfo) - } - if got := afO.String(); got != sfO { - t.Errorf("Atom(%#v).String(): got %q, want %q", afO, got, sfO) - } -} - -func BenchmarkLookup(b *testing.B) { - sortedTable := make([]string, 0, len(table)) - for _, a := range table { - if a != 0 { - sortedTable = append(sortedTable, a.String()) - } - } - sort.Strings(sortedTable) - - x := make([][]byte, 1000) - for i := range x { - x[i] = []byte(sortedTable[i%len(sortedTable)]) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - for _, s := range x { - Lookup(s) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/atom/table_test.go b/Godeps/_workspace/src/golang.org/x/net/html/atom/table_test.go deleted file mode 100644 index 0f2ecce4fd4..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/atom/table_test.go +++ /dev/null @@ -1,351 +0,0 @@ -// generated by go run gen.go -test; DO NOT EDIT - -package atom - -var testAtomList = []string{ - "a", - "abbr", - "abbr", - "accept", - "accept-charset", - "accesskey", - "action", - "address", - "align", - "alt", - "annotation", - "annotation-xml", - "applet", - "area", - "article", - "aside", - "async", - "audio", - "autocomplete", - "autofocus", - "autoplay", - "b", - "base", - "basefont", - "bdi", - "bdo", - "bgsound", - "big", - "blink", - "blockquote", - "body", - "br", - "button", - "canvas", - "caption", - "center", - "challenge", - "charset", - "checked", - "cite", - "cite", - "class", - "code", - "col", - "colgroup", - "color", - "cols", - "colspan", - "command", - "command", - "content", - "contenteditable", - "contextmenu", - "controls", - "coords", - "crossorigin", - "data", - "data", - "datalist", - "datetime", - "dd", - "default", - "defer", - "del", - "desc", - "details", - "dfn", - "dialog", - "dir", - "dirname", - "disabled", - "div", - "dl", - "download", - "draggable", - "dropzone", - "dt", - "em", - "embed", - "enctype", - "face", - "fieldset", - "figcaption", - "figure", - "font", - "footer", - "for", - "foreignObject", - "foreignobject", - "form", - "form", - "formaction", - "formenctype", - "formmethod", - "formnovalidate", - "formtarget", - "frame", - "frameset", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "head", - "header", - "headers", - "height", - "hgroup", - "hidden", - "high", - "hr", - "href", - "hreflang", - "html", - "http-equiv", - "i", - "icon", - "id", - "iframe", - "image", - "img", - "input", - "inputmode", - "ins", - "isindex", - "ismap", - "itemid", - "itemprop", - "itemref", - "itemscope", - "itemtype", - "kbd", - "keygen", - "keytype", - "kind", - "label", - "label", - "lang", - "legend", - "li", - "link", - "list", - "listing", - "loop", - "low", - "malignmark", - "manifest", - "map", - "mark", - "marquee", - "math", - "max", - "maxlength", - "media", - "mediagroup", - "menu", - "menuitem", - "meta", - "meter", - "method", - "mglyph", - "mi", - "min", - "minlength", - "mn", - "mo", - "ms", - "mtext", - "multiple", - "muted", - "name", - "nav", - "nobr", - "noembed", - "noframes", - "noscript", - "novalidate", - "object", - "ol", - "onabort", - "onafterprint", - "onautocomplete", - "onautocompleteerror", - "onbeforeprint", - "onbeforeunload", - "onblur", - "oncancel", - "oncanplay", - "oncanplaythrough", - "onchange", - "onclick", - "onclose", - "oncontextmenu", - "oncuechange", - "ondblclick", - "ondrag", - "ondragend", - "ondragenter", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onended", - "onerror", - "onfocus", - "onhashchange", - "oninput", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeyup", - "onlanguagechange", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadstart", - "onmessage", - "onmousedown", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onoffline", - "ononline", - "onpagehide", - "onpageshow", - "onpause", - "onplay", - "onplaying", - "onpopstate", - "onprogress", - "onratechange", - "onreset", - "onresize", - "onscroll", - "onseeked", - "onseeking", - "onselect", - "onshow", - "onsort", - "onstalled", - "onstorage", - "onsubmit", - "onsuspend", - "ontimeupdate", - "ontoggle", - "onunload", - "onvolumechange", - "onwaiting", - "open", - "optgroup", - "optimum", - "option", - "output", - "p", - "param", - "pattern", - "ping", - "placeholder", - "plaintext", - "poster", - "pre", - "preload", - "progress", - "prompt", - "public", - "q", - "radiogroup", - "readonly", - "rel", - "required", - "reversed", - "rows", - "rowspan", - "rp", - "rt", - "ruby", - "s", - "samp", - "sandbox", - "scope", - "scoped", - "script", - "seamless", - "section", - "select", - "selected", - "shape", - "size", - "sizes", - "small", - "sortable", - "sorted", - "source", - "spacer", - "span", - "span", - "spellcheck", - "src", - "srcdoc", - "srclang", - "start", - "step", - "strike", - "strong", - "style", - "style", - "sub", - "summary", - "sup", - "svg", - "system", - "tabindex", - "table", - "target", - "tbody", - "td", - "template", - "textarea", - "tfoot", - "th", - "thead", - "time", - "title", - "title", - "tr", - "track", - "translate", - "tt", - "type", - "typemustmatch", - "u", - "ul", - "usemap", - "value", - "var", - "video", - "wbr", - "width", - "wrap", - "xmp", -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/charset_test.go b/Godeps/_workspace/src/golang.org/x/net/html/charset/charset_test.go deleted file mode 100644 index 8b10399d3d7..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/charset_test.go +++ /dev/null @@ -1,236 +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 charset - -import ( - "bytes" - "encoding/xml" - "io/ioutil" - "runtime" - "strings" - "testing" - - "golang.org/x/text/transform" -) - -func transformString(t transform.Transformer, s string) (string, error) { - r := transform.NewReader(strings.NewReader(s), t) - b, err := ioutil.ReadAll(r) - return string(b), err -} - -var testCases = []struct { - utf8, other, otherEncoding string -}{ - {"Résumé", "Résumé", "utf8"}, - {"Résumé", "R\xe9sum\xe9", "latin1"}, - {"これは漢字です。", "S0\x8c0o0\"oW[g0Y0\x020", "UTF-16LE"}, - {"これは漢字です。", "0S0\x8c0oo\"[W0g0Y0\x02", "UTF-16BE"}, - {"Hello, world", "Hello, world", "ASCII"}, - {"Gdańsk", "Gda\xf1sk", "ISO-8859-2"}, - {"Ââ Čč Đđ Ŋŋ Õõ Šš Žž Åå Ää", "\xc2\xe2 \xc8\xe8 \xa9\xb9 \xaf\xbf \xd5\xf5 \xaa\xba \xac\xbc \xc5\xe5 \xc4\xe4", "ISO-8859-10"}, - {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "ISO-8859-11"}, - {"latviešu", "latvie\xf0u", "ISO-8859-13"}, - {"Seònaid", "Se\xf2naid", "ISO-8859-14"}, - {"€1 is cheap", "\xa41 is cheap", "ISO-8859-15"}, - {"românește", "rom\xe2ne\xbate", "ISO-8859-16"}, - {"nutraĵo", "nutra\xbco", "ISO-8859-3"}, - {"Kalâdlit", "Kal\xe2dlit", "ISO-8859-4"}, - {"русский", "\xe0\xe3\xe1\xe1\xda\xd8\xd9", "ISO-8859-5"}, - {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "ISO-8859-7"}, - {"Kağan", "Ka\xf0an", "ISO-8859-9"}, - {"Résumé", "R\x8esum\x8e", "macintosh"}, - {"Gdańsk", "Gda\xf1sk", "windows-1250"}, - {"русский", "\xf0\xf3\xf1\xf1\xea\xe8\xe9", "windows-1251"}, - {"Résumé", "R\xe9sum\xe9", "windows-1252"}, - {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "windows-1253"}, - {"Kağan", "Ka\xf0an", "windows-1254"}, - {"עִבְרִית", "\xf2\xc4\xe1\xc0\xf8\xc4\xe9\xfa", "windows-1255"}, - {"العربية", "\xc7\xe1\xda\xd1\xc8\xed\xc9", "windows-1256"}, - {"latviešu", "latvie\xf0u", "windows-1257"}, - {"Việt", "Vi\xea\xf2t", "windows-1258"}, - {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "windows-874"}, - {"русский", "\xd2\xd5\xd3\xd3\xcb\xc9\xca", "KOI8-R"}, - {"українська", "\xd5\xcb\xd2\xc1\xa7\xce\xd3\xd8\xcb\xc1", "KOI8-U"}, - {"Hello 常用國字標準字體表", "Hello \xb1`\xa5\u03b0\xea\xa6r\xbc\u0437\u01e6r\xc5\xe9\xaa\xed", "big5"}, - {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gbk"}, - {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gb18030"}, - {"עִבְרִית", "\x81\x30\xfb\x30\x81\x30\xf6\x34\x81\x30\xf9\x33\x81\x30\xf6\x30\x81\x30\xfb\x36\x81\x30\xf6\x34\x81\x30\xfa\x31\x81\x30\xfb\x38", "gb18030"}, - {"㧯", "\x82\x31\x89\x38", "gb18030"}, - {"これは漢字です。", "\x82\xb1\x82\xea\x82\xcd\x8a\xbf\x8e\x9a\x82\xc5\x82\xb7\x81B", "SJIS"}, - {"Hello, 世界!", "Hello, \x90\xa2\x8aE!", "SJIS"}, - {"イウエオカ", "\xb2\xb3\xb4\xb5\xb6", "SJIS"}, - {"これは漢字です。", "\xa4\xb3\xa4\xec\xa4\u03f4\xc1\xbb\xfa\xa4\u01e4\xb9\xa1\xa3", "EUC-JP"}, - {"Hello, 世界!", "Hello, \x1b$B@$3&\x1b(B!", "ISO-2022-JP"}, - {"네이트 | 즐거움의 시작, 슈파스(Spaβ) NATE", "\xb3\xd7\xc0\xcc\xc6\xae | \xc1\xf1\xb0\xc5\xbf\xf2\xc0\xc7 \xbd\xc3\xc0\xdb, \xbd\xb4\xc6\xc4\xbd\xba(Spa\xa5\xe2) NATE", "EUC-KR"}, -} - -func TestDecode(t *testing.T) { - for _, tc := range testCases { - e, _ := Lookup(tc.otherEncoding) - if e == nil { - t.Errorf("%s: not found", tc.otherEncoding) - continue - } - s, err := transformString(e.NewDecoder(), tc.other) - if err != nil { - t.Errorf("%s: decode %q: %v", tc.otherEncoding, tc.other, err) - continue - } - if s != tc.utf8 { - t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.utf8) - } - } -} - -func TestEncode(t *testing.T) { - for _, tc := range testCases { - e, _ := Lookup(tc.otherEncoding) - if e == nil { - t.Errorf("%s: not found", tc.otherEncoding) - continue - } - s, err := transformString(e.NewEncoder(), tc.utf8) - if err != nil { - t.Errorf("%s: encode %q: %s", tc.otherEncoding, tc.utf8, err) - continue - } - if s != tc.other { - t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.other) - } - } -} - -// TestNames verifies that you can pass an encoding's name to Lookup and get -// the same encoding back (except for "replacement"). -func TestNames(t *testing.T) { - for _, e := range encodings { - if e.name == "replacement" { - continue - } - _, got := Lookup(e.name) - if got != e.name { - t.Errorf("got %q, want %q", got, e.name) - continue - } - } -} - -var sniffTestCases = []struct { - filename, declared, want string -}{ - {"HTTP-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"UTF-16LE-BOM.html", "", "utf-16le"}, - {"UTF-16BE-BOM.html", "", "utf-16be"}, - {"meta-content-attribute.html", "text/html", "iso-8859-15"}, - {"meta-charset-attribute.html", "text/html", "iso-8859-15"}, - {"No-encoding-declaration.html", "text/html", "utf-8"}, - {"HTTP-vs-UTF-8-BOM.html", "text/html; charset=iso-8859-15", "utf-8"}, - {"HTTP-vs-meta-content.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"HTTP-vs-meta-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"UTF-8-BOM-vs-meta-content.html", "text/html", "utf-8"}, - {"UTF-8-BOM-vs-meta-charset.html", "text/html", "utf-8"}, -} - -func TestSniff(t *testing.T) { - switch runtime.GOOS { - case "nacl": // platforms that don't permit direct file system access - t.Skipf("not supported on %q", runtime.GOOS) - } - - for _, tc := range sniffTestCases { - content, err := ioutil.ReadFile("testdata/" + tc.filename) - if err != nil { - t.Errorf("%s: error reading file: %v", tc.filename, err) - continue - } - - _, name, _ := DetermineEncoding(content, tc.declared) - if name != tc.want { - t.Errorf("%s: got %q, want %q", tc.filename, name, tc.want) - continue - } - } -} - -func TestReader(t *testing.T) { - switch runtime.GOOS { - case "nacl": // platforms that don't permit direct file system access - t.Skipf("not supported on %q", runtime.GOOS) - } - - for _, tc := range sniffTestCases { - content, err := ioutil.ReadFile("testdata/" + tc.filename) - if err != nil { - t.Errorf("%s: error reading file: %v", tc.filename, err) - continue - } - - r, err := NewReader(bytes.NewReader(content), tc.declared) - if err != nil { - t.Errorf("%s: error creating reader: %v", tc.filename, err) - continue - } - - got, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("%s: error reading from charset.NewReader: %v", tc.filename, err) - continue - } - - e, _ := Lookup(tc.want) - want, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(content), e.NewDecoder())) - if err != nil { - t.Errorf("%s: error decoding with hard-coded charset name: %v", tc.filename, err) - continue - } - - if !bytes.Equal(got, want) { - t.Errorf("%s: got %q, want %q", tc.filename, got, want) - continue - } - } -} - -var metaTestCases = []struct { - meta, want string -}{ - {"", ""}, - {"text/html", ""}, - {"text/html; charset utf-8", ""}, - {"text/html; charset=latin-2", "latin-2"}, - {"text/html; charset; charset = utf-8", "utf-8"}, - {`charset="big5"`, "big5"}, - {"charset='shift_jis'", "shift_jis"}, -} - -func TestFromMeta(t *testing.T) { - for _, tc := range metaTestCases { - got := fromMetaElement(tc.meta) - if got != tc.want { - t.Errorf("%q: got %q, want %q", tc.meta, got, tc.want) - } - } -} - -func TestXML(t *testing.T) { - const s = "r\xe9sum\xe9" - - d := xml.NewDecoder(strings.NewReader(s)) - d.CharsetReader = NewReaderLabel - - var a struct { - Word string - } - err := d.Decode(&a) - if err != nil { - t.Fatalf("Decode: %v", err) - } - - want := "résumé" - if a.Word != want { - t.Errorf("got %q, want %q", a.Word, want) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-charset.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-charset.html deleted file mode 100644 index 9915fa0ee4f..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-charset.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - HTTP charset - - - - - - - - - - - -

    HTTP charset

    - - -
    - - -
     
    - - - - - -
    -

    The character encoding of a page can be set using the HTTP header charset declaration.

    -

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

    The only character encoding declaration for this HTML file is in the HTTP header, which sets the encoding to ISO 8859-15.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-001
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html deleted file mode 100644 index 26e5d8b4ebf..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - HTTP vs UTF-8 BOM - - - - - - - - - - - -

    HTTP vs UTF-8 BOM

    - - -
    - - -
     
    - - - - - -
    -

    A character encoding set in the HTTP header has lower precedence than the UTF-8 signature.

    -

    The HTTP header attempts to set the character encoding to ISO 8859-15. The page starts with a UTF-8 signature.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

    If the test is unsuccessful, the characters  should appear at the top of the page. These represent the bytes that make up the UTF-8 signature when encountered in the ISO 8859-15 encoding.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-034
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html deleted file mode 100644 index 2f07e95158e..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - HTTP vs meta charset - - - - - - - - - - - -

    HTTP vs meta charset

    - - -
    - - -
     
    - - - - - -
    -

    The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute.

    -

    The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-1.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-018
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html deleted file mode 100644 index 6853cddeccc..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - HTTP vs meta content - - - - - - - - - - - -

    HTTP vs meta content

    - - -
    - - -
     
    - - - - - -
    -

    The HTTP header has a higher precedence than an encoding declaration in a meta content attribute.

    -

    The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-1.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-016
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html deleted file mode 100644 index 612e26c6c52..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - No encoding declaration - - - - - - - - - - - -

    No encoding declaration

    - - -
    - - -
     
    - - - - - -
    -

    A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.

    -

    The test on this page contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-015
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/README b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/README deleted file mode 100644 index 38ef0f9f121..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/README +++ /dev/null @@ -1,9 +0,0 @@ -These test cases come from -http://www.w3.org/International/tests/repository/html5/the-input-byte-stream/results-basics - -Distributed under both the W3C Test Suite License -(http://www.w3.org/Consortium/Legal/2008/04-testsuite-license) -and the W3C 3-clause BSD License -(http://www.w3.org/Consortium/Legal/2008/03-bsd-license). -To contribute to a W3C Test Suite, see the policies and contribution -forms (http://www.w3.org/2004/10/27-testcases). diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-16BE-BOM.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-16BE-BOM.html deleted file mode 100644 index 3abf7a9343c20518e57dfea58b374fb0f4fb58a1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2670 zcmcJR?QRoS5Qc}JAoU&=BQ-(7b^;2j8i*i3RV1JlO@;VXIsPurV!WHiDdLW}i`*CO z^UnC>tih=KsVr;H&Y7?C&O3AV(?534uG?e##U9y_y|!QNi4``n+D>d{2lky^LnFNx z?9HrarH$>rwQR_$g)Hk0*&STI*EYq|47~&U9sfUB+ji})9eR{QqCUra7oDsZ5obtB zdxP%<)-$4Q;rSHJiM>U(#ZI=;?n^BC?Dp6lu=~_1-lnX3u03&2BlmQIY>L+!Uq7XoytKw^Q#oZSM?3*J?)&ojG&yzQRkC!Ml5JE?ax;lp_NYEcdUht`ZswOviB~L5hmJ|pXI71nn20w;>vG! zQGB$EE9&wC``&J#_Ym~PgRu-Bd>1!pOp0||k`kr=VJ zfH6I6rmRaeHA7U-A^OTsT+|d2a^i(>DePzZ{)ibXoCBvJnuYrd-3kkN$uy{qQK;=*Y;S87ro12aTgu^i*%f8zC3>a}9DIe4cfxOzsCw&(cqvP9{ud{N6f` z#TNDY(B6@Gpr|uN+%&x^XZjBHdc@2vsM(Tyc2=vshHQ5w+obmp>tuWT(t4BTUGAQw zxeI$UGSLUBg=WFbF;4f@4=^P2AgY@CFn8A`bcC=_&~)fiDe)#cUARRBzJ^k|%X)69 z+{Cb`wq}Rsg%B62CC_tK!AV(W{(MV?#mndR46CU#BUN<{8e?*oT+!pE5wF#O#TR#a z$9qRT)tpbw8zAI~QQJg2C3|6$I%(T(;`zOMy6SO+&;pG=c#2P|P-WZn$$DpWJlC3U z3*nvmz zwP{u~r$L?-m3uqp9I1+#3yE|3M$(s-BEtih=LQ>`qYoiktOop(wi%!;yh%+Rm z{e|xntY<{q!1F1Z6MKtngPm-p-4|H&+3m4AVE3_AyiHm6Tzlf4M(*ht*%YrezJ6kr zHGj45pc?64*$Cm%-zseWMA`x;)v*~jA=i}szqts9xmQkS`M11|(H7bTXAycsXU53+ zJ?120SRZeyiFjW7enPN`bxk$IaWV3o48oJF7D&2ysoY;6(s6%6vVfaYd&mC=erK!) zNGI^7upQgN)53OHe_VE<@J+G8*Y|p*)zB2Thdi}+YR<5QWHm!|a_*AoZXuv7)$xe| zm3Q$D7{|#}{m4X&UY!6(ZhyYi2(5JLzGE$H)W6BQklnjPMwn<Yvv7Z*TVWwD*=E3QpH37* z#lqXJA0A~J9T_<^W5smspmDg2p6ac5Bjn+~LAoow%1TCdZ*$K8`O zw_$HaCi+0N&@7la#_7KL5r$+QL{)Pi=I&aDjt~|Knht#`CEi4*3%97i_fSfASlwUz0=3V0GCxY}z81UC-nP=CGt2OqYV$ zoRCo+qM9YX*3FFORLC=E3B~S@+KROyk4r5 yX7?DaslDfIebqXgC!KKp4IYy+W~X?ddE6o=`A+x#x0AK&6MF#W&AXxbRrv+SX}PNa diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html deleted file mode 100644 index 83de43338ec..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - UTF-8 BOM vs meta charset - - - - - - - - - - - -

    UTF-8 BOM vs meta charset

    - - -
    - - -
     
    - - - - - -
    -

    A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding.

    -

    The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-038
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html deleted file mode 100644 index 501aac2d6a5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - UTF-8 BOM vs meta content - - - - - - - - - - - -

    UTF-8 BOM vs meta content

    - - -
    - - -
     
    - - - - - -
    -

    A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding.

    -

    The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-037
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html deleted file mode 100644 index 2d7d25aba14..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - meta charset attribute - - - - - - - - - - - -

    meta charset attribute

    - - -
    - - -
     
    - - - - - -
    -

    The character encoding of the page can be set by a meta element with charset attribute.

    -

    The only character encoding declaration for this HTML file is in the charset attribute of the meta element, which declares the encoding to be ISO 8859-15.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-009
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-content-attribute.html b/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-content-attribute.html deleted file mode 100644 index 1c3f228e7c9..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/charset/testdata/meta-content-attribute.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - meta content attribute - - - - - - - - - - - -

    meta content attribute

    - - -
    - - -
     
    - - - - - -
    -

    The character encoding of the page can be set by a meta element with http-equiv and content attributes.

    -

    The only character encoding declaration for this HTML file is in the content attribute of the meta element, which declares the encoding to be ISO 8859-15.

    The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

    -
    -
    -
    HTML5
    -

    the-input-byte-stream-007
    Result summary & related tests
    Detailed results for this test
    Link to spec

    -
    Assumptions:
    • The default encoding for the browser you are testing is not set to ISO 8859-15.
    • -
    • The test is read from a server that supports HTTP.
    -
    - - - - - - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/entity_test.go b/Godeps/_workspace/src/golang.org/x/net/html/entity_test.go deleted file mode 100644 index b53f866fa2d..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/entity_test.go +++ /dev/null @@ -1,29 +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 html - -import ( - "testing" - "unicode/utf8" -) - -func TestEntityLength(t *testing.T) { - // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key). - // The +1 comes from the leading "&". This property implies that the length of - // unescaped text is <= the length of escaped text. - for k, v := range entity { - if 1+len(k) < utf8.RuneLen(v) { - t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v)) - } - if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' { - t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon) - } - } - for k, v := range entity2 { - if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) { - t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1])) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/escape_test.go b/Godeps/_workspace/src/golang.org/x/net/html/escape_test.go deleted file mode 100644 index b405d4b4a77..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/escape_test.go +++ /dev/null @@ -1,97 +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 html - -import "testing" - -type unescapeTest struct { - // A short description of the test case. - desc string - // The HTML text. - html string - // The unescaped text. - unescaped string -} - -var unescapeTests = []unescapeTest{ - // Handle no entities. - { - "copy", - "A\ttext\nstring", - "A\ttext\nstring", - }, - // Handle simple named entities. - { - "simple", - "& > <", - "& > <", - }, - // Handle hitting the end of the string. - { - "stringEnd", - "& &", - "& &", - }, - // Handle entities with two codepoints. - { - "multiCodepoint", - "text ⋛︀ blah", - "text \u22db\ufe00 blah", - }, - // Handle decimal numeric entities. - { - "decimalEntity", - "Delta = Δ ", - "Delta = Δ ", - }, - // Handle hexadecimal numeric entities. - { - "hexadecimalEntity", - "Lambda = λ = λ ", - "Lambda = λ = λ ", - }, - // Handle numeric early termination. - { - "numericEnds", - "&# &#x €43 © = ©f = ©", - "&# &#x €43 © = ©f = ©", - }, - // Handle numeric ISO-8859-1 entity replacements. - { - "numericReplacements", - "Footnote‡", - "Footnote‡", - }, -} - -func TestUnescape(t *testing.T) { - for _, tt := range unescapeTests { - unescaped := UnescapeString(tt.html) - if unescaped != tt.unescaped { - t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) - } - } -} - -func TestUnescapeEscape(t *testing.T) { - ss := []string{ - ``, - `abc def`, - `a & b`, - `a&b`, - `a & b`, - `"`, - `"`, - `"<&>"`, - `"<&>"`, - `3&5==1 && 0<1, "0<1", a+acute=á`, - `The special characters are: <, >, &, ' and "`, - } - for _, s := range ss { - if got := UnescapeString(EscapeString(s)); got != s { - t.Errorf("got %q want %q", got, s) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/example_test.go b/Godeps/_workspace/src/golang.org/x/net/html/example_test.go deleted file mode 100644 index 0b06ed7730f..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/example_test.go +++ /dev/null @@ -1,40 +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. - -// This example demonstrates parsing HTML data and walking the resulting tree. -package html_test - -import ( - "fmt" - "log" - "strings" - - "golang.org/x/net/html" -) - -func ExampleParse() { - s := `

    Links:

    ` - doc, err := html.Parse(strings.NewReader(s)) - if err != nil { - log.Fatal(err) - } - var f func(*html.Node) - f = func(n *html.Node) { - if n.Type == html.ElementNode && n.Data == "a" { - for _, a := range n.Attr { - if a.Key == "href" { - fmt.Println(a.Val) - break - } - } - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - f(c) - } - } - f(doc) - // Output: - // foo - // /bar/baz -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/node_test.go b/Godeps/_workspace/src/golang.org/x/net/html/node_test.go deleted file mode 100644 index 471102f3a22..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/node_test.go +++ /dev/null @@ -1,146 +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 html - -import ( - "fmt" -) - -// checkTreeConsistency checks that a node and its descendants are all -// consistent in their parent/child/sibling relationships. -func checkTreeConsistency(n *Node) error { - return checkTreeConsistency1(n, 0) -} - -func checkTreeConsistency1(n *Node, depth int) error { - if depth == 1e4 { - return fmt.Errorf("html: tree looks like it contains a cycle") - } - if err := checkNodeConsistency(n); err != nil { - return err - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := checkTreeConsistency1(c, depth+1); err != nil { - return err - } - } - return nil -} - -// checkNodeConsistency checks that a node's parent/child/sibling relationships -// are consistent. -func checkNodeConsistency(n *Node) error { - if n == nil { - return nil - } - - nParent := 0 - for p := n.Parent; p != nil; p = p.Parent { - nParent++ - if nParent == 1e4 { - return fmt.Errorf("html: parent list looks like an infinite loop") - } - } - - nForward := 0 - for c := n.FirstChild; c != nil; c = c.NextSibling { - nForward++ - if nForward == 1e6 { - return fmt.Errorf("html: forward list of children looks like an infinite loop") - } - if c.Parent != n { - return fmt.Errorf("html: inconsistent child/parent relationship") - } - } - - nBackward := 0 - for c := n.LastChild; c != nil; c = c.PrevSibling { - nBackward++ - if nBackward == 1e6 { - return fmt.Errorf("html: backward list of children looks like an infinite loop") - } - if c.Parent != n { - return fmt.Errorf("html: inconsistent child/parent relationship") - } - } - - if n.Parent != nil { - if n.Parent == n { - return fmt.Errorf("html: inconsistent parent relationship") - } - if n.Parent == n.FirstChild { - return fmt.Errorf("html: inconsistent parent/first relationship") - } - if n.Parent == n.LastChild { - return fmt.Errorf("html: inconsistent parent/last relationship") - } - if n.Parent == n.PrevSibling { - return fmt.Errorf("html: inconsistent parent/prev relationship") - } - if n.Parent == n.NextSibling { - return fmt.Errorf("html: inconsistent parent/next relationship") - } - - parentHasNAsAChild := false - for c := n.Parent.FirstChild; c != nil; c = c.NextSibling { - if c == n { - parentHasNAsAChild = true - break - } - } - if !parentHasNAsAChild { - return fmt.Errorf("html: inconsistent parent/child relationship") - } - } - - if n.PrevSibling != nil && n.PrevSibling.NextSibling != n { - return fmt.Errorf("html: inconsistent prev/next relationship") - } - if n.NextSibling != nil && n.NextSibling.PrevSibling != n { - return fmt.Errorf("html: inconsistent next/prev relationship") - } - - if (n.FirstChild == nil) != (n.LastChild == nil) { - return fmt.Errorf("html: inconsistent first/last relationship") - } - if n.FirstChild != nil && n.FirstChild == n.LastChild { - // We have a sole child. - if n.FirstChild.PrevSibling != nil || n.FirstChild.NextSibling != nil { - return fmt.Errorf("html: inconsistent sole child's sibling relationship") - } - } - - seen := map[*Node]bool{} - - var last *Node - for c := n.FirstChild; c != nil; c = c.NextSibling { - if seen[c] { - return fmt.Errorf("html: inconsistent repeated child") - } - seen[c] = true - last = c - } - if last != n.LastChild { - return fmt.Errorf("html: inconsistent last relationship") - } - - var first *Node - for c := n.LastChild; c != nil; c = c.PrevSibling { - if !seen[c] { - return fmt.Errorf("html: inconsistent missing child") - } - delete(seen, c) - first = c - } - if first != n.FirstChild { - return fmt.Errorf("html: inconsistent first relationship") - } - - if len(seen) != 0 { - return fmt.Errorf("html: inconsistent forwards/backwards child list") - } - - return nil -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/parse_test.go b/Godeps/_workspace/src/golang.org/x/net/html/parse_test.go deleted file mode 100644 index 7e47d11be8a..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/parse_test.go +++ /dev/null @@ -1,388 +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 html - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "sort" - "strings" - "testing" - - "golang.org/x/net/html/atom" -) - -// readParseTest reads a single test case from r. -func readParseTest(r *bufio.Reader) (text, want, context string, err error) { - line, err := r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - var b []byte - - // Read the HTML. - if string(line) != "#data\n" { - return "", "", "", fmt.Errorf(`got %q want "#data\n"`, line) - } - for { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - if line[0] == '#' { - break - } - b = append(b, line...) - } - text = strings.TrimSuffix(string(b), "\n") - b = b[:0] - - // Skip the error list. - if string(line) != "#errors\n" { - return "", "", "", fmt.Errorf(`got %q want "#errors\n"`, line) - } - for { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - if line[0] == '#' { - break - } - } - - if string(line) == "#document-fragment\n" { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - context = strings.TrimSpace(string(line)) - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - } - - // Read the dump of what the parse tree should be. - if string(line) != "#document\n" { - return "", "", "", fmt.Errorf(`got %q want "#document\n"`, line) - } - inQuote := false - for { - line, err = r.ReadSlice('\n') - if err != nil && err != io.EOF { - return "", "", "", err - } - trimmed := bytes.Trim(line, "| \n") - if len(trimmed) > 0 { - if line[0] == '|' && trimmed[0] == '"' { - inQuote = true - } - if trimmed[len(trimmed)-1] == '"' && !(line[0] == '|' && len(trimmed) == 1) { - inQuote = false - } - } - if len(line) == 0 || len(line) == 1 && line[0] == '\n' && !inQuote { - break - } - b = append(b, line...) - } - return text, string(b), context, nil -} - -func dumpIndent(w io.Writer, level int) { - io.WriteString(w, "| ") - for i := 0; i < level; i++ { - io.WriteString(w, " ") - } -} - -type sortedAttributes []Attribute - -func (a sortedAttributes) Len() int { - return len(a) -} - -func (a sortedAttributes) Less(i, j int) bool { - if a[i].Namespace != a[j].Namespace { - return a[i].Namespace < a[j].Namespace - } - return a[i].Key < a[j].Key -} - -func (a sortedAttributes) Swap(i, j int) { - a[i], a[j] = a[j], a[i] -} - -func dumpLevel(w io.Writer, n *Node, level int) error { - dumpIndent(w, level) - switch n.Type { - case ErrorNode: - return errors.New("unexpected ErrorNode") - case DocumentNode: - return errors.New("unexpected DocumentNode") - case ElementNode: - if n.Namespace != "" { - fmt.Fprintf(w, "<%s %s>", n.Namespace, n.Data) - } else { - fmt.Fprintf(w, "<%s>", n.Data) - } - attr := sortedAttributes(n.Attr) - sort.Sort(attr) - for _, a := range attr { - io.WriteString(w, "\n") - dumpIndent(w, level+1) - if a.Namespace != "" { - fmt.Fprintf(w, `%s %s="%s"`, a.Namespace, a.Key, a.Val) - } else { - fmt.Fprintf(w, `%s="%s"`, a.Key, a.Val) - } - } - case TextNode: - fmt.Fprintf(w, `"%s"`, n.Data) - case CommentNode: - fmt.Fprintf(w, "", n.Data) - case DoctypeNode: - fmt.Fprintf(w, "") - case scopeMarkerNode: - return errors.New("unexpected scopeMarkerNode") - default: - return errors.New("unknown node type") - } - io.WriteString(w, "\n") - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := dumpLevel(w, c, level+1); err != nil { - return err - } - } - return nil -} - -func dump(n *Node) (string, error) { - if n == nil || n.FirstChild == nil { - return "", nil - } - var b bytes.Buffer - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := dumpLevel(&b, c, 0); err != nil { - return "", err - } - } - return b.String(), nil -} - -const testDataDir = "testdata/webkit/" - -func TestParser(t *testing.T) { - testFiles, err := filepath.Glob(testDataDir + "*.dat") - if err != nil { - t.Fatal(err) - } - for _, tf := range testFiles { - f, err := os.Open(tf) - if err != nil { - t.Fatal(err) - } - defer f.Close() - r := bufio.NewReader(f) - - for i := 0; ; i++ { - text, want, context, err := readParseTest(r) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - - err = testParseCase(text, want, context) - - if err != nil { - t.Errorf("%s test #%d %q, %s", tf, i, text, err) - } - } - } -} - -// testParseCase tests one test case from the test files. If the test does not -// pass, it returns an error that explains the failure. -// text is the HTML to be parsed, want is a dump of the correct parse tree, -// and context is the name of the context node, if any. -func testParseCase(text, want, context string) (err error) { - defer func() { - if x := recover(); x != nil { - switch e := x.(type) { - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - } - }() - - var doc *Node - if context == "" { - doc, err = Parse(strings.NewReader(text)) - if err != nil { - return err - } - } else { - contextNode := &Node{ - Type: ElementNode, - DataAtom: atom.Lookup([]byte(context)), - Data: context, - } - nodes, err := ParseFragment(strings.NewReader(text), contextNode) - if err != nil { - return err - } - doc = &Node{ - Type: DocumentNode, - } - for _, n := range nodes { - doc.AppendChild(n) - } - } - - if err := checkTreeConsistency(doc); err != nil { - return err - } - - got, err := dump(doc) - if err != nil { - return err - } - // Compare the parsed tree to the #document section. - if got != want { - return fmt.Errorf("got vs want:\n----\n%s----\n%s----", got, want) - } - - if renderTestBlacklist[text] || context != "" { - return nil - } - - // Check that rendering and re-parsing results in an identical tree. - pr, pw := io.Pipe() - go func() { - pw.CloseWithError(Render(pw, doc)) - }() - doc1, err := Parse(pr) - if err != nil { - return err - } - got1, err := dump(doc1) - if err != nil { - return err - } - if got != got1 { - return fmt.Errorf("got vs got1:\n----\n%s----\n%s----", got, got1) - } - - return nil -} - -// Some test input result in parse trees are not 'well-formed' despite -// following the HTML5 recovery algorithms. Rendering and re-parsing such a -// tree will not result in an exact clone of that tree. We blacklist such -// inputs from the render test. -var renderTestBlacklist = map[string]bool{ - // The second will be reparented to the first 's parent. This - // results in an whose parent is an , which is not 'well-formed'. - `
    XCY`: true, - // The same thing with a

    : - `

    `: true, - // More cases of being reparented: - `aba
    brx
    aoe`: true, - `

    `: true, - `
    `: true, - // A similar reparenting situation involving : - `123`: true, - // A element is reparented, putting it before a table. - // A <plaintext> element can't have anything after it in HTML. - `<table><plaintext><td>`: true, - `<!doctype html><table><plaintext></plaintext>`: true, - `<!doctype html><table><tbody><plaintext></plaintext>`: true, - `<!doctype html><table><tbody><tr><plaintext></plaintext>`: true, - // A form inside a table inside a form doesn't work either. - `<!doctype html><form><table></form><form></table></form>`: true, - // A script that ends at EOF may escape its own closing tag when rendered. - `<!doctype html><script><!--<script `: true, - `<!doctype html><script><!--<script <`: true, - `<!doctype html><script><!--<script <a`: true, - `<!doctype html><script><!--<script </`: true, - `<!doctype html><script><!--<script </s`: true, - `<!doctype html><script><!--<script </script`: true, - `<!doctype html><script><!--<script </scripta`: true, - `<!doctype html><script><!--<script -`: true, - `<!doctype html><script><!--<script -a`: true, - `<!doctype html><script><!--<script -<`: true, - `<!doctype html><script><!--<script --`: true, - `<!doctype html><script><!--<script --a`: true, - `<!doctype html><script><!--<script --<`: true, - `<script><!--<script `: true, - `<script><!--<script <a`: true, - `<script><!--<script </script`: true, - `<script><!--<script </scripta`: true, - `<script><!--<script -`: true, - `<script><!--<script -a`: true, - `<script><!--<script --`: true, - `<script><!--<script --a`: true, - `<script><!--<script <`: true, - `<script><!--<script </`: true, - `<script><!--<script </s`: true, - // Reconstructing the active formatting elements results in a <plaintext> - // element that contains an <a> element. - `<!doctype html><p><a><plaintext>b`: true, -} - -func TestNodeConsistency(t *testing.T) { - // inconsistentNode is a Node whose DataAtom and Data do not agree. - inconsistentNode := &Node{ - Type: ElementNode, - DataAtom: atom.Frameset, - Data: "table", - } - _, err := ParseFragment(strings.NewReader("<p>hello</p>"), inconsistentNode) - if err == nil { - t.Errorf("got nil error, want non-nil") - } -} - -func BenchmarkParser(b *testing.B) { - buf, err := ioutil.ReadFile("testdata/go1.html") - if err != nil { - b.Fatalf("could not read testdata/go1.html: %v", err) - } - b.SetBytes(int64(len(buf))) - runtime.GC() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - Parse(bytes.NewBuffer(buf)) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/render_test.go b/Godeps/_workspace/src/golang.org/x/net/html/render_test.go deleted file mode 100644 index 11da54b313e..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/render_test.go +++ /dev/null @@ -1,156 +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 html - -import ( - "bytes" - "testing" -) - -func TestRenderer(t *testing.T) { - nodes := [...]*Node{ - 0: { - Type: ElementNode, - Data: "html", - }, - 1: { - Type: ElementNode, - Data: "head", - }, - 2: { - Type: ElementNode, - Data: "body", - }, - 3: { - Type: TextNode, - Data: "0<1", - }, - 4: { - Type: ElementNode, - Data: "p", - Attr: []Attribute{ - { - Key: "id", - Val: "A", - }, - { - Key: "foo", - Val: `abc"def`, - }, - }, - }, - 5: { - Type: TextNode, - Data: "2", - }, - 6: { - Type: ElementNode, - Data: "b", - Attr: []Attribute{ - { - Key: "empty", - Val: "", - }, - }, - }, - 7: { - Type: TextNode, - Data: "3", - }, - 8: { - Type: ElementNode, - Data: "i", - Attr: []Attribute{ - { - Key: "backslash", - Val: `\`, - }, - }, - }, - 9: { - Type: TextNode, - Data: "&4", - }, - 10: { - Type: TextNode, - Data: "5", - }, - 11: { - Type: ElementNode, - Data: "blockquote", - }, - 12: { - Type: ElementNode, - Data: "br", - }, - 13: { - Type: TextNode, - Data: "6", - }, - } - - // Build a tree out of those nodes, based on a textual representation. - // Only the ".\t"s are significant. The trailing HTML-like text is - // just commentary. The "0:" prefixes are for easy cross-reference with - // the nodes array. - treeAsText := [...]string{ - 0: `<html>`, - 1: `. <head>`, - 2: `. <body>`, - 3: `. . "0&lt;1"`, - 4: `. . <p id="A" foo="abc&#34;def">`, - 5: `. . . "2"`, - 6: `. . . <b empty="">`, - 7: `. . . . "3"`, - 8: `. . . <i backslash="\">`, - 9: `. . . . "&amp;4"`, - 10: `. . "5"`, - 11: `. . <blockquote>`, - 12: `. . <br>`, - 13: `. . "6"`, - } - if len(nodes) != len(treeAsText) { - t.Fatal("len(nodes) != len(treeAsText)") - } - var stack [8]*Node - for i, line := range treeAsText { - level := 0 - for line[0] == '.' { - // Strip a leading ".\t". - line = line[2:] - level++ - } - n := nodes[i] - if level == 0 { - if stack[0] != nil { - t.Fatal("multiple root nodes") - } - stack[0] = n - } else { - stack[level-1].AppendChild(n) - stack[level] = n - for i := level + 1; i < len(stack); i++ { - stack[i] = nil - } - } - // At each stage of tree construction, we check all nodes for consistency. - for j, m := range nodes { - if err := checkNodeConsistency(m); err != nil { - t.Fatalf("i=%d, j=%d: %v", i, j, err) - } - } - } - - want := `<html><head></head><body>0&lt;1<p id="A" foo="abc&#34;def">` + - `2<b empty="">3</b><i backslash="\">&amp;4</i></p>` + - `5<blockquote></blockquote><br/>6</body></html>` - b := new(bytes.Buffer) - if err := Render(b, nodes[0]); err != nil { - t.Fatal(err) - } - if got := b.String(); got != want { - t.Errorf("got vs want:\n%s\n%s\n", got, want) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/go1.html b/Godeps/_workspace/src/golang.org/x/net/html/testdata/go1.html deleted file mode 100644 index a782cc71d20..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/go1.html +++ /dev/null @@ -1,2237 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - - <title>Go 1 Release Notes - The Go Programming Language</title> - -<link type="text/css" rel="stylesheet" href="/doc/style.css"> -<script type="text/javascript" src="/doc/godocs.js"></script> - -<link rel="search" type="application/opensearchdescription+xml" title="godoc" href="/opensearch.xml" /> - -<script type="text/javascript"> -var _gaq = _gaq || []; -_gaq.push(["_setAccount", "UA-11222381-2"]); -_gaq.push(["_trackPageview"]); -</script> -</head> -<body> - -<div id="topbar"><div class="container wide"> - -<form method="GET" action="/search"> -<div id="menu"> -<a href="/doc/">Documents</a> -<a href="/ref/">References</a> -<a href="/pkg/">Packages</a> -<a href="/project/">The Project</a> -<a href="/help/">Help</a> -<input type="text" id="search" name="q" class="inactive" value="Search"> -</div> -<div id="heading"><a href="/">The Go Programming Language</a></div> -</form> - -</div></div> - -<div id="page" class="wide"> - - - <div id="plusone"><g:plusone size="small" annotation="none"></g:plusone></div> - <h1>Go 1 Release Notes</h1> - - - - -<div id="nav"></div> - - - - -<h2 id="introduction">Introduction to Go 1</h2> - -<p> -Go version 1, Go 1 for short, defines a language and a set of core libraries -that provide a stable foundation for creating reliable products, projects, and -publications. -</p> - -<p> -The driving motivation for Go 1 is stability for its users. People should be able to -write Go programs and expect that they will continue to compile and run without -change, on a time scale of years, including in production environments such as -Google App Engine. Similarly, people should be able to write books about Go, be -able to say which version of Go the book is describing, and have that version -number still be meaningful much later. -</p> - -<p> -Code that compiles in Go 1 should, with few exceptions, continue to compile and -run throughout the lifetime of that version, even as we issue updates and bug -fixes such as Go version 1.1, 1.2, and so on. Other than critical fixes, changes -made to the language and library for subsequent releases of Go 1 may -add functionality but will not break existing Go 1 programs. -<a href="go1compat.html">The Go 1 compatibility document</a> -explains the compatibility guidelines in more detail. -</p> - -<p> -Go 1 is a representation of Go as it used today, not a wholesale rethinking of -the language. We avoided designing new features and instead focused on cleaning -up problems and inconsistencies and improving portability. There are a number -changes to the Go language and packages that we had considered for some time and -prototyped but not released primarily because they are significant and -backwards-incompatible. Go 1 was an opportunity to get them out, which is -helpful for the long term, but also means that Go 1 introduces incompatibilities -for old programs. Fortunately, the <code>go</code> <code>fix</code> tool can -automate much of the work needed to bring programs up to the Go 1 standard. -</p> - -<p> -This document outlines the major changes in Go 1 that will affect programmers -updating existing code; its reference point is the prior release, r60 (tagged as -r60.3). It also explains how to update code from r60 to run under Go 1. -</p> - -<h2 id="language">Changes to the language</h2> - -<h3 id="append">Append</h3> - -<p> -The <code>append</code> predeclared variadic function makes it easy to grow a slice -by adding elements to the end. -A common use is to add bytes to the end of a byte slice when generating output. -However, <code>append</code> did not provide a way to append a string to a <code>[]byte</code>, -which is another common case. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/greeting := ..byte/` `/append.*hello/`}} ---> greeting := []byte{} - greeting = append(greeting, []byte(&#34;hello &#34;)...)</pre> - -<p> -By analogy with the similar property of <code>copy</code>, Go 1 -permits a string to be appended (byte-wise) directly to a byte -slice, reducing the friction between strings and byte slices. -The conversion is no longer necessary: -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/append.*world/`}} ---> greeting = append(greeting, &#34;world&#34;...)</pre> - -<p> -<em>Updating</em>: -This is a new feature, so existing code needs no changes. -</p> - -<h3 id="close">Close</h3> - -<p> -The <code>close</code> predeclared function provides a mechanism -for a sender to signal that no more values will be sent. -It is important to the implementation of <code>for</code> <code>range</code> -loops over channels and is helpful in other situations. -Partly by design and partly because of race conditions that can occur otherwise, -it is intended for use only by the goroutine sending on the channel, -not by the goroutine receiving data. -However, before Go 1 there was no compile-time checking that <code>close</code> -was being used correctly. -</p> - -<p> -To close this gap, at least in part, Go 1 disallows <code>close</code> on receive-only channels. -Attempting to close such a channel is a compile-time error. -</p> - -<pre> - var c chan int - var csend chan&lt;- int = c - var crecv &lt;-chan int = c - close(c) // legal - close(csend) // legal - close(crecv) // illegal -</pre> - -<p> -<em>Updating</em>: -Existing code that attempts to close a receive-only channel was -erroneous even before Go 1 and should be fixed. The compiler will -now reject such code. -</p> - -<h3 id="literals">Composite literals</h3> - -<p> -In Go 1, a composite literal of array, slice, or map type can elide the -type specification for the elements' initializers if they are of pointer type. -All four of the initializations in this example are legal; the last one was illegal before Go 1. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/type Date struct/` `/STOP/`}} ---> type Date struct { - month string - day int - } - <span class="comment">// Struct values, fully qualified; always legal.</span> - holiday1 := []Date{ - Date{&#34;Feb&#34;, 14}, - Date{&#34;Nov&#34;, 11}, - Date{&#34;Dec&#34;, 25}, - } - <span class="comment">// Struct values, type name elided; always legal.</span> - holiday2 := []Date{ - {&#34;Feb&#34;, 14}, - {&#34;Nov&#34;, 11}, - {&#34;Dec&#34;, 25}, - } - <span class="comment">// Pointers, fully qualified, always legal.</span> - holiday3 := []*Date{ - &amp;Date{&#34;Feb&#34;, 14}, - &amp;Date{&#34;Nov&#34;, 11}, - &amp;Date{&#34;Dec&#34;, 25}, - } - <span class="comment">// Pointers, type name elided; legal in Go 1.</span> - holiday4 := []*Date{ - {&#34;Feb&#34;, 14}, - {&#34;Nov&#34;, 11}, - {&#34;Dec&#34;, 25}, - }</pre> - -<p> -<em>Updating</em>: -This change has no effect on existing code, but the command -<code>gofmt</code> <code>-s</code> applied to existing source -will, among other things, elide explicit element types wherever permitted. -</p> - - -<h3 id="init">Goroutines during init</h3> - -<p> -The old language defined that <code>go</code> statements executed during initialization created goroutines but that they did not begin to run until initialization of the entire program was complete. -This introduced clumsiness in many places and, in effect, limited the utility -of the <code>init</code> construct: -if it was possible for another package to use the library during initialization, the library -was forced to avoid goroutines. -This design was done for reasons of simplicity and safety but, -as our confidence in the language grew, it seemed unnecessary. -Running goroutines during initialization is no more complex or unsafe than running them during normal execution. -</p> - -<p> -In Go 1, code that uses goroutines can be called from -<code>init</code> routines and global initialization expressions -without introducing a deadlock. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/PackageGlobal/` `/^}/`}} --->var PackageGlobal int - -func init() { - c := make(chan int) - go initializationFunction(c) - PackageGlobal = &lt;-c -}</pre> - -<p> -<em>Updating</em>: -This is a new feature, so existing code needs no changes, -although it's possible that code that depends on goroutines not starting before <code>main</code> will break. -There was no such code in the standard repository. -</p> - -<h3 id="rune">The rune type</h3> - -<p> -The language spec allows the <code>int</code> type to be 32 or 64 bits wide, but current implementations set <code>int</code> to 32 bits even on 64-bit platforms. -It would be preferable to have <code>int</code> be 64 bits on 64-bit platforms. -(There are important consequences for indexing large slices.) -However, this change would waste space when processing Unicode characters with -the old language because the <code>int</code> type was also used to hold Unicode code points: each code point would waste an extra 32 bits of storage if <code>int</code> grew from 32 bits to 64. -</p> - -<p> -To make changing to 64-bit <code>int</code> feasible, -Go 1 introduces a new basic type, <code>rune</code>, to represent -individual Unicode code points. -It is an alias for <code>int32</code>, analogous to <code>byte</code> -as an alias for <code>uint8</code>. -</p> - -<p> -Character literals such as <code>'a'</code>, <code>'語'</code>, and <code>'\u0345'</code> -now have default type <code>rune</code>, -analogous to <code>1.0</code> having default type <code>float64</code>. -A variable initialized to a character constant will therefore -have type <code>rune</code> unless otherwise specified. -</p> - -<p> -Libraries have been updated to use <code>rune</code> rather than <code>int</code> -when appropriate. For instance, the functions <code>unicode.ToLower</code> and -relatives now take and return a <code>rune</code>. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/STARTRUNE/` `/ENDRUNE/`}} ---> delta := &#39;δ&#39; <span class="comment">// delta has type rune.</span> - var DELTA rune - DELTA = unicode.ToUpper(delta) - epsilon := unicode.ToLower(DELTA + 1) - if epsilon != &#39;δ&#39;+1 { - log.Fatal(&#34;inconsistent casing for Greek&#34;) - }</pre> - -<p> -<em>Updating</em>: -Most source code will be unaffected by this because the type inference from -<code>:=</code> initializers introduces the new type silently, and it propagates -from there. -Some code may get type errors that a trivial conversion will resolve. -</p> - -<h3 id="error">The error type</h3> - -<p> -Go 1 introduces a new built-in type, <code>error</code>, which has the following definition: -</p> - -<pre> - type error interface { - Error() string - } -</pre> - -<p> -Since the consequences of this type are all in the package library, -it is discussed <a href="#errors">below</a>. -</p> - -<h3 id="delete">Deleting from maps</h3> - -<p> -In the old language, to delete the entry with key <code>k</code> from map <code>m</code>, one wrote the statement, -</p> - -<pre> - m[k] = value, false -</pre> - -<p> -This syntax was a peculiar special case, the only two-to-one assignment. -It required passing a value (usually ignored) that is evaluated but discarded, -plus a boolean that was nearly always the constant <code>false</code>. -It did the job but was odd and a point of contention. -</p> - -<p> -In Go 1, that syntax has gone; instead there is a new built-in -function, <code>delete</code>. The call -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/delete\(m, k\)/`}} ---> delete(m, k)</pre> - -<p> -will delete the map entry retrieved by the expression <code>m[k]</code>. -There is no return value. Deleting a non-existent entry is a no-op. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will convert expressions of the form <code>m[k] = value, -false</code> into <code>delete(m, k)</code> when it is clear that -the ignored value can be safely discarded from the program and -<code>false</code> refers to the predefined boolean constant. -The fix tool -will flag other uses of the syntax for inspection by the programmer. -</p> - -<h3 id="iteration">Iterating in maps</h3> - -<p> -The old language specification did not define the order of iteration for maps, -and in practice it differed across hardware platforms. -This caused tests that iterated over maps to be fragile and non-portable, with the -unpleasant property that a test might always pass on one machine but break on another. -</p> - -<p> -In Go 1, the order in which elements are visited when iterating -over a map using a <code>for</code> <code>range</code> statement -is defined to be unpredictable, even if the same loop is run multiple -times with the same map. -Code should not assume that the elements are visited in any particular order. -</p> - -<p> -This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. -Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a map. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/Sunday/` `/^ }/`}} ---> m := map[string]int{&#34;Sunday&#34;: 0, &#34;Monday&#34;: 1} - for name, value := range m { - <span class="comment">// This loop should not assume Sunday will be visited first.</span> - f(name, value) - }</pre> - -<p> -<em>Updating</em>: -This is one change where tools cannot help. Most existing code -will be unaffected, but some programs may break or misbehave; we -recommend manual checking of all range statements over maps to -verify they do not depend on iteration order. There were a few such -examples in the standard repository; they have been fixed. -Note that it was already incorrect to depend on the iteration order, which -was unspecified. This change codifies the unpredictability. -</p> - -<h3 id="multiple_assignment">Multiple assignment</h3> - -<p> -The language specification has long guaranteed that in assignments -the right-hand-side expressions are all evaluated before any left-hand-side expressions are assigned. -To guarantee predictable behavior, -Go 1 refines the specification further. -</p> - -<p> -If the left-hand side of the assignment -statement contains expressions that require evaluation, such as -function calls or array indexing operations, these will all be done -using the usual left-to-right rule before any variables are assigned -their value. Once everything is evaluated, the actual assignments -proceed in left-to-right order. -</p> - -<p> -These examples illustrate the behavior. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/sa :=/` `/then sc.0. = 2/`}} ---> sa := []int{1, 2, 3} - i := 0 - i, sa[i] = 1, 2 <span class="comment">// sets i = 1, sa[0] = 2</span> - - sb := []int{1, 2, 3} - j := 0 - sb[j], j = 2, 1 <span class="comment">// sets sb[0] = 2, j = 1</span> - - sc := []int{1, 2, 3} - sc[0], sc[0] = 1, 2 <span class="comment">// sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end)</span></pre> - -<p> -<em>Updating</em>: -This is one change where tools cannot help, but breakage is unlikely. -No code in the standard repository was broken by this change, and code -that depended on the previous unspecified behavior was already incorrect. -</p> - -<h3 id="shadowing">Returns and shadowed variables</h3> - -<p> -A common mistake is to use <code>return</code> (without arguments) after an assignment to a variable that has the same name as a result variable but is not the same variable. -This situation is called <em>shadowing</em>: the result variable has been shadowed by another variable with the same name declared in an inner scope. -</p> - -<p> -In functions with named return values, -the Go 1 compilers disallow return statements without arguments if any of the named return values is shadowed at the point of the return statement. -(It isn't part of the specification, because this is one area we are still exploring; -the situation is analogous to the compilers rejecting functions that do not end with an explicit return statement.) -</p> - -<p> -This function implicitly returns a shadowed return value and will be rejected by the compiler: -</p> - -<pre> - func Bug() (i, j, k int) { - for i = 0; i &lt; 5; i++ { - for j := 0; j &lt; 5; j++ { // Redeclares j. - k += i*j - if k > 100 { - return // Rejected: j is shadowed here. - } - } - } - return // OK: j is not shadowed here. - } -</pre> - -<p> -<em>Updating</em>: -Code that shadows return values in this way will be rejected by the compiler and will need to be fixed by hand. -The few cases that arose in the standard repository were mostly bugs. -</p> - -<h3 id="unexported">Copying structs with unexported fields</h3> - -<p> -The old language did not allow a package to make a copy of a struct value containing unexported fields belonging to a different package. -There was, however, a required exception for a method receiver; -also, the implementations of <code>copy</code> and <code>append</code> have never honored the restriction. -</p> - -<p> -Go 1 will allow packages to copy struct values containing unexported fields from other packages. -Besides resolving the inconsistency, -this change admits a new kind of API: a package can return an opaque value without resorting to a pointer or interface. -The new implementations of <code>time.Time</code> and -<code>reflect.Value</code> are examples of types taking advantage of this new property. -</p> - -<p> -As an example, if package <code>p</code> includes the definitions, -</p> - -<pre> - type Struct struct { - Public int - secret int - } - func NewStruct(a int) Struct { // Note: not a pointer. - return Struct{a, f(a)} - } - func (s Struct) String() string { - return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret) - } -</pre> - -<p> -a package that imports <code>p</code> can assign and copy values of type -<code>p.Struct</code> at will. -Behind the scenes the unexported fields will be assigned and copied just -as if they were exported, -but the client code will never be aware of them. The code -</p> - -<pre> - import "p" - - myStruct := p.NewStruct(23) - copyOfMyStruct := myStruct - fmt.Println(myStruct, copyOfMyStruct) -</pre> - -<p> -will show that the secret field of the struct has been copied to the new value. -</p> - -<p> -<em>Updating</em>: -This is a new feature, so existing code needs no changes. -</p> - -<h3 id="equality">Equality</h3> - -<p> -Before Go 1, the language did not define equality on struct and array values. -This meant, -among other things, that structs and arrays could not be used as map keys. -On the other hand, Go did define equality on function and map values. -Function equality was problematic in the presence of closures -(when are two closures equal?) -while map equality compared pointers, not the maps' content, which was usually -not what the user would want. -</p> - -<p> -Go 1 addressed these issues. -First, structs and arrays can be compared for equality and inequality -(<code>==</code> and <code>!=</code>), -and therefore be used as map keys, -provided they are composed from elements for which equality is also defined, -using element-wise comparison. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/type Day struct/` `/Printf/`}} ---> type Day struct { - long string - short string - } - Christmas := Day{&#34;Christmas&#34;, &#34;XMas&#34;} - Thanksgiving := Day{&#34;Thanksgiving&#34;, &#34;Turkey&#34;} - holiday := map[Day]bool{ - Christmas: true, - Thanksgiving: true, - } - fmt.Printf(&#34;Christmas is a holiday: %t\n&#34;, holiday[Christmas])</pre> - -<p> -Second, Go 1 removes the definition of equality for function values, -except for comparison with <code>nil</code>. -Finally, map equality is gone too, also except for comparison with <code>nil</code>. -</p> - -<p> -Note that equality is still undefined for slices, for which the -calculation is in general infeasible. Also note that the ordered -comparison operators (<code>&lt;</code> <code>&lt;=</code> -<code>&gt;</code> <code>&gt;=</code>) are still undefined for -structs and arrays. - -<p> -<em>Updating</em>: -Struct and array equality is a new feature, so existing code needs no changes. -Existing code that depends on function or map equality will be -rejected by the compiler and will need to be fixed by hand. -Few programs will be affected, but the fix may require some -redesign. -</p> - -<h2 id="packages">The package hierarchy</h2> - -<p> -Go 1 addresses many deficiencies in the old standard library and -cleans up a number of packages, making them more internally consistent -and portable. -</p> - -<p> -This section describes how the packages have been rearranged in Go 1. -Some have moved, some have been renamed, some have been deleted. -New packages are described in later sections. -</p> - -<h3 id="hierarchy">The package hierarchy</h3> - -<p> -Go 1 has a rearranged package hierarchy that groups related items -into subdirectories. For instance, <code>utf8</code> and -<code>utf16</code> now occupy subdirectories of <code>unicode</code>. -Also, <a href="#subrepo">some packages</a> have moved into -subrepositories of -<a href="http://code.google.com/p/go"><code>code.google.com/p/go</code></a> -while <a href="#deleted">others</a> have been deleted outright. -</p> - -<table class="codetable" frame="border" summary="Moved packages"> -<colgroup align="left" width="60%"></colgroup> -<colgroup align="left" width="40%"></colgroup> -<tr> -<th align="left">Old path</th> -<th align="left">New path</th> -</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>asn1</td> <td>encoding/asn1</td></tr> -<tr><td>csv</td> <td>encoding/csv</td></tr> -<tr><td>gob</td> <td>encoding/gob</td></tr> -<tr><td>json</td> <td>encoding/json</td></tr> -<tr><td>xml</td> <td>encoding/xml</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>exp/template/html</td> <td>html/template</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>big</td> <td>math/big</td></tr> -<tr><td>cmath</td> <td>math/cmplx</td></tr> -<tr><td>rand</td> <td>math/rand</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>http</td> <td>net/http</td></tr> -<tr><td>http/cgi</td> <td>net/http/cgi</td></tr> -<tr><td>http/fcgi</td> <td>net/http/fcgi</td></tr> -<tr><td>http/httptest</td> <td>net/http/httptest</td></tr> -<tr><td>http/pprof</td> <td>net/http/pprof</td></tr> -<tr><td>mail</td> <td>net/mail</td></tr> -<tr><td>rpc</td> <td>net/rpc</td></tr> -<tr><td>rpc/jsonrpc</td> <td>net/rpc/jsonrpc</td></tr> -<tr><td>smtp</td> <td>net/smtp</td></tr> -<tr><td>url</td> <td>net/url</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>exec</td> <td>os/exec</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>scanner</td> <td>text/scanner</td></tr> -<tr><td>tabwriter</td> <td>text/tabwriter</td></tr> -<tr><td>template</td> <td>text/template</td></tr> -<tr><td>template/parse</td> <td>text/template/parse</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>utf8</td> <td>unicode/utf8</td></tr> -<tr><td>utf16</td> <td>unicode/utf16</td></tr> -</table> - -<p> -Note that the package names for the old <code>cmath</code> and -<code>exp/template/html</code> packages have changed to <code>cmplx</code> -and <code>template</code>. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update all imports and package renames for packages that -remain inside the standard repository. Programs that import packages -that are no longer in the standard repository will need to be edited -by hand. -</p> - -<h3 id="exp">The package tree exp</h3> - -<p> -Because they are not standardized, the packages under the <code>exp</code> directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form -in <a href="http://code.google.com/p/go/">the repository</a> for -developers who wish to use them. -</p> - -<p> -Several packages have moved under <code>exp</code> at the time of Go 1's release: -</p> - -<ul> -<li><code>ebnf</code></li> -<li><code>html</code><sup>&#8224;</sup></li> -<li><code>go/types</code></li> -</ul> - -<p> -(<sup>&#8224;</sup>The <code>EscapeString</code> and <code>UnescapeString</code> types remain -in package <code>html</code>.) -</p> - -<p> -All these packages are available under the same names, with the prefix <code>exp/</code>: <code>exp/ebnf</code> etc. -</p> - -<p> -Also, the <code>utf8.String</code> type has been moved to its own package, <code>exp/utf8string</code>. -</p> - -<p> -Finally, the <code>gotype</code> command now resides in <code>exp/gotype</code>, while -<code>ebnflint</code> is now in <code>exp/ebnflint</code>. -If they are installed, they now reside in <code>$GOROOT/bin/tool</code>. -</p> - -<p> -<em>Updating</em>: -Code that uses packages in <code>exp</code> will need to be updated by hand, -or else compiled from an installation that has <code>exp</code> available. -The <code>go</code> <code>fix</code> tool or the compiler will complain about such uses. -</p> - -<h3 id="old">The package tree old</h3> - -<p> -Because they are deprecated, the packages under the <code>old</code> directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form for -developers who wish to use them. -</p> - -<p> -The packages in their new locations are: -</p> - -<ul> -<li><code>old/netchan</code></li> -<li><code>old/regexp</code></li> -<li><code>old/template</code></li> -</ul> - -<p> -<em>Updating</em>: -Code that uses packages now in <code>old</code> will need to be updated by hand, -or else compiled from an installation that has <code>old</code> available. -The <code>go</code> <code>fix</code> tool will warn about such uses. -</p> - -<h3 id="deleted">Deleted packages</h3> - -<p> -Go 1 deletes several packages outright: -</p> - -<ul> -<li><code>container/vector</code></li> -<li><code>exp/datafmt</code></li> -<li><code>go/typechecker</code></li> -<li><code>try</code></li> -</ul> - -<p> -and also the command <code>gotry</code>. -</p> - -<p> -<em>Updating</em>: -Code that uses <code>container/vector</code> should be updated to use -slices directly. See -<a href="http://code.google.com/p/go-wiki/wiki/SliceTricks">the Go -Language Community Wiki</a> for some suggestions. -Code that uses the other packages (there should be almost zero) will need to be rethought. -</p> - -<h3 id="subrepo">Packages moving to subrepositories</h3> - -<p> -Go 1 has moved a number of packages into other repositories, usually sub-repositories of -<a href="http://code.google.com/p/go/">the main Go repository</a>. -This table lists the old and new import paths: - -<table class="codetable" frame="border" summary="Sub-repositories"> -<colgroup align="left" width="40%"></colgroup> -<colgroup align="left" width="60%"></colgroup> -<tr> -<th align="left">Old</th> -<th align="left">New</th> -</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>crypto/bcrypt</td> <td>code.google.com/p/go.crypto/bcrypt</tr> -<tr><td>crypto/blowfish</td> <td>code.google.com/p/go.crypto/blowfish</tr> -<tr><td>crypto/cast5</td> <td>code.google.com/p/go.crypto/cast5</tr> -<tr><td>crypto/md4</td> <td>code.google.com/p/go.crypto/md4</tr> -<tr><td>crypto/ocsp</td> <td>code.google.com/p/go.crypto/ocsp</tr> -<tr><td>crypto/openpgp</td> <td>code.google.com/p/go.crypto/openpgp</tr> -<tr><td>crypto/openpgp/armor</td> <td>code.google.com/p/go.crypto/openpgp/armor</tr> -<tr><td>crypto/openpgp/elgamal</td> <td>code.google.com/p/go.crypto/openpgp/elgamal</tr> -<tr><td>crypto/openpgp/errors</td> <td>code.google.com/p/go.crypto/openpgp/errors</tr> -<tr><td>crypto/openpgp/packet</td> <td>code.google.com/p/go.crypto/openpgp/packet</tr> -<tr><td>crypto/openpgp/s2k</td> <td>code.google.com/p/go.crypto/openpgp/s2k</tr> -<tr><td>crypto/ripemd160</td> <td>code.google.com/p/go.crypto/ripemd160</tr> -<tr><td>crypto/twofish</td> <td>code.google.com/p/go.crypto/twofish</tr> -<tr><td>crypto/xtea</td> <td>code.google.com/p/go.crypto/xtea</tr> -<tr><td>exp/ssh</td> <td>code.google.com/p/go.crypto/ssh</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>image/bmp</td> <td>code.google.com/p/go.image/bmp</tr> -<tr><td>image/tiff</td> <td>code.google.com/p/go.image/tiff</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>net/dict</td> <td>code.google.com/p/go.net/dict</tr> -<tr><td>net/websocket</td> <td>code.google.com/p/go.net/websocket</tr> -<tr><td>exp/spdy</td> <td>code.google.com/p/go.net/spdy</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>encoding/git85</td> <td>code.google.com/p/go.codereview/git85</tr> -<tr><td>patch</td> <td>code.google.com/p/go.codereview/patch</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>exp/wingui</td> <td>code.google.com/p/gowingui</tr> -</table> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update imports of these packages to use the new import paths. -Installations that depend on these packages will need to install them using -a <code>go get</code> command. -</p> - -<h2 id="major">Major changes to the library</h2> - -<p> -This section describes significant changes to the core libraries, the ones that -affect the most programs. -</p> - -<h3 id="errors">The error type and errors package</h3> - -<p> -The placement of <code>os.Error</code> in package <code>os</code> is mostly historical: errors first came up when implementing package <code>os</code>, and they seemed system-related at the time. -Since then it has become clear that errors are more fundamental than the operating system. For example, it would be nice to use <code>Errors</code> in packages that <code>os</code> depends on, like <code>syscall</code>. -Also, having <code>Error</code> in <code>os</code> introduces many dependencies on <code>os</code> that would otherwise not exist. -</p> - -<p> -Go 1 solves these problems by introducing a built-in <code>error</code> interface type and a separate <code>errors</code> package (analogous to <code>bytes</code> and <code>strings</code>) that contains utility functions. -It replaces <code>os.NewError</code> with -<a href="/pkg/errors/#New"><code>errors.New</code></a>, -giving errors a more central place in the environment. -</p> - -<p> -So the widely-used <code>String</code> method does not cause accidental satisfaction -of the <code>error</code> interface, the <code>error</code> interface uses instead -the name <code>Error</code> for that method: -</p> - -<pre> - type error interface { - Error() string - } -</pre> - -<p> -The <code>fmt</code> library automatically invokes <code>Error</code>, as it already -does for <code>String</code>, for easy printing of error values. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/START ERROR EXAMPLE/` `/END ERROR EXAMPLE/`}} --->type SyntaxError struct { - File string - Line int - Message string -} - -func (se *SyntaxError) Error() string { - return fmt.Sprintf(&#34;%s:%d: %s&#34;, se.File, se.Line, se.Message) -}</pre> - -<p> -All standard packages have been updated to use the new interface; the old <code>os.Error</code> is gone. -</p> - -<p> -A new package, <a href="/pkg/errors/"><code>errors</code></a>, contains the function -</p> - -<pre> -func New(text string) error -</pre> - -<p> -to turn a string into an error. It replaces the old <code>os.NewError</code>. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/ErrSyntax/`}} ---> var ErrSyntax = errors.New(&#34;syntax error&#34;)</pre> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update almost all code affected by the change. -Code that defines error types with a <code>String</code> method will need to be updated -by hand to rename the methods to <code>Error</code>. -</p> - -<h3 id="errno">System call errors</h3> - -<p> -The old <code>syscall</code> package, which predated <code>os.Error</code> -(and just about everything else), -returned errors as <code>int</code> values. -In turn, the <code>os</code> package forwarded many of these errors, such -as <code>EINVAL</code>, but using a different set of errors on each platform. -This behavior was unpleasant and unportable. -</p> - -<p> -In Go 1, the -<a href="/pkg/syscall/"><code>syscall</code></a> -package instead returns an <code>error</code> for system call errors. -On Unix, the implementation is done by a -<a href="/pkg/syscall/#Errno"><code>syscall.Errno</code></a> type -that satisfies <code>error</code> and replaces the old <code>os.Errno</code>. -</p> - -<p> -The changes affecting <code>os.EINVAL</code> and relatives are -described <a href="#os">elsewhere</a>. - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update almost all code affected by the change. -Regardless, most code should use the <code>os</code> package -rather than <code>syscall</code> and so will be unaffected. -</p> - -<h3 id="time">Time</h3> - -<p> -Time is always a challenge to support well in a programming language. -The old Go <code>time</code> package had <code>int64</code> units, no -real type safety, -and no distinction between absolute times and durations. -</p> - -<p> -One of the most sweeping changes in the Go 1 library is therefore a -complete redesign of the -<a href="/pkg/time/"><code>time</code></a> package. -Instead of an integer number of nanoseconds as an <code>int64</code>, -and a separate <code>*time.Time</code> type to deal with human -units such as hours and years, -there are now two fundamental types: -<a href="/pkg/time/#Time"><code>time.Time</code></a> -(a value, so the <code>*</code> is gone), which represents a moment in time; -and <a href="/pkg/time/#Duration"><code>time.Duration</code></a>, -which represents an interval. -Both have nanosecond resolution. -A <code>Time</code> can represent any time into the ancient -past and remote future, while a <code>Duration</code> can -span plus or minus only about 290 years. -There are methods on these types, plus a number of helpful -predefined constant durations such as <code>time.Second</code>. -</p> - -<p> -Among the new methods are things like -<a href="/pkg/time/#Time.Add"><code>Time.Add</code></a>, -which adds a <code>Duration</code> to a <code>Time</code>, and -<a href="/pkg/time/#Time.Sub"><code>Time.Sub</code></a>, -which subtracts two <code>Times</code> to yield a <code>Duration</code>. -</p> - -<p> -The most important semantic change is that the Unix epoch (Jan 1, 1970) is now -relevant only for those functions and methods that mention Unix: -<a href="/pkg/time/#Unix"><code>time.Unix</code></a> -and the <a href="/pkg/time/#Time.Unix"><code>Unix</code></a> -and <a href="/pkg/time/#Time.UnixNano"><code>UnixNano</code></a> methods -of the <code>Time</code> type. -In particular, -<a href="/pkg/time/#Now"><code>time.Now</code></a> -returns a <code>time.Time</code> value rather than, in the old -API, an integer nanosecond count since the Unix epoch. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/sleepUntil/` `/^}/`}} ---><span class="comment">// sleepUntil sleeps until the specified time. It returns immediately if it&#39;s too late.</span> -func sleepUntil(wakeup time.Time) { - now := time.Now() <span class="comment">// A Time.</span> - if !wakeup.After(now) { - return - } - delta := wakeup.Sub(now) <span class="comment">// A Duration.</span> - fmt.Printf(&#34;Sleeping for %.3fs\n&#34;, delta.Seconds()) - time.Sleep(delta) -}</pre> - -<p> -The new types, methods, and constants have been propagated through -all the standard packages that use time, such as <code>os</code> and -its representation of file time stamps. -</p> - -<p> -<em>Updating</em>: -The <code>go</code> <code>fix</code> tool will update many uses of the old <code>time</code> package to use the new -types and methods, although it does not replace values such as <code>1e9</code> -representing nanoseconds per second. -Also, because of type changes in some of the values that arise, -some of the expressions rewritten by the fix tool may require -further hand editing; in such cases the rewrite will include -the correct function or method for the old functionality, but -may have the wrong type or require further analysis. -</p> - -<h2 id="minor">Minor changes to the library</h2> - -<p> -This section describes smaller changes, such as those to less commonly -used packages or that affect -few programs beyond the need to run <code>go</code> <code>fix</code>. -This category includes packages that are new in Go 1. -Collectively they improve portability, regularize behavior, and -make the interfaces more modern and Go-like. -</p> - -<h3 id="archive_zip">The archive/zip package</h3> - -<p> -In Go 1, <a href="/pkg/archive/zip/#Writer"><code>*zip.Writer</code></a> no -longer has a <code>Write</code> method. Its presence was a mistake. -</p> - -<p> -<em>Updating</em>: -What little code is affected will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="bufio">The bufio package</h3> - -<p> -In Go 1, <a href="/pkg/bufio/#NewReaderSize"><code>bufio.NewReaderSize</code></a> -and -<a href="/pkg/bufio/#NewWriterSize"><code>bufio.NewWriterSize</code></a> -functions no longer return an error for invalid sizes. -If the argument size is too small or invalid, it is adjusted. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="compress">The compress/flate, compress/gzip and compress/zlib packages</h3> - -<p> -In Go 1, the <code>NewWriterXxx</code> functions in -<a href="/pkg/compress/flate"><code>compress/flate</code></a>, -<a href="/pkg/compress/gzip"><code>compress/gzip</code></a> and -<a href="/pkg/compress/zlib"><code>compress/zlib</code></a> -all return <code>(*Writer, error)</code> if they take a compression level, -and <code>*Writer</code> otherwise. Package <code>gzip</code>'s -<code>Compressor</code> and <code>Decompressor</code> types have been renamed -to <code>Writer</code> and <code>Reader</code>. Package <code>flate</code>'s -<code>WrongValueError</code> type has been removed. -</p> - -<p> -<em>Updating</em> -Running <code>go</code> <code>fix</code> will update old names and calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="crypto_aes_des">The crypto/aes and crypto/des packages</h3> - -<p> -In Go 1, the <code>Reset</code> method has been removed. Go does not guarantee -that memory is not copied and therefore this method was misleading. -</p> - -<p> -The cipher-specific types <code>*aes.Cipher</code>, <code>*des.Cipher</code>, -and <code>*des.TripleDESCipher</code> have been removed in favor of -<code>cipher.Block</code>. -</p> - -<p> -<em>Updating</em>: -Remove the calls to Reset. Replace uses of the specific cipher types with -cipher.Block. -</p> - -<h3 id="crypto_elliptic">The crypto/elliptic package</h3> - -<p> -In Go 1, <a href="/pkg/crypto/elliptic/#Curve"><code>elliptic.Curve</code></a> -has been made an interface to permit alternative implementations. The curve -parameters have been moved to the -<a href="/pkg/crypto/elliptic/#CurveParams"><code>elliptic.CurveParams</code></a> -structure. -</p> - -<p> -<em>Updating</em>: -Existing users of <code>*elliptic.Curve</code> will need to change to -simply <code>elliptic.Curve</code>. Calls to <code>Marshal</code>, -<code>Unmarshal</code> and <code>GenerateKey</code> are now functions -in <code>crypto/elliptic</code> that take an <code>elliptic.Curve</code> -as their first argument. -</p> - -<h3 id="crypto_hmac">The crypto/hmac package</h3> - -<p> -In Go 1, the hash-specific functions, such as <code>hmac.NewMD5</code>, have -been removed from <code>crypto/hmac</code>. Instead, <code>hmac.New</code> takes -a function that returns a <code>hash.Hash</code>, such as <code>md5.New</code>. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will perform the needed changes. -</p> - -<h3 id="crypto_x509">The crypto/x509 package</h3> - -<p> -In Go 1, the -<a href="/pkg/crypto/x509/#CreateCertificate"><code>CreateCertificate</code></a> -and -<a href="/pkg/crypto/x509/#CreateCRL"><code>CreateCRL</code></a> -functions in <code>crypto/x509</code> have been altered to take an -<code>interface{}</code> where they previously took a <code>*rsa.PublicKey</code> -or <code>*rsa.PrivateKey</code>. This will allow other public key algorithms -to be implemented in the future. -</p> - -<p> -<em>Updating</em>: -No changes will be needed. -</p> - -<h3 id="encoding_binary">The encoding/binary package</h3> - -<p> -In Go 1, the <code>binary.TotalSize</code> function has been replaced by -<a href="/pkg/encoding/binary/#Size"><code>Size</code></a>, -which takes an <code>interface{}</code> argument rather than -a <code>reflect.Value</code>. -</p> - -<p> -<em>Updating</em>: -What little code is affected will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="encoding_xml">The encoding/xml package</h3> - -<p> -In Go 1, the <a href="/pkg/encoding/xml/"><code>xml</code></a> package -has been brought closer in design to the other marshaling packages such -as <a href="/pkg/encoding/gob/"><code>encoding/gob</code></a>. -</p> - -<p> -The old <code>Parser</code> type is renamed -<a href="/pkg/encoding/xml/#Decoder"><code>Decoder</code></a> and has a new -<a href="/pkg/encoding/xml/#Decoder.Decode"><code>Decode</code></a> method. An -<a href="/pkg/encoding/xml/#Encoder"><code>Encoder</code></a> type was also introduced. -</p> - -<p> -The functions <a href="/pkg/encoding/xml/#Marshal"><code>Marshal</code></a> -and <a href="/pkg/encoding/xml/#Unmarshal"><code>Unmarshal</code></a> -work with <code>[]byte</code> values now. To work with streams, -use the new <a href="/pkg/encoding/xml/#Encoder"><code>Encoder</code></a> -and <a href="/pkg/encoding/xml/#Decoder"><code>Decoder</code></a> types. -</p> - -<p> -When marshaling or unmarshaling values, the format of supported flags in -field tags has changed to be closer to the -<a href="/pkg/encoding/json"><code>json</code></a> package -(<code>`xml:"name,flag"`</code>). The matching done between field tags, field -names, and the XML attribute and element names is now case-sensitive. -The <code>XMLName</code> field tag, if present, must also match the name -of the XML element being marshaled. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update most uses of the package except for some calls to -<code>Unmarshal</code>. Special care must be taken with field tags, -since the fix tool will not update them and if not fixed by hand they will -misbehave silently in some cases. For example, the old -<code>"attr"</code> is now written <code>",attr"</code> while plain -<code>"attr"</code> remains valid but with a different meaning. -</p> - -<h3 id="expvar">The expvar package</h3> - -<p> -In Go 1, the <code>RemoveAll</code> function has been removed. -The <code>Iter</code> function and Iter method on <code>*Map</code> have -been replaced by -<a href="/pkg/expvar/#Do"><code>Do</code></a> -and -<a href="/pkg/expvar/#Map.Do"><code>(*Map).Do</code></a>. -</p> - -<p> -<em>Updating</em>: -Most code using <code>expvar</code> will not need changing. The rare code that used -<code>Iter</code> can be updated to pass a closure to <code>Do</code> to achieve the same effect. -</p> - -<h3 id="flag">The flag package</h3> - -<p> -In Go 1, the interface <a href="/pkg/flag/#Value"><code>flag.Value</code></a> has changed slightly. -The <code>Set</code> method now returns an <code>error</code> instead of -a <code>bool</code> to indicate success or failure. -</p> - -<p> -There is also a new kind of flag, <code>Duration</code>, to support argument -values specifying time intervals. -Values for such flags must be given units, just as <code>time.Duration</code> -formats them: <code>10s</code>, <code>1h30m</code>, etc. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/timeout/`}} --->var timeout = flag.Duration(&#34;timeout&#34;, 30*time.Second, &#34;how long to wait for completion&#34;)</pre> - -<p> -<em>Updating</em>: -Programs that implement their own flags will need minor manual fixes to update their -<code>Set</code> methods. -The <code>Duration</code> flag is new and affects no existing code. -</p> - - -<h3 id="go">The go/* packages</h3> - -<p> -Several packages under <code>go</code> have slightly revised APIs. -</p> - -<p> -A concrete <code>Mode</code> type was introduced for configuration mode flags -in the packages -<a href="/pkg/go/scanner/"><code>go/scanner</code></a>, -<a href="/pkg/go/parser/"><code>go/parser</code></a>, -<a href="/pkg/go/printer/"><code>go/printer</code></a>, and -<a href="/pkg/go/doc/"><code>go/doc</code></a>. -</p> - -<p> -The modes <code>AllowIllegalChars</code> and <code>InsertSemis</code> have been removed -from the <a href="/pkg/go/scanner/"><code>go/scanner</code></a> package. They were mostly -useful for scanning text other then Go source files. Instead, the -<a href="/pkg/text/scanner/"><code>text/scanner</code></a> package should be used -for that purpose. -</p> - -<p> -The <a href="/pkg/go/scanner/#ErrorHandler"><code>ErrorHandler</code></a> provided -to the scanner's <a href="/pkg/go/scanner/#Scanner.Init"><code>Init</code></a> method is -now simply a function rather than an interface. The <code>ErrorVector</code> type has -been removed in favor of the (existing) <a href="/pkg/go/scanner/#ErrorList"><code>ErrorList</code></a> -type, and the <code>ErrorVector</code> methods have been migrated. Instead of embedding -an <code>ErrorVector</code> in a client of the scanner, now a client should maintain -an <code>ErrorList</code>. -</p> - -<p> -The set of parse functions provided by the <a href="/pkg/go/parser/"><code>go/parser</code></a> -package has been reduced to the primary parse function -<a href="/pkg/go/parser/#ParseFile"><code>ParseFile</code></a>, and a couple of -convenience functions <a href="/pkg/go/parser/#ParseDir"><code>ParseDir</code></a> -and <a href="/pkg/go/parser/#ParseExpr"><code>ParseExpr</code></a>. -</p> - -<p> -The <a href="/pkg/go/printer/"><code>go/printer</code></a> package supports an additional -configuration mode <a href="/pkg/go/printer/#Mode"><code>SourcePos</code></a>; -if set, the printer will emit <code>//line</code> comments such that the generated -output contains the original source code position information. The new type -<a href="/pkg/go/printer/#CommentedNode"><code>CommentedNode</code></a> can be -used to provide comments associated with an arbitrary -<a href="/pkg/go/ast/#Node"><code>ast.Node</code></a> (until now only -<a href="/pkg/go/ast/#File"><code>ast.File</code></a> carried comment information). -</p> - -<p> -The type names of the <a href="/pkg/go/doc/"><code>go/doc</code></a> package have been -streamlined by removing the <code>Doc</code> suffix: <code>PackageDoc</code> -is now <code>Package</code>, <code>ValueDoc</code> is <code>Value</code>, etc. -Also, all types now consistently have a <code>Name</code> field (or <code>Names</code>, -in the case of type <code>Value</code>) and <code>Type.Factories</code> has become -<code>Type.Funcs</code>. -Instead of calling <code>doc.NewPackageDoc(pkg, importpath)</code>, -documentation for a package is created with: -</p> - -<pre> - doc.New(pkg, importpath, mode) -</pre> - -<p> -where the new <code>mode</code> parameter specifies the operation mode: -if set to <a href="/pkg/go/doc/#AllDecls"><code>AllDecls</code></a>, all declarations -(not just exported ones) are considered. -The function <code>NewFileDoc</code> was removed, and the function -<code>CommentText</code> has become the method -<a href="/pkg/go/ast/#Text"><code>Text</code></a> of -<a href="/pkg/go/ast/#CommentGroup"><code>ast.CommentGroup</code></a>. -</p> - -<p> -In package <a href="/pkg/go/token/"><code>go/token</code></a>, the -<a href="/pkg/go/token/#FileSet"><code>token.FileSet</code></a> method <code>Files</code> -(which originally returned a channel of <code>*token.File</code>s) has been replaced -with the iterator <a href="/pkg/go/token/#FileSet.Iterate"><code>Iterate</code></a> that -accepts a function argument instead. -</p> - -<p> -In package <a href="/pkg/go/build/"><code>go/build</code></a>, the API -has been nearly completely replaced. -The package still computes Go package information -but it does not run the build: the <code>Cmd</code> and <code>Script</code> -types are gone. -(To build code, use the new -<a href="/cmd/go/"><code>go</code></a> command instead.) -The <code>DirInfo</code> type is now named -<a href="/pkg/go/build/#Package"><code>Package</code></a>. -<code>FindTree</code> and <code>ScanDir</code> are replaced by -<a href="/pkg/go/build/#Import"><code>Import</code></a> -and -<a href="/pkg/go/build/#ImportDir"><code>ImportDir</code></a>. -</p> - -<p> -<em>Updating</em>: -Code that uses packages in <code>go</code> will have to be updated by hand; the -compiler will reject incorrect uses. Templates used in conjunction with any of the -<code>go/doc</code> types may need manual fixes; the renamed fields will lead -to run-time errors. -</p> - -<h3 id="hash">The hash package</h3> - -<p> -In Go 1, the definition of <a href="/pkg/hash/#Hash"><code>hash.Hash</code></a> includes -a new method, <code>BlockSize</code>. This new method is used primarily in the -cryptographic libraries. -</p> - -<p> -The <code>Sum</code> method of the -<a href="/pkg/hash/#Hash"><code>hash.Hash</code></a> interface now takes a -<code>[]byte</code> argument, to which the hash value will be appended. -The previous behavior can be recreated by adding a <code>nil</code> argument to the call. -</p> - -<p> -<em>Updating</em>: -Existing implementations of <code>hash.Hash</code> will need to add a -<code>BlockSize</code> method. Hashes that process the input one byte at -a time can implement <code>BlockSize</code> to return 1. -Running <code>go</code> <code>fix</code> will update calls to the <code>Sum</code> methods of the various -implementations of <code>hash.Hash</code>. -</p> - -<p> -<em>Updating</em>: -Since the package's functionality is new, no updating is necessary. -</p> - -<h3 id="http">The http package</h3> - -<p> -In Go 1 the <a href="/pkg/net/http/"><code>http</code></a> package is refactored, -putting some of the utilities into a -<a href="/pkg/net/http/httputil/"><code>httputil</code></a> subdirectory. -These pieces are only rarely needed by HTTP clients. -The affected items are: -</p> - -<ul> -<li>ClientConn</li> -<li>DumpRequest</li> -<li>DumpRequestOut</li> -<li>DumpResponse</li> -<li>NewChunkedReader</li> -<li>NewChunkedWriter</li> -<li>NewClientConn</li> -<li>NewProxyClientConn</li> -<li>NewServerConn</li> -<li>NewSingleHostReverseProxy</li> -<li>ReverseProxy</li> -<li>ServerConn</li> -</ul> - -<p> -The <code>Request.RawURL</code> field has been removed; it was a -historical artifact. -</p> - -<p> -The <code>Handle</code> and <code>HandleFunc</code> -functions, and the similarly-named methods of <code>ServeMux</code>, -now panic if an attempt is made to register the same pattern twice. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update the few programs that are affected except for -uses of <code>RawURL</code>, which must be fixed by hand. -</p> - -<h3 id="image">The image package</h3> - -<p> -The <a href="/pkg/image/"><code>image</code></a> package has had a number of -minor changes, rearrangements and renamings. -</p> - -<p> -Most of the color handling code has been moved into its own package, -<a href="/pkg/image/color/"><code>image/color</code></a>. -For the elements that moved, a symmetry arises; for instance, -each pixel of an -<a href="/pkg/image/#RGBA"><code>image.RGBA</code></a> -is a -<a href="/pkg/image/color/#RGBA"><code>color.RGBA</code></a>. -</p> - -<p> -The old <code>image/ycbcr</code> package has been folded, with some -renamings, into the -<a href="/pkg/image/"><code>image</code></a> -and -<a href="/pkg/image/color/"><code>image/color</code></a> -packages. -</p> - -<p> -The old <code>image.ColorImage</code> type is still in the <code>image</code> -package but has been renamed -<a href="/pkg/image/#Uniform"><code>image.Uniform</code></a>, -while <code>image.Tiled</code> has been removed. -</p> - -<p> -This table lists the renamings. -</p> - -<table class="codetable" frame="border" summary="image renames"> -<colgroup align="left" width="50%"></colgroup> -<colgroup align="left" width="50%"></colgroup> -<tr> -<th align="left">Old</th> -<th align="left">New</th> -</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>image.Color</td> <td>color.Color</td></tr> -<tr><td>image.ColorModel</td> <td>color.Model</td></tr> -<tr><td>image.ColorModelFunc</td> <td>color.ModelFunc</td></tr> -<tr><td>image.PalettedColorModel</td> <td>color.Palette</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>image.RGBAColor</td> <td>color.RGBA</td></tr> -<tr><td>image.RGBA64Color</td> <td>color.RGBA64</td></tr> -<tr><td>image.NRGBAColor</td> <td>color.NRGBA</td></tr> -<tr><td>image.NRGBA64Color</td> <td>color.NRGBA64</td></tr> -<tr><td>image.AlphaColor</td> <td>color.Alpha</td></tr> -<tr><td>image.Alpha16Color</td> <td>color.Alpha16</td></tr> -<tr><td>image.GrayColor</td> <td>color.Gray</td></tr> -<tr><td>image.Gray16Color</td> <td>color.Gray16</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>image.RGBAColorModel</td> <td>color.RGBAModel</td></tr> -<tr><td>image.RGBA64ColorModel</td> <td>color.RGBA64Model</td></tr> -<tr><td>image.NRGBAColorModel</td> <td>color.NRGBAModel</td></tr> -<tr><td>image.NRGBA64ColorModel</td> <td>color.NRGBA64Model</td></tr> -<tr><td>image.AlphaColorModel</td> <td>color.AlphaModel</td></tr> -<tr><td>image.Alpha16ColorModel</td> <td>color.Alpha16Model</td></tr> -<tr><td>image.GrayColorModel</td> <td>color.GrayModel</td></tr> -<tr><td>image.Gray16ColorModel</td> <td>color.Gray16Model</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>ycbcr.RGBToYCbCr</td> <td>color.RGBToYCbCr</td></tr> -<tr><td>ycbcr.YCbCrToRGB</td> <td>color.YCbCrToRGB</td></tr> -<tr><td>ycbcr.YCbCrColorModel</td> <td>color.YCbCrModel</td></tr> -<tr><td>ycbcr.YCbCrColor</td> <td>color.YCbCr</td></tr> -<tr><td>ycbcr.YCbCr</td> <td>image.YCbCr</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>ycbcr.SubsampleRatio444</td> <td>image.YCbCrSubsampleRatio444</td></tr> -<tr><td>ycbcr.SubsampleRatio422</td> <td>image.YCbCrSubsampleRatio422</td></tr> -<tr><td>ycbcr.SubsampleRatio420</td> <td>image.YCbCrSubsampleRatio420</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>image.ColorImage</td> <td>image.Uniform</td></tr> -</table> - -<p> -The image package's <code>New</code> functions -(<a href="/pkg/image/#NewRGBA"><code>NewRGBA</code></a>, -<a href="/pkg/image/#NewRGBA64"><code>NewRGBA64</code></a>, etc.) -take an <a href="/pkg/image/#Rectangle"><code>image.Rectangle</code></a> as an argument -instead of four integers. -</p> - -<p> -Finally, there are new predefined <code>color.Color</code> variables -<a href="/pkg/image/color/#Black"><code>color.Black</code></a>, -<a href="/pkg/image/color/#White"><code>color.White</code></a>, -<a href="/pkg/image/color/#Opaque"><code>color.Opaque</code></a> -and -<a href="/pkg/image/color/#Transparent"><code>color.Transparent</code></a>. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update almost all code affected by the change. -</p> - -<h3 id="log_syslog">The log/syslog package</h3> - -<p> -In Go 1, the <a href="/pkg/log/syslog/#NewLogger"><code>syslog.NewLogger</code></a> -function returns an error as well as a <code>log.Logger</code>. -</p> - -<p> -<em>Updating</em>: -What little code is affected will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="mime">The mime package</h3> - -<p> -In Go 1, the <a href="/pkg/mime/#FormatMediaType"><code>FormatMediaType</code></a> function -of the <code>mime</code> package has been simplified to make it -consistent with -<a href="/pkg/mime/#ParseMediaType"><code>ParseMediaType</code></a>. -It now takes <code>"text/html"</code> rather than <code>"text"</code> and <code>"html"</code>. -</p> - -<p> -<em>Updating</em>: -What little code is affected will be caught by the compiler and must be updated by hand. -</p> - -<h3 id="net">The net package</h3> - -<p> -In Go 1, the various <code>SetTimeout</code>, -<code>SetReadTimeout</code>, and <code>SetWriteTimeout</code> methods -have been replaced with -<a href="/pkg/net/#IPConn.SetDeadline"><code>SetDeadline</code></a>, -<a href="/pkg/net/#IPConn.SetReadDeadline"><code>SetReadDeadline</code></a>, and -<a href="/pkg/net/#IPConn.SetWriteDeadline"><code>SetWriteDeadline</code></a>, -respectively. Rather than taking a timeout value in nanoseconds that -apply to any activity on the connection, the new methods set an -absolute deadline (as a <code>time.Time</code> value) after which -reads and writes will time out and no longer block. -</p> - -<p> -There are also new functions -<a href="/pkg/net/#DialTimeout"><code>net.DialTimeout</code></a> -to simplify timing out dialing a network address and -<a href="/pkg/net/#ListenMulticastUDP"><code>net.ListenMulticastUDP</code></a> -to allow multicast UDP to listen concurrently across multiple listeners. -The <code>net.ListenMulticastUDP</code> function replaces the old -<code>JoinGroup</code> and <code>LeaveGroup</code> methods. -</p> - -<p> -<em>Updating</em>: -Code that uses the old methods will fail to compile and must be updated by hand. -The semantic change makes it difficult for the fix tool to update automatically. -</p> - -<h3 id="os">The os package</h3> - -<p> -The <code>Time</code> function has been removed; callers should use -the <a href="/pkg/time/#Time"><code>Time</code></a> type from the -<code>time</code> package. -</p> - -<p> -The <code>Exec</code> function has been removed; callers should use -<code>Exec</code> from the <code>syscall</code> package, where available. -</p> - -<p> -The <code>ShellExpand</code> function has been renamed to <a -href="/pkg/os/#ExpandEnv"><code>ExpandEnv</code></a>. -</p> - -<p> -The <a href="/pkg/os/#NewFile"><code>NewFile</code></a> function -now takes a <code>uintptr</code> fd, instead of an <code>int</code>. -The <a href="/pkg/os/#File.Fd"><code>Fd</code></a> method on files now -also returns a <code>uintptr</code>. -</p> - -<p> -There are no longer error constants such as <code>EINVAL</code> -in the <code>os</code> package, since the set of values varied with -the underlying operating system. There are new portable functions like -<a href="/pkg/os/#IsPermission"><code>IsPermission</code></a> -to test common error properties, plus a few new error values -with more Go-like names, such as -<a href="/pkg/os/#ErrPermission"><code>ErrPermission</code></a> -and -<a href="/pkg/os/#ErrNoEnv"><code>ErrNoEnv</code></a>. -</p> - -<p> -The <code>Getenverror</code> function has been removed. To distinguish -between a non-existent environment variable and an empty string, -use <a href="/pkg/os/#Environ"><code>os.Environ</code></a> or -<a href="/pkg/syscall/#Getenv"><code>syscall.Getenv</code></a>. -</p> - - -<p> -The <a href="/pkg/os/#Process.Wait"><code>Process.Wait</code></a> method has -dropped its option argument and the associated constants are gone -from the package. -Also, the function <code>Wait</code> is gone; only the method of -the <code>Process</code> type persists. -</p> - -<p> -The <code>Waitmsg</code> type returned by -<a href="/pkg/os/#Process.Wait"><code>Process.Wait</code></a> -has been replaced with a more portable -<a href="/pkg/os/#ProcessState"><code>ProcessState</code></a> -type with accessor methods to recover information about the -process. -Because of changes to <code>Wait</code>, the <code>ProcessState</code> -value always describes an exited process. -Portability concerns simplified the interface in other ways, but the values returned by the -<a href="/pkg/os/#ProcessState.Sys"><code>ProcessState.Sys</code></a> and -<a href="/pkg/os/#ProcessState.SysUsage"><code>ProcessState.SysUsage</code></a> -methods can be type-asserted to underlying system-specific data structures such as -<a href="/pkg/syscall/#WaitStatus"><code>syscall.WaitStatus</code></a> and -<a href="/pkg/syscall/#Rusage"><code>syscall.Rusage</code></a> on Unix. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will drop a zero argument to <code>Process.Wait</code>. -All other changes will be caught by the compiler and must be updated by hand. -</p> - -<h4 id="os_fileinfo">The os.FileInfo type</h4> - -<p> -Go 1 redefines the <a href="/pkg/os/#FileInfo"><code>os.FileInfo</code></a> type, -changing it from a struct to an interface: -</p> - -<pre> - type FileInfo interface { - Name() string // base name of the file - Size() int64 // length in bytes - Mode() FileMode // file mode bits - ModTime() time.Time // modification time - IsDir() bool // abbreviation for Mode().IsDir() - Sys() interface{} // underlying data source (can return nil) - } -</pre> - -<p> -The file mode information has been moved into a subtype called -<a href="/pkg/os/#FileMode"><code>os.FileMode</code></a>, -a simple integer type with <code>IsDir</code>, <code>Perm</code>, and <code>String</code> -methods. -</p> - -<p> -The system-specific details of file modes and properties such as (on Unix) -i-number have been removed from <code>FileInfo</code> altogether. -Instead, each operating system's <code>os</code> package provides an -implementation of the <code>FileInfo</code> interface, which -has a <code>Sys</code> method that returns the -system-specific representation of file metadata. -For instance, to discover the i-number of a file on a Unix system, unpack -the <code>FileInfo</code> like this: -</p> - -<pre> - fi, err := os.Stat("hello.go") - if err != nil { - log.Fatal(err) - } - // Check that it's a Unix file. - unixStat, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - log.Fatal("hello.go: not a Unix file") - } - fmt.Printf("file i-number: %d\n", unixStat.Ino) -</pre> - -<p> -Assuming (which is unwise) that <code>"hello.go"</code> is a Unix file, -the i-number expression could be contracted to -</p> - -<pre> - fi.Sys().(*syscall.Stat_t).Ino -</pre> - -<p> -The vast majority of uses of <code>FileInfo</code> need only the methods -of the standard interface. -</p> - -<p> -The <code>os</code> package no longer contains wrappers for the POSIX errors -such as <code>ENOENT</code>. -For the few programs that need to verify particular error conditions, there are -now the boolean functions -<a href="/pkg/os/#IsExist"><code>IsExist</code></a>, -<a href="/pkg/os/#IsNotExist"><code>IsNotExist</code></a> -and -<a href="/pkg/os/#IsPermission"><code>IsPermission</code></a>. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/os\.Open/` `/}/`}} ---> f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - log.Printf(&#34;%s already exists&#34;, name) - }</pre> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update code that uses the old equivalent of the current <code>os.FileInfo</code> -and <code>os.FileMode</code> API. -Code that needs system-specific file details will need to be updated by hand. -Code that uses the old POSIX error values from the <code>os</code> package -will fail to compile and will also need to be updated by hand. -</p> - -<h3 id="os_signal">The os/signal package</h3> - -<p> -The <code>os/signal</code> package in Go 1 replaces the -<code>Incoming</code> function, which returned a channel -that received all incoming signals, -with the selective <code>Notify</code> function, which asks -for delivery of specific signals on an existing channel. -</p> - -<p> -<em>Updating</em>: -Code must be updated by hand. -A literal translation of -</p> -<pre> -c := signal.Incoming() -</pre> -<p> -is -</p> -<pre> -c := make(chan os.Signal) -signal.Notify(c) // ask for all signals -</pre> -<p> -but most code should list the specific signals it wants to handle instead: -</p> -<pre> -c := make(chan os.Signal) -signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT) -</pre> - -<h3 id="path_filepath">The path/filepath package</h3> - -<p> -In Go 1, the <a href="/pkg/path/filepath/#Walk"><code>Walk</code></a> function of the -<code>path/filepath</code> package -has been changed to take a function value of type -<a href="/pkg/path/filepath/#WalkFunc"><code>WalkFunc</code></a> -instead of a <code>Visitor</code> interface value. -<code>WalkFunc</code> unifies the handling of both files and directories. -</p> - -<pre> - type WalkFunc func(path string, info os.FileInfo, err error) error -</pre> - -<p> -The <code>WalkFunc</code> function will be called even for files or directories that could not be opened; -in such cases the error argument will describe the failure. -If a directory's contents are to be skipped, -the function should return the value <a href="/pkg/path/filepath/#variables"><code>filepath.SkipDir</code></a> -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/STARTWALK/` `/ENDWALK/`}} ---> markFn := func(path string, info os.FileInfo, err error) error { - if path == &#34;pictures&#34; { <span class="comment">// Will skip walking of directory pictures and its contents.</span> - return filepath.SkipDir - } - if err != nil { - return err - } - log.Println(path) - return nil - } - err := filepath.Walk(&#34;.&#34;, markFn) - if err != nil { - log.Fatal(err) - }</pre> - -<p> -<em>Updating</em>: -The change simplifies most code but has subtle consequences, so affected programs -will need to be updated by hand. -The compiler will catch code using the old interface. -</p> - -<h3 id="regexp">The regexp package</h3> - -<p> -The <a href="/pkg/regexp/"><code>regexp</code></a> package has been rewritten. -It has the same interface but the specification of the regular expressions -it supports has changed from the old "egrep" form to that of -<a href="http://code.google.com/p/re2/">RE2</a>. -</p> - -<p> -<em>Updating</em>: -Code that uses the package should have its regular expressions checked by hand. -</p> - -<h3 id="runtime">The runtime package</h3> - -<p> -In Go 1, much of the API exported by package -<code>runtime</code> has been removed in favor of -functionality provided by other packages. -Code using the <code>runtime.Type</code> interface -or its specific concrete type implementations should -now use package <a href="/pkg/reflect/"><code>reflect</code></a>. -Code using <code>runtime.Semacquire</code> or <code>runtime.Semrelease</code> -should use channels or the abstractions in package <a href="/pkg/sync/"><code>sync</code></a>. -The <code>runtime.Alloc</code>, <code>runtime.Free</code>, -and <code>runtime.Lookup</code> functions, an unsafe API created for -debugging the memory allocator, have no replacement. -</p> - -<p> -Before, <code>runtime.MemStats</code> was a global variable holding -statistics about memory allocation, and calls to <code>runtime.UpdateMemStats</code> -ensured that it was up to date. -In Go 1, <code>runtime.MemStats</code> is a struct type, and code should use -<a href="/pkg/runtime/#ReadMemStats"><code>runtime.ReadMemStats</code></a> -to obtain the current statistics. -</p> - -<p> -The package adds a new function, -<a href="/pkg/runtime/#NumCPU"><code>runtime.NumCPU</code></a>, that returns the number of CPUs available -for parallel execution, as reported by the operating system kernel. -Its value can inform the setting of <code>GOMAXPROCS</code>. -The <code>runtime.Cgocalls</code> and <code>runtime.Goroutines</code> functions -have been renamed to <code>runtime.NumCgoCall</code> and <code>runtime.NumGoroutine</code>. -</p> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update code for the function renamings. -Other code will need to be updated by hand. -</p> - -<h3 id="strconv">The strconv package</h3> - -<p> -In Go 1, the -<a href="/pkg/strconv/"><code>strconv</code></a> -package has been significantly reworked to make it more Go-like and less C-like, -although <code>Atoi</code> lives on (it's similar to -<code>int(ParseInt(x, 10, 0))</code>, as does -<code>Itoa(x)</code> (<code>FormatInt(int64(x), 10)</code>). -There are also new variants of some of the functions that append to byte slices rather than -return strings, to allow control over allocation. -</p> - -<p> -This table summarizes the renamings; see the -<a href="/pkg/strconv/">package documentation</a> -for full details. -</p> - -<table class="codetable" frame="border" summary="strconv renames"> -<colgroup align="left" width="50%"></colgroup> -<colgroup align="left" width="50%"></colgroup> -<tr> -<th align="left">Old call</th> -<th align="left">New call</th> -</tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Atob(x)</td> <td>ParseBool(x)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Atof32(x)</td> <td>ParseFloat(x, 32)§</td></tr> -<tr><td>Atof64(x)</td> <td>ParseFloat(x, 64)</td></tr> -<tr><td>AtofN(x, n)</td> <td>ParseFloat(x, n)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Atoi(x)</td> <td>Atoi(x)</td></tr> -<tr><td>Atoi(x)</td> <td>ParseInt(x, 10, 0)§</td></tr> -<tr><td>Atoi64(x)</td> <td>ParseInt(x, 10, 64)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Atoui(x)</td> <td>ParseUint(x, 10, 0)§</td></tr> -<tr><td>Atoui64(x)</td> <td>ParseUint(x, 10, 64)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Btoi64(x, b)</td> <td>ParseInt(x, b, 64)</td></tr> -<tr><td>Btoui64(x, b)</td> <td>ParseUint(x, b, 64)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Btoa(x)</td> <td>FormatBool(x)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Ftoa32(x, f, p)</td> <td>FormatFloat(float64(x), f, p, 32)</td></tr> -<tr><td>Ftoa64(x, f, p)</td> <td>FormatFloat(x, f, p, 64)</td></tr> -<tr><td>FtoaN(x, f, p, n)</td> <td>FormatFloat(x, f, p, n)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Itoa(x)</td> <td>Itoa(x)</td></tr> -<tr><td>Itoa(x)</td> <td>FormatInt(int64(x), 10)</td></tr> -<tr><td>Itoa64(x)</td> <td>FormatInt(x, 10)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Itob(x, b)</td> <td>FormatInt(int64(x), b)</td></tr> -<tr><td>Itob64(x, b)</td> <td>FormatInt(x, b)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Uitoa(x)</td> <td>FormatUint(uint64(x), 10)</td></tr> -<tr><td>Uitoa64(x)</td> <td>FormatUint(x, 10)</td></tr> -<tr> -<td colspan="2"><hr></td> -</tr> -<tr><td>Uitob(x, b)</td> <td>FormatUint(uint64(x), b)</td></tr> -<tr><td>Uitob64(x, b)</td> <td>FormatUint(x, b)</td></tr> -</table> - -<p> -<em>Updating</em>: -Running <code>go</code> <code>fix</code> will update almost all code affected by the change. -<br> -§ <code>Atoi</code> persists but <code>Atoui</code> and <code>Atof32</code> do not, so -they may require -a cast that must be added by hand; the <code>go</code> <code>fix</code> tool will warn about it. -</p> - - -<h3 id="templates">The template packages</h3> - -<p> -The <code>template</code> and <code>exp/template/html</code> packages have moved to -<a href="/pkg/text/template/"><code>text/template</code></a> and -<a href="/pkg/html/template/"><code>html/template</code></a>. -More significant, the interface to these packages has been simplified. -The template language is the same, but the concept of "template set" is gone -and the functions and methods of the packages have changed accordingly, -often by elimination. -</p> - -<p> -Instead of sets, a <code>Template</code> object -may contain multiple named template definitions, -in effect constructing -name spaces for template invocation. -A template can invoke any other template associated with it, but only those -templates associated with it. -The simplest way to associate templates is to parse them together, something -made easier with the new structure of the packages. -</p> - -<p> -<em>Updating</em>: -The imports will be updated by fix tool. -Single-template uses will be otherwise be largely unaffected. -Code that uses multiple templates in concert will need to be updated by hand. -The <a href="/pkg/text/template/#examples">examples</a> in -the documentation for <code>text/template</code> can provide guidance. -</p> - -<h3 id="testing">The testing package</h3> - -<p> -The testing package has a type, <code>B</code>, passed as an argument to benchmark functions. -In Go 1, <code>B</code> has new methods, analogous to those of <code>T</code>, enabling -logging and failure reporting. -</p> - -<pre><!--{{code "/doc/progs/go1.go" `/func.*Benchmark/` `/^}/`}} --->func BenchmarkSprintf(b *testing.B) { - <span class="comment">// Verify correctness before running benchmark.</span> - b.StopTimer() - got := fmt.Sprintf(&#34;%x&#34;, 23) - const expect = &#34;17&#34; - if expect != got { - b.Fatalf(&#34;expected %q; got %q&#34;, expect, got) - } - b.StartTimer() - for i := 0; i &lt; b.N; i++ { - fmt.Sprintf(&#34;%x&#34;, 23) - } -}</pre> - -<p> -<em>Updating</em>: -Existing code is unaffected, although benchmarks that use <code>println</code> -or <code>panic</code> should be updated to use the new methods. -</p> - -<h3 id="testing_script">The testing/script package</h3> - -<p> -The testing/script package has been deleted. It was a dreg. -</p> - -<p> -<em>Updating</em>: -No code is likely to be affected. -</p> - -<h3 id="unsafe">The unsafe package</h3> - -<p> -In Go 1, the functions -<code>unsafe.Typeof</code>, <code>unsafe.Reflect</code>, -<code>unsafe.Unreflect</code>, <code>unsafe.New</code>, and -<code>unsafe.NewArray</code> have been removed; -they duplicated safer functionality provided by -package <a href="/pkg/reflect/"><code>reflect</code></a>. -</p> - -<p> -<em>Updating</em>: -Code using these functions must be rewritten to use -package <a href="/pkg/reflect/"><code>reflect</code></a>. -The changes to <a href="http://code.google.com/p/go/source/detail?r=2646dc956207">encoding/gob</a> and the <a href="http://code.google.com/p/goprotobuf/source/detail?r=5340ad310031">protocol buffer library</a> -may be helpful as examples. -</p> - -<h3 id="url">The url package</h3> - -<p> -In Go 1 several fields from the <a href="/pkg/net/url/#URL"><code>url.URL</code></a> type -were removed or replaced. -</p> - -<p> -The <a href="/pkg/net/url/#URL.String"><code>String</code></a> method now -predictably rebuilds an encoded URL string using all of <code>URL</code>'s -fields as necessary. The resulting string will also no longer have -passwords escaped. -</p> - -<p> -The <code>Raw</code> field has been removed. In most cases the <code>String</code> -method may be used in its place. -</p> - -<p> -The old <code>RawUserinfo</code> field is replaced by the <code>User</code> -field, of type <a href="/pkg/net/url/#Userinfo"><code>*net.Userinfo</code></a>. -Values of this type may be created using the new <a href="/pkg/net/url/#User"><code>net.User</code></a> -and <a href="/pkg/net/url/#UserPassword"><code>net.UserPassword</code></a> -functions. The <code>EscapeUserinfo</code> and <code>UnescapeUserinfo</code> -functions are also gone. -</p> - -<p> -The <code>RawAuthority</code> field has been removed. The same information is -available in the <code>Host</code> and <code>User</code> fields. -</p> - -<p> -The <code>RawPath</code> field and the <code>EncodedPath</code> method have -been removed. The path information in rooted URLs (with a slash following the -schema) is now available only in decoded form in the <code>Path</code> field. -Occasionally, the encoded data may be required to obtain information that -was lost in the decoding process. These cases must be handled by accessing -the data the URL was built from. -</p> - -<p> -URLs with non-rooted paths, such as <code>"mailto:dev@golang.org?subject=Hi"</code>, -are also handled differently. The <code>OpaquePath</code> boolean field has been -removed and a new <code>Opaque</code> string field introduced to hold the encoded -path for such URLs. In Go 1, the cited URL parses as: -</p> - -<pre> - URL{ - Scheme: "mailto", - Opaque: "dev@golang.org", - RawQuery: "subject=Hi", - } -</pre> - -<p> -A new <a href="/pkg/net/url/#URL.RequestURI"><code>RequestURI</code></a> method was -added to <code>URL</code>. -</p> - -<p> -The <code>ParseWithReference</code> function has been renamed to <code>ParseWithFragment</code>. -</p> - -<p> -<em>Updating</em>: -Code that uses the old fields will fail to compile and must be updated by hand. -The semantic changes make it difficult for the fix tool to update automatically. -</p> - -<h2 id="cmd_go">The go command</h2> - -<p> -Go 1 introduces the <a href="/cmd/go/">go command</a>, a tool for fetching, -building, and installing Go packages and commands. The <code>go</code> command -does away with makefiles, instead using Go source code to find dependencies and -determine build conditions. Most existing Go programs will no longer require -makefiles to be built. -</p> - -<p> -See <a href="/doc/code.html">How to Write Go Code</a> for a primer on the -<code>go</code> command and the <a href="/cmd/go/">go command documentation</a> -for the full details. -</p> - -<p> -<em>Updating</em>: -Projects that depend on the Go project's old makefile-based build -infrastructure (<code>Make.pkg</code>, <code>Make.cmd</code>, and so on) should -switch to using the <code>go</code> command for building Go code and, if -necessary, rewrite their makefiles to perform any auxiliary build tasks. -</p> - -<h2 id="cmd_cgo">The cgo command</h2> - -<p> -In Go 1, the <a href="/cmd/cgo">cgo command</a> -uses a different <code>_cgo_export.h</code> -file, which is generated for packages containing <code>//export</code> lines. -The <code>_cgo_export.h</code> file now begins with the C preamble comment, -so that exported function definitions can use types defined there. -This has the effect of compiling the preamble multiple times, so a -package using <code>//export</code> must not put function definitions -or variable initializations in the C preamble. -</p> - -<h2 id="releases">Packaged releases</h2> - -<p> -One of the most significant changes associated with Go 1 is the availability -of prepackaged, downloadable distributions. -They are available for many combinations of architecture and operating system -(including Windows) and the list will grow. -Installation details are described on the -<a href="/doc/install">Getting Started</a> page, while -the distributions themselves are listed on the -<a href="http://code.google.com/p/go/downloads/list">downloads page</a>. - - -</div> - -<div id="footer"> -Build version go1.0.1.<br> -Except as <a href="http://code.google.com/policies.html#restrictions">noted</a>, -the content of this page is licensed under the -Creative Commons Attribution 3.0 License, -and code is licensed under a <a href="/LICENSE">BSD license</a>.<br> -<a href="/doc/tos.html">Terms of Service</a> | -<a href="http://www.google.com/intl/en/privacy/privacy-policy.html">Privacy Policy</a> -</div> - -<script type="text/javascript"> -(function() { - var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true; - ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js"; - var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s); -})(); -</script> -</body> -<script type="text/javascript"> - (function() { - var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; - po.src = 'https://apis.google.com/js/plusone.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); - })(); -</script> -</html> - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/README b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/README deleted file mode 100644 index 9b4c2d8be0a..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/README +++ /dev/null @@ -1,28 +0,0 @@ -The *.dat files in this directory are copied from The WebKit Open Source -Project, specifically $WEBKITROOT/LayoutTests/html5lib/resources. -WebKit is licensed under a BSD style license. -http://webkit.org/coding/bsd-license.html says: - -Copyright (C) 2009 Apple Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. - -2. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption01.dat deleted file mode 100644 index 787e1b01e19..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption01.dat +++ /dev/null @@ -1,194 +0,0 @@ -#data -<a><p></a></p> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <p> -| <a> - -#data -<a>1<p>2</a>3</p> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <p> -| <a> -| "2" -| "3" - -#data -<a>1<button>2</a>3</button> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <button> -| <a> -| "2" -| "3" - -#data -<a>1<b>2</a>3</b> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <b> -| "2" -| <b> -| "3" - -#data -<a>1<div>2<div>3</a>4</div>5</div> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <div> -| <a> -| "2" -| <div> -| <a> -| "3" -| "4" -| "5" - -#data -<table><a>1<p>2</a>3</p> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <p> -| <a> -| "2" -| "3" -| <table> - -#data -<b><b><a><p></a> -#errors -#document -| <html> -| <head> -| <body> -| <b> -| <b> -| <a> -| <p> -| <a> - -#data -<b><a><b><p></a> -#errors -#document -| <html> -| <head> -| <body> -| <b> -| <a> -| <b> -| <b> -| <p> -| <a> - -#data -<a><b><b><p></a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <b> -| <b> -| <b> -| <b> -| <p> -| <a> - -#data -<p>1<s id="A">2<b id="B">3</p>4</s>5</b> -#errors -#document -| <html> -| <head> -| <body> -| <p> -| "1" -| <s> -| id="A" -| "2" -| <b> -| id="B" -| "3" -| <s> -| id="A" -| <b> -| id="B" -| "4" -| <b> -| id="B" -| "5" - -#data -<table><a>1<td>2</td>3</table> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "1" -| <a> -| "3" -| <table> -| <tbody> -| <tr> -| <td> -| "2" - -#data -<table>A<td>B</td>C</table> -#errors -#document -| <html> -| <head> -| <body> -| "AC" -| <table> -| <tbody> -| <tr> -| <td> -| "B" - -#data -<a><svg><tr><input></a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <svg svg> -| <svg tr> -| <svg input> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption02.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption02.dat deleted file mode 100644 index d18151b44f0..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/adoption02.dat +++ /dev/null @@ -1,31 +0,0 @@ -#data -<b>1<i>2<p>3</b>4 -#errors -#document -| <html> -| <head> -| <body> -| <b> -| "1" -| <i> -| "2" -| <i> -| <p> -| <b> -| "3" -| "4" - -#data -<a><div><style></style><address><a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <div> -| <a> -| <style> -| <address> -| <a> -| <a> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/comments01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/comments01.dat deleted file mode 100644 index 44f18768300..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/comments01.dat +++ /dev/null @@ -1,135 +0,0 @@ -#data -FOO<!-- BAR -->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR --> -| "BAZ" - -#data -FOO<!-- BAR --!>BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR --> -| "BAZ" - -#data -FOO<!-- BAR -- >BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR -- >BAZ --> - -#data -FOO<!-- BAR -- <QUX> -- MUX -->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR -- <QUX> -- MUX --> -| "BAZ" - -#data -FOO<!-- BAR -- <QUX> -- MUX --!>BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR -- <QUX> -- MUX --> -| "BAZ" - -#data -FOO<!-- BAR -- <QUX> -- MUX -- >BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- BAR -- <QUX> -- MUX -- >BAZ --> - -#data -FOO<!---->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- --> -| "BAZ" - -#data -FOO<!--->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- --> -| "BAZ" - -#data -FOO<!-->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- --> -| "BAZ" - -#data -<?xml version="1.0">Hi -#errors -#document -| <!-- ?xml version="1.0" --> -| <html> -| <head> -| <body> -| "Hi" - -#data -<?xml version="1.0"> -#errors -#document -| <!-- ?xml version="1.0" --> -| <html> -| <head> -| <body> - -#data -<?xml version -#errors -#document -| <!-- ?xml version --> -| <html> -| <head> -| <body> - -#data -FOO<!----->BAZ -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <!-- - --> -| "BAZ" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/doctype01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/doctype01.dat deleted file mode 100644 index ae457328a45..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/doctype01.dat +++ /dev/null @@ -1,370 +0,0 @@ -#data -<!DOCTYPE html>Hello -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!dOctYpE HtMl>Hello -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPEhtml>Hello -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE>Hello -#errors -#document -| <!DOCTYPE > -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE >Hello -#errors -#document -| <!DOCTYPE > -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato >Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato taco>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato taco "ddd>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato sYstEM>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato sYstEM >Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato sYstEM ggg>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato SYSTEM taco >Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato SYSTEM 'taco"'>Hello -#errors -#document -| <!DOCTYPE potato "" "taco""> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato SYSTEM "taco">Hello -#errors -#document -| <!DOCTYPE potato "" "taco"> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato SYSTEM "tai'co">Hello -#errors -#document -| <!DOCTYPE potato "" "tai'co"> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato SYSTEMtaco "ddd">Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato grass SYSTEM taco>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato pUbLIc>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato pUbLIc >Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato pUbLIcgoof>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato PUBLIC goof>Hello -#errors -#document -| <!DOCTYPE potato> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato PUBLIC "go'of">Hello -#errors -#document -| <!DOCTYPE potato "go'of" ""> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato PUBLIC 'go'of'>Hello -#errors -#document -| <!DOCTYPE potato "go" ""> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato PUBLIC 'go:hh of' >Hello -#errors -#document -| <!DOCTYPE potato "go:hh of" ""> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE potato PUBLIC "W3C-//dfdf" SYSTEM ggg>Hello -#errors -#document -| <!DOCTYPE potato "W3C-//dfdf" ""> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" - "http://www.w3.org/TR/html4/strict.dtd">Hello -#errors -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE ...>Hello -#errors -#document -| <!DOCTYPE ...> -| <html> -| <head> -| <body> -| "Hello" - -#data -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE root-element [SYSTEM OR PUBLIC FPI] "uri" [ -<!-- internal declarations --> -]> -#errors -#document -| <!DOCTYPE root-element> -| <html> -| <head> -| <body> -| "]>" - -#data -<!DOCTYPE html PUBLIC - "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" - "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> -#errors -#document -| <!DOCTYPE html "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE HTML SYSTEM "http://www.w3.org/DTD/HTML4-strict.dtd"><body><b>Mine!</b></body> -#errors -#document -| <!DOCTYPE html "" "http://www.w3.org/DTD/HTML4-strict.dtd"> -| <html> -| <head> -| <body> -| <b> -| "Mine!" - -#data -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'http://www.w3.org/TR/html4/strict.dtd'> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01//EN"'http://www.w3.org/TR/html4/strict.dtd'> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE HTML PUBLIC'-//W3C//DTD HTML 4.01//EN''http://www.w3.org/TR/html4/strict.dtd'> -#errors -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -| <html> -| <head> -| <body> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities01.dat deleted file mode 100644 index c8073b7810b..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities01.dat +++ /dev/null @@ -1,603 +0,0 @@ -#data -FOO&gt;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO>BAR" - -#data -FOO&gtBAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO>BAR" - -#data -FOO&gt BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO> BAR" - -#data -FOO&gt;;;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO>;;BAR" - -#data -I'm &notit; I tell you -#errors -#document -| <html> -| <head> -| <body> -| "I'm ¬it; I tell you" - -#data -I'm &notin; I tell you -#errors -#document -| <html> -| <head> -| <body> -| "I'm ∉ I tell you" - -#data -FOO& BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO& BAR" - -#data -FOO&<BAR> -#errors -#document -| <html> -| <head> -| <body> -| "FOO&" -| <bar> - -#data -FOO&&&&gt;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO&&&>BAR" - -#data -FOO&#41;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO)BAR" - -#data -FOO&#x41;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOOABAR" - -#data -FOO&#X41;BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOOABAR" - -#data -FOO&#BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO&#BAR" - -#data -FOO&#ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO&#ZOO" - -#data -FOO&#xBAR -#errors -#document -| <html> -| <head> -| <body> -| "FOOºR" - -#data -FOO&#xZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO&#xZOO" - -#data -FOO&#XZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO&#XZOO" - -#data -FOO&#41BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO)BAR" - -#data -FOO&#x41BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO䆺R" - -#data -FOO&#x41ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOAZOO" - -#data -FOO&#x0000;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#x0078;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOxZOO" - -#data -FOO&#x0079;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOyZOO" - -#data -FOO&#x0080;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO€ZOO" - -#data -FOO&#x0081;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x0082;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO‚ZOO" - -#data -FOO&#x0083;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOƒZOO" - -#data -FOO&#x0084;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO„ZOO" - -#data -FOO&#x0085;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO…ZOO" - -#data -FOO&#x0086;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO†ZOO" - -#data -FOO&#x0087;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO‡ZOO" - -#data -FOO&#x0088;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOˆZOO" - -#data -FOO&#x0089;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO‰ZOO" - -#data -FOO&#x008A;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOŠZOO" - -#data -FOO&#x008B;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO‹ZOO" - -#data -FOO&#x008C;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOŒZOO" - -#data -FOO&#x008D;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x008E;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOŽZOO" - -#data -FOO&#x008F;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x0090;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x0091;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO‘ZOO" - -#data -FOO&#x0092;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO’ZOO" - -#data -FOO&#x0093;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO“ZOO" - -#data -FOO&#x0094;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO”ZOO" - -#data -FOO&#x0095;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO•ZOO" - -#data -FOO&#x0096;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO–ZOO" - -#data -FOO&#x0097;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO—ZOO" - -#data -FOO&#x0098;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO˜ZOO" - -#data -FOO&#x0099;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO™ZOO" - -#data -FOO&#x009A;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOšZOO" - -#data -FOO&#x009B;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO›ZOO" - -#data -FOO&#x009C;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOœZOO" - -#data -FOO&#x009D;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x009E;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOžZOO" - -#data -FOO&#x009F;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOŸZOO" - -#data -FOO&#x00A0;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO ZOO" - -#data -FOO&#xD7FF;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO퟿ZOO" - -#data -FOO&#xD800;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#xD801;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#xDFFE;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#xDFFF;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#xE000;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOOZOO" - -#data -FOO&#x10FFFE;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO􏿾ZOO" - -#data -FOO&#x1087D4;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO􈟔ZOO" - -#data -FOO&#x10FFFF;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO􏿿ZOO" - -#data -FOO&#x110000;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" - -#data -FOO&#xFFFFFF;ZOO -#errors -#document -| <html> -| <head> -| <body> -| "FOO�ZOO" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities02.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities02.dat deleted file mode 100644 index e2fb42a078b..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/entities02.dat +++ /dev/null @@ -1,249 +0,0 @@ -#data -<div bar="ZZ&gt;YY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ>YY" - -#data -<div bar="ZZ&"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&" - -#data -<div bar='ZZ&'></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&" - -#data -<div bar=ZZ&></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&" - -#data -<div bar="ZZ&gt=YY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&gt=YY" - -#data -<div bar="ZZ&gt0YY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&gt0YY" - -#data -<div bar="ZZ&gt9YY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&gt9YY" - -#data -<div bar="ZZ&gtaYY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&gtaYY" - -#data -<div bar="ZZ&gtZYY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&gtZYY" - -#data -<div bar="ZZ&gt YY"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ> YY" - -#data -<div bar="ZZ&gt"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ>" - -#data -<div bar='ZZ&gt'></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ>" - -#data -<div bar=ZZ&gt></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ>" - -#data -<div bar="ZZ&pound_id=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ£_id=23" - -#data -<div bar="ZZ&prod_id=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&prod_id=23" - -#data -<div bar="ZZ&pound;_id=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ£_id=23" - -#data -<div bar="ZZ&prod;_id=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ∏_id=23" - -#data -<div bar="ZZ&pound=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&pound=23" - -#data -<div bar="ZZ&prod=23"></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| bar="ZZ&prod=23" - -#data -<div>ZZ&pound_id=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ£_id=23" - -#data -<div>ZZ&prod_id=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ&prod_id=23" - -#data -<div>ZZ&pound;_id=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ£_id=23" - -#data -<div>ZZ&prod;_id=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ∏_id=23" - -#data -<div>ZZ&pound=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ£=23" - -#data -<div>ZZ&prod=23</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "ZZ&prod=23" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/html5test-com.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/html5test-com.dat deleted file mode 100644 index d7cb71db054..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/html5test-com.dat +++ /dev/null @@ -1,246 +0,0 @@ -#data -<div<div> -#errors -#document -| <html> -| <head> -| <body> -| <div<div> - -#data -<div foo<bar=''> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| foo<bar="" - -#data -<div foo=`bar`> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| foo="`bar`" - -#data -<div \"foo=''> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| \"foo="" - -#data -<a href='\nbar'></a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| href="\nbar" - -#data -<!DOCTYPE html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -&lang;&rang; -#errors -#document -| <html> -| <head> -| <body> -| "⟨⟩" - -#data -&apos; -#errors -#document -| <html> -| <head> -| <body> -| "'" - -#data -&ImaginaryI; -#errors -#document -| <html> -| <head> -| <body> -| "ⅈ" - -#data -&Kopf; -#errors -#document -| <html> -| <head> -| <body> -| "𝕂" - -#data -&notinva; -#errors -#document -| <html> -| <head> -| <body> -| "∉" - -#data -<?import namespace="foo" implementation="#bar"> -#errors -#document -| <!-- ?import namespace="foo" implementation="#bar" --> -| <html> -| <head> -| <body> - -#data -<!--foo--bar--> -#errors -#document -| <!-- foo--bar --> -| <html> -| <head> -| <body> - -#data -<![CDATA[x]]> -#errors -#document -| <!-- [CDATA[x]] --> -| <html> -| <head> -| <body> - -#data -<textarea><!--</textarea>--></textarea> -#errors -#document -| <html> -| <head> -| <body> -| <textarea> -| "<!--" -| "-->" - -#data -<textarea><!--</textarea>--> -#errors -#document -| <html> -| <head> -| <body> -| <textarea> -| "<!--" -| "-->" - -#data -<style><!--</style>--></style> -#errors -#document -| <html> -| <head> -| <style> -| "<!--" -| <body> -| "-->" - -#data -<style><!--</style>--> -#errors -#document -| <html> -| <head> -| <style> -| "<!--" -| <body> -| "-->" - -#data -<ul><li>A </li> <li>B</li></ul> -#errors -#document -| <html> -| <head> -| <body> -| <ul> -| <li> -| "A " -| " " -| <li> -| "B" - -#data -<table><form><input type=hidden><input></form><div></div></table> -#errors -#document -| <html> -| <head> -| <body> -| <input> -| <div> -| <table> -| <form> -| <input> -| type="hidden" - -#data -<i>A<b>B<p></i>C</b>D -#errors -#document -| <html> -| <head> -| <body> -| <i> -| "A" -| <b> -| "B" -| <b> -| <p> -| <b> -| <i> -| "C" -| "D" - -#data -<div></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> - -#data -<svg></svg> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> - -#data -<math></math> -#errors -#document -| <html> -| <head> -| <body> -| <math math> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/inbody01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/inbody01.dat deleted file mode 100644 index 3f2bd374c03..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/inbody01.dat +++ /dev/null @@ -1,43 +0,0 @@ -#data -<button>1</foo> -#errors -#document -| <html> -| <head> -| <body> -| <button> -| "1" - -#data -<foo>1<p>2</foo> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| "1" -| <p> -| "2" - -#data -<dd>1</foo> -#errors -#document -| <html> -| <head> -| <body> -| <dd> -| "1" - -#data -<foo>1<dd>2</foo> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| "1" -| <dd> -| "2" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/isindex.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/isindex.dat deleted file mode 100644 index 88325ffe64c..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/isindex.dat +++ /dev/null @@ -1,40 +0,0 @@ -#data -<isindex> -#errors -#document -| <html> -| <head> -| <body> -| <form> -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| <hr> - -#data -<isindex name="A" action="B" prompt="C" foo="D"> -#errors -#document -| <html> -| <head> -| <body> -| <form> -| action="B" -| <hr> -| <label> -| "C" -| <input> -| foo="D" -| name="isindex" -| <hr> - -#data -<form><isindex> -#errors -#document -| <html> -| <head> -| <body> -| <form> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes-plain-text-unsafe.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes-plain-text-unsafe.dat deleted file mode 100644 index a5ebb1eb285116af391137bc94beac0c8a6834b4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 115 zcmXZUQ3`+{41i&ucZ#9c5brYEqF^T2f`Sg8m2W@)!xxy0Am++fibh!_xp`HU=1fj= l5Tv!*b_iUjqsV4(V_d9g>VZ9lc;ttC7t#O7YxuDS4-Zl&BR>ED diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes.dat deleted file mode 100644 index 5a9208465f5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/pending-spec-changes.dat +++ /dev/null @@ -1,52 +0,0 @@ -#data -<input type="hidden"><frameset> -#errors -21: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -31: “frameset” start tag seen. -31: End of file seen and there were open elements. -#document -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><table><caption><svg>foo</table>bar -#errors -47: End tag “table” did not match the name of the current open element (“svg”). -47: “table” closed but “caption” was still open. -47: End tag “table” seen, but there were open elements. -36: Unclosed element “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <svg svg> -| "foo" -| "bar" - -#data -<table><tr><td><svg><desc><td></desc><circle> -#errors -7: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -30: A table cell was implicitly closed, but there were open elements. -26: Unclosed element “desc”. -20: Unclosed element “svg”. -37: Stray end tag “desc”. -45: End of file seen and there were open elements. -45: Unclosed element “circle”. -7: Unclosed element “table”. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg desc> -| <td> -| <circle> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/plain-text-unsafe.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/plain-text-unsafe.dat deleted file mode 100644 index 04cc11fb9d458ea32dca02e2f3bf39221196ab8e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4166 zcmds4&1%~~5Y}1XcNojiOL5|Zdr6iB6Q@@dnjYGa!^&DaD*8j(rYZE*N*}4O(Ai!6 zt?Ym#%MQd~yz+X#nfd0M+40P0g4rKk_ucGyu~@9HzqzhG<5`wuxjplf&5wx3!u}29 zQA8od1>ll1zgT*S|4T0c9E6$RdB?_+5>}tF$TnjU&$*!FvRd{rQXeva!GcpkGm9M! zZBWBlo0XH%V%aC7h2%Ws8$qo;*=zDp0+b3F08~mq!5(ow4OtKi{*2LVgD~WoB_9R= z%96mMsPR;h$nTtgfB$G~Tu5~MsAZ5p?I@Yv->g@6t9!$ThX*>G;HMo(<c>}#7Rl5a zZg4uE1I7jOIW4nFO4J6iM;kDRJYY@HxlJ-2>|)pZu4LM<KOUh3ErDsMA{%qAZOUw$ zscvR?JZJVK)-qamv2krWRmhr-vcp#rkm+dl=W)$LH~WnyKCXT2=DO^$@Rb}6$4@S` zDy!WdH|zeTS5P`WCOgJYv%MecK8>qS(UCIoh@(L9F*ZXarNczOPxy50-rRltbPH<s zA!)|x#GcqI^c|On6=j}5m2?=K6mlgf$6nP%Y{F?5Ca>+lsqMcUzhGX-DG?dIeM%yw zq)6Z5tV+moc?F-@Px$g4N7@AhG2|lSEV{6lAFkjw_958<_GvD+SlP=VmQ!lVHXJsI znhY+?3E0d<$JA<%tK<^VtQR#nU@+CT{-PMJ<%52yKtV-o{8a81dy0d-O}vj9)n^7k zT4d@%G%wJ%%qhlePD%yYMMpP?=tpcJ%YZV=t3+x1nKCnh=v}&mgl&nSNPf^%ki)ze l`$yqfayHMBo}R^L^DOS^S$;Op@}8cl(m$8f+I>c;?LSw^)ujLc diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scriptdata01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scriptdata01.dat deleted file mode 100644 index 76b67f4ba60..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scriptdata01.dat +++ /dev/null @@ -1,308 +0,0 @@ -#data -FOO<script>'Hello'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'Hello'" -| "BAR" - -#data -FOO<script></script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "BAR" - -#data -FOO<script></script >BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "BAR" - -#data -FOO<script></script/>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "BAR" - -#data -FOO<script></script/ >BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "BAR" - -#data -FOO<script type="text/plain"></scriptx>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "</scriptx>BAR" - -#data -FOO<script></script foo=">" dd>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "BAR" - -#data -FOO<script>'<'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<'" -| "BAR" - -#data -FOO<script>'<!'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!'" -| "BAR" - -#data -FOO<script>'<!-'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-'" -| "BAR" - -#data -FOO<script>'<!--'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!--'" -| "BAR" - -#data -FOO<script>'<!---'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!---'" -| "BAR" - -#data -FOO<script>'<!-->'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-->'" -| "BAR" - -#data -FOO<script>'<!-->'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-->'" -| "BAR" - -#data -FOO<script>'<!-- potato'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-- potato'" -| "BAR" - -#data -FOO<script>'<!-- <sCrIpt'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-- <sCrIpt'" -| "BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt>'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt>'</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt> -'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt> -'</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt> --'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt> --'</script>BAR" - -#data -FOO<script>'<!-- <sCrIpt> -->'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| "'<!-- <sCrIpt> -->'" -| "BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt> --!>'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt> --!>'</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt> -- >'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt> -- >'</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt '</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt '</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt/'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt/'</script>BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt\'</script>BAR -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt\'" -| "BAR" - -#data -FOO<script type="text/plain">'<!-- <sCrIpt/'</script>BAR</script>QUX -#errors -#document -| <html> -| <head> -| <body> -| "FOO" -| <script> -| type="text/plain" -| "'<!-- <sCrIpt/'</script>BAR" -| "QUX" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/adoption01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/adoption01.dat deleted file mode 100644 index 4e08d0e84a0..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/adoption01.dat +++ /dev/null @@ -1,15 +0,0 @@ -#data -<p><b id="A"><script>document.getElementById("A").id = "B"</script></p>TEXT</b> -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <b> -| id="B" -| <script> -| "document.getElementById("A").id = "B"" -| <b> -| id="A" -| "TEXT" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/webkit01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/webkit01.dat deleted file mode 100644 index ef4a41ca00b..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/scripted/webkit01.dat +++ /dev/null @@ -1,28 +0,0 @@ -#data -1<script>document.write("2")</script>3 -#errors -#document -| <html> -| <head> -| <body> -| "1" -| <script> -| "document.write("2")" -| "23" - -#data -1<script>document.write("<script>document.write('2')</scr"+ "ipt><script>document.write('3')</scr" + "ipt>")</script>4 -#errors -#document -| <html> -| <head> -| <body> -| "1" -| <script> -| "document.write("<script>document.write('2')</scr"+ "ipt><script>document.write('3')</scr" + "ipt>")" -| <script> -| "document.write('2')" -| "2" -| <script> -| "document.write('3')" -| "34" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tables01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tables01.dat deleted file mode 100644 index c4b47e48a81..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tables01.dat +++ /dev/null @@ -1,212 +0,0 @@ -#data -<table><th> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <th> - -#data -<table><td> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<table><col foo='bar'> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <colgroup> -| <col> -| foo="bar" - -#data -<table><colgroup></html>foo -#errors -#document -| <html> -| <head> -| <body> -| "foo" -| <table> -| <colgroup> - -#data -<table></table><p>foo -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <p> -| "foo" - -#data -<table></body></caption></col></colgroup></html></tbody></td></tfoot></th></thead></tr><td> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<table><select><option>3</select></table> -#errors -#document -| <html> -| <head> -| <body> -| <select> -| <option> -| "3" -| <table> - -#data -<table><select><table></table></select></table> -#errors -#document -| <html> -| <head> -| <body> -| <select> -| <table> -| <table> - -#data -<table><select></table> -#errors -#document -| <html> -| <head> -| <body> -| <select> -| <table> - -#data -<table><select><option>A<tr><td>B</td></tr></table> -#errors -#document -| <html> -| <head> -| <body> -| <select> -| <option> -| "A" -| <table> -| <tbody> -| <tr> -| <td> -| "B" - -#data -<table><td></body></caption></col></colgroup></html>foo -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "foo" - -#data -<table><td>A</table>B -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "A" -| "B" - -#data -<table><tr><caption> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <caption> - -#data -<table><tr></body></caption></col></colgroup></html></td></th><td>foo -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "foo" - -#data -<table><td><tr> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <tr> - -#data -<table><td><button><td> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <button> -| <td> - -#data -<table><tr><td><svg><desc><td> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg desc> -| <td> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests1.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests1.dat deleted file mode 100644 index cbf8bdda638..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests1.dat +++ /dev/null @@ -1,1952 +0,0 @@ -#data -Test -#errors -Line: 1 Col: 4 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "Test" - -#data -<p>One<p>Two -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <p> -| "One" -| <p> -| "Two" - -#data -Line1<br>Line2<br>Line3<br>Line4 -#errors -Line: 1 Col: 5 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "Line1" -| <br> -| "Line2" -| <br> -| "Line3" -| <br> -| "Line4" - -#data -<html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<head> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<body> -#errors -Line: 1 Col: 6 Unexpected start tag (body). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head></head> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head></head><body> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head></head><body></body> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head><body></body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><head></body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -Line: 1 Col: 19 Unexpected end tag (body). -Line: 1 Col: 26 Unexpected end tag (html). -#document -| <html> -| <head> -| <body> - -#data -<html><head><body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<html><body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (body). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<head></html> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end tag (html). Ignored. -#document -| <html> -| <head> -| <body> - -#data -</head> -#errors -Line: 1 Col: 7 Unexpected end tag (head). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -</body> -#errors -Line: 1 Col: 7 Unexpected end tag (body). Expected DOCTYPE. -Line: 1 Col: 7 Unexpected end tag (body) after the (implied) root element. -#document -| <html> -| <head> -| <body> - -#data -</html> -#errors -Line: 1 Col: 7 Unexpected end tag (html). Expected DOCTYPE. -Line: 1 Col: 7 Unexpected end tag (html) after the (implied) root element. -#document -| <html> -| <head> -| <body> - -#data -<b><table><td><i></table> -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 25 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 25 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| <table> -| <tbody> -| <tr> -| <td> -| <i> - -#data -<b><table><td></b><i></table>X -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 18 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 29 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 30 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| <table> -| <tbody> -| <tr> -| <td> -| <i> -| "X" - -#data -<h1>Hello<h2>World -#errors -4: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -13: Heading cannot be a child of another heading. -18: End of file seen and there were open elements. -#document -| <html> -| <head> -| <body> -| <h1> -| "Hello" -| <h2> -| "World" - -#data -<a><p>X<a>Y</a>Z</p></a> -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 10 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 10 End tag (a) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 24 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <a> -| <p> -| <a> -| "X" -| <a> -| "Y" -| "Z" - -#data -<b><button>foo</b>bar -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 15 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <b> -| <button> -| <b> -| "foo" -| "bar" - -#data -<!DOCTYPE html><span><button>foo</span>bar -#errors -39: End tag “span” seen but there were unclosed elements. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <span> -| <button> -| "foobar" - -#data -<p><b><div><marquee></p></b></div>X -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end tag (p). Ignored. -Line: 1 Col: 24 Unexpected end tag (p). Ignored. -Line: 1 Col: 28 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 34 End tag (div) seen too early. Expected other end tag. -Line: 1 Col: 35 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <p> -| <b> -| <div> -| <b> -| <marquee> -| <p> -| "X" - -#data -<script><div></script></div><title><p></title><p><p> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 28 Unexpected end tag (div). Ignored. -#document -| <html> -| <head> -| <script> -| "<div>" -| <title> -| "<p>" -| <body> -| <p> -| <p> - -#data -<!--><div>--<!--> -#errors -Line: 1 Col: 5 Incorrect comment. -Line: 1 Col: 10 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 17 Incorrect comment. -Line: 1 Col: 17 Expected closing tag. Unexpected end of file. -#document -| <!-- --> -| <html> -| <head> -| <body> -| <div> -| "--" -| <!-- --> - -#data -<p><hr></p> -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end tag (p). Ignored. -#document -| <html> -| <head> -| <body> -| <p> -| <hr> -| <p> - -#data -<select><b><option><select><option></b></select>X -#errors -Line: 1 Col: 8 Unexpected start tag (select). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected start tag token (b) in the select phase. Ignored. -Line: 1 Col: 27 Unexpected select start tag in the select phase treated as select end tag. -Line: 1 Col: 39 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 48 Unexpected end tag (select). Ignored. -Line: 1 Col: 49 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <select> -| <option> -| <option> -| "X" - -#data -<a><table><td><a><table></table><a></tr><a></table><b>X</b>C<a>Y -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 35 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 40 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 43 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 43 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 43 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 51 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 63 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 64 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| <a> -| <table> -| <tbody> -| <tr> -| <td> -| <a> -| <table> -| <a> -| <a> -| <b> -| "X" -| "C" -| <a> -| "Y" - -#data -<a X>0<b>1<a Y>2 -#errors -Line: 1 Col: 5 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 15 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 15 End tag (a) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 16 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| x="" -| "0" -| <b> -| "1" -| <b> -| <a> -| y="" -| "2" - -#data -<!-----><font><div>hello<table>excite!<b>me!<th><i>please!</tr><!--X--> -#errors -Line: 1 Col: 7 Unexpected '-' after '--' found in comment. -Line: 1 Col: 14 Unexpected start tag (font). Expected DOCTYPE. -Line: 1 Col: 38 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 41 Unexpected start tag (b) in table context caused voodoo mode. -Line: 1 Col: 48 Unexpected implied end tag (b) in the table phase. -Line: 1 Col: 48 Unexpected table cell start tag (th) in the table body phase. -Line: 1 Col: 63 Got table cell end tag (th) while required end tags are missing. -Line: 1 Col: 71 Unexpected end of file. Expected table content. -#document -| <!-- - --> -| <html> -| <head> -| <body> -| <font> -| <div> -| "helloexcite!" -| <b> -| "me!" -| <table> -| <tbody> -| <tr> -| <th> -| <i> -| "please!" -| <!-- X --> - -#data -<!DOCTYPE html><li>hello<li>world<ul>how<li>do</ul>you</body><!--do--> -#errors -Line: 1 Col: 61 Unexpected end tag (li). Missing end tag (body). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <li> -| "hello" -| <li> -| "world" -| <ul> -| "how" -| <li> -| "do" -| "you" -| <!-- do --> - -#data -<!DOCTYPE html>A<option>B<optgroup>C<select>D</option>E -#errors -Line: 1 Col: 54 Unexpected end tag (option) in the select phase. Ignored. -Line: 1 Col: 55 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "A" -| <option> -| "B" -| <optgroup> -| "C" -| <select> -| "DE" - -#data -< -#errors -Line: 1 Col: 1 Expected tag name. Got something else instead -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "<" - -#data -<# -#errors -Line: 1 Col: 1 Expected tag name. Got something else instead -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "<#" - -#data -</ -#errors -Line: 1 Col: 2 Expected closing tag. Unexpected end of file. -Line: 1 Col: 2 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "</" - -#data -</# -#errors -Line: 1 Col: 2 Expected closing tag. Unexpected character '#' found. -Line: 1 Col: 3 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- # --> -| <html> -| <head> -| <body> - -#data -<? -#errors -Line: 1 Col: 1 Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.) -Line: 1 Col: 2 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- ? --> -| <html> -| <head> -| <body> - -#data -<?# -#errors -Line: 1 Col: 1 Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.) -Line: 1 Col: 3 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- ?# --> -| <html> -| <head> -| <body> - -#data -<! -#errors -Line: 1 Col: 2 Expected '--' or 'DOCTYPE'. Not found. -Line: 1 Col: 2 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- --> -| <html> -| <head> -| <body> - -#data -<!# -#errors -Line: 1 Col: 3 Expected '--' or 'DOCTYPE'. Not found. -Line: 1 Col: 3 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- # --> -| <html> -| <head> -| <body> - -#data -<?COMMENT?> -#errors -Line: 1 Col: 1 Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.) -Line: 1 Col: 11 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- ?COMMENT? --> -| <html> -| <head> -| <body> - -#data -<!COMMENT> -#errors -Line: 1 Col: 2 Expected '--' or 'DOCTYPE'. Not found. -Line: 1 Col: 10 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- COMMENT --> -| <html> -| <head> -| <body> - -#data -</ COMMENT > -#errors -Line: 1 Col: 2 Expected closing tag. Unexpected character ' ' found. -Line: 1 Col: 12 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- COMMENT --> -| <html> -| <head> -| <body> - -#data -<?COM--MENT?> -#errors -Line: 1 Col: 1 Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.) -Line: 1 Col: 13 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- ?COM--MENT? --> -| <html> -| <head> -| <body> - -#data -<!COM--MENT> -#errors -Line: 1 Col: 2 Expected '--' or 'DOCTYPE'. Not found. -Line: 1 Col: 12 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- COM--MENT --> -| <html> -| <head> -| <body> - -#data -</ COM--MENT > -#errors -Line: 1 Col: 2 Expected closing tag. Unexpected character ' ' found. -Line: 1 Col: 14 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- COM--MENT --> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><style> EOF -#errors -Line: 1 Col: 26 Unexpected end of file. Expected end tag (style). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| " EOF" -| <body> - -#data -<!DOCTYPE html><script> <!-- </script> --> </script> EOF -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| " <!-- " -| " " -| <body> -| "--> EOF" - -#data -<b><p></b>TEST -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 10 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <b> -| <p> -| <b> -| "TEST" - -#data -<p id=a><b><p id=b></b>TEST -#errors -Line: 1 Col: 8 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 19 Unexpected end tag (p). Ignored. -Line: 1 Col: 23 End tag (b) violates step 1, paragraph 2 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <p> -| id="a" -| <b> -| <p> -| id="b" -| "TEST" - -#data -<b id=a><p><b id=b></p></b>TEST -#errors -Line: 1 Col: 8 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end tag (p). Ignored. -Line: 1 Col: 27 End tag (b) violates step 1, paragraph 2 of the adoption agency algorithm. -Line: 1 Col: 31 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| id="a" -| <p> -| <b> -| id="b" -| "TEST" - -#data -<!DOCTYPE html><title>U-test</title><body><div><p>Test<u></p></div></body> -#errors -Line: 1 Col: 61 Unexpected end tag (p). Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "U-test" -| <body> -| <div> -| <p> -| "Test" -| <u> - -#data -<!DOCTYPE html><font><table></font></table></font> -#errors -Line: 1 Col: 35 Unexpected end tag (font) in table context caused voodoo mode. -Line: 1 Col: 35 End tag (font) violates step 1, paragraph 1 of the adoption agency algorithm. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <font> -| <table> - -#data -<font><p>hello<b>cruel</font>world -#errors -Line: 1 Col: 6 Unexpected start tag (font). Expected DOCTYPE. -Line: 1 Col: 29 End tag (font) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 29 End tag (font) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 34 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <font> -| <p> -| <font> -| "hello" -| <b> -| "cruel" -| <b> -| "world" - -#data -<b>Test</i>Test -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 11 End tag (i) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 15 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| "TestTest" - -#data -<b>A<cite>B<div>C -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 17 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| "A" -| <cite> -| "B" -| <div> -| "C" - -#data -<b>A<cite>B<div>C</cite>D -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 24 Unexpected end tag (cite). Ignored. -Line: 1 Col: 25 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| "A" -| <cite> -| "B" -| <div> -| "CD" - -#data -<b>A<cite>B<div>C</b>D -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 21 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 22 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| "A" -| <cite> -| "B" -| <div> -| <b> -| "C" -| "D" - -#data - -#errors -Line: 1 Col: 0 Unexpected End of file. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<DIV> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 5 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> - -#data -<DIV> abc -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 9 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc" - -#data -<DIV> abc <B> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 13 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> - -#data -<DIV> abc <B> def -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 17 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def" - -#data -<DIV> abc <B> def <I> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 21 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> - -#data -<DIV> abc <B> def <I> ghi -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 25 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi" - -#data -<DIV> abc <B> def <I> ghi <P> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 29 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <p> - -#data -<DIV> abc <B> def <I> ghi <P> jkl -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 33 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <p> -| " jkl" - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 38 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <b> -| " jkl " - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> mno -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 42 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <b> -| " jkl " -| " mno" - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> mno </I> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 47 End tag (i) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 47 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <i> -| <b> -| " jkl " -| " mno " - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> mno </I> pqr -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 47 End tag (i) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 51 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <i> -| <b> -| " jkl " -| " mno " -| " pqr" - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> mno </I> pqr </P> -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 47 End tag (i) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 56 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <i> -| <b> -| " jkl " -| " mno " -| " pqr " - -#data -<DIV> abc <B> def <I> ghi <P> jkl </B> mno </I> pqr </P> stu -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 38 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 47 End tag (i) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 60 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " abc " -| <b> -| " def " -| <i> -| " ghi " -| <i> -| <p> -| <i> -| <b> -| " jkl " -| " mno " -| " pqr " -| " stu" - -#data -<test attribute----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------> -#errors -Line: 1 Col: 1040 Unexpected start tag (test). Expected DOCTYPE. -Line: 1 Col: 1040 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <test> -| attribute----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------="" - -#data -<a href="blah">aba<table><a href="foo">br<tr><td></td></tr>x</table>aoe -#errors -Line: 1 Col: 15 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 39 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 39 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 39 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 45 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 68 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 71 Expected closing tag. Unexpected end of file. - -#document -| <html> -| <head> -| <body> -| <a> -| href="blah" -| "aba" -| <a> -| href="foo" -| "br" -| <a> -| href="foo" -| "x" -| <table> -| <tbody> -| <tr> -| <td> -| <a> -| href="foo" -| "aoe" - -#data -<a href="blah">aba<table><tr><td><a href="foo">br</td></tr>x</table>aoe -#errors -Line: 1 Col: 15 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 54 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 60 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 71 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| href="blah" -| "abax" -| <table> -| <tbody> -| <tr> -| <td> -| <a> -| href="foo" -| "br" -| "aoe" - -#data -<table><a href="blah">aba<tr><td><a href="foo">br</td></tr>x</table>aoe -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 29 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 54 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 68 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 71 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| href="blah" -| "aba" -| <a> -| href="blah" -| "x" -| <table> -| <tbody> -| <tr> -| <td> -| <a> -| href="foo" -| "br" -| <a> -| href="blah" -| "aoe" - -#data -<a href=a>aa<marquee>aa<a href=b>bb</marquee>aa -#errors -Line: 1 Col: 10 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 45 End tag (marquee) seen too early. Expected other end tag. -Line: 1 Col: 47 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| href="a" -| "aa" -| <marquee> -| "aa" -| <a> -| href="b" -| "bb" -| "aa" - -#data -<wbr><strike><code></strike><code><strike></code> -#errors -Line: 1 Col: 5 Unexpected start tag (wbr). Expected DOCTYPE. -Line: 1 Col: 28 End tag (strike) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 49 Unexpected end tag (code). Ignored. -#document -| <html> -| <head> -| <body> -| <wbr> -| <strike> -| <code> -| <code> -| <code> -| <strike> - -#data -<!DOCTYPE html><spacer>foo -#errors -26: End of file seen and there were open elements. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <spacer> -| "foo" - -#data -<title><meta></title><link><title><meta></title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| "<meta>" -| <link> -| <title> -| "<meta>" -| <body> - -#data -<style><!--</style><meta><script>--><link></script> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 51 Unexpected end of file. Expected end tag (style). -#document -| <html> -| <head> -| <style> -| "<!--" -| <meta> -| <script> -| "--><link>" -| <body> - -#data -<head><meta></head><link> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 25 Unexpected start tag (link) that can be in head. Moved. -#document -| <html> -| <head> -| <meta> -| <link> -| <body> - -#data -<table><tr><tr><td><td><span><th><span>X</table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 33 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 48 Got table cell end tag (th) while required end tags are missing. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <tr> -| <td> -| <td> -| <span> -| <th> -| <span> -| "X" - -#data -<body><body><base><link><meta><title><p></title><body><p></body> -#errors -Line: 1 Col: 6 Unexpected start tag (body). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected start tag (body). -Line: 1 Col: 54 Unexpected start tag (body). -Line: 1 Col: 64 Unexpected end tag (p). Missing end tag (body). -#document -| <html> -| <head> -| <body> -| <base> -| <link> -| <meta> -| <title> -| "<p>" -| <p> - -#data -<textarea><p></textarea> -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <textarea> -| "<p>" - -#data -<p><image></p> -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 10 Unexpected start tag (image). Treated as img. -#document -| <html> -| <head> -| <body> -| <p> -| <img> - -#data -<a><table><a></table><p><a><div><a> -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 13 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 13 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 21 Unexpected end tag (table). Expected end tag (a). -Line: 1 Col: 27 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 27 End tag (a) violates step 1, paragraph 2 of the adoption agency algorithm. -Line: 1 Col: 32 Unexpected end tag (p). Ignored. -Line: 1 Col: 35 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 35 End tag (a) violates step 1, paragraph 2 of the adoption agency algorithm. -Line: 1 Col: 35 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| <a> -| <table> -| <p> -| <a> -| <div> -| <a> - -#data -<head></p><meta><p> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 10 Unexpected end tag (p). Ignored. -#document -| <html> -| <head> -| <meta> -| <body> -| <p> - -#data -<head></html><meta><p> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 19 Unexpected start tag (meta). -#document -| <html> -| <head> -| <body> -| <meta> -| <p> - -#data -<b><table><td><i></table> -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 25 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 25 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| <table> -| <tbody> -| <tr> -| <td> -| <i> - -#data -<b><table><td></b><i></table> -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 18 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 29 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 29 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| <table> -| <tbody> -| <tr> -| <td> -| <i> - -#data -<h1><h2> -#errors -4: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -8: Heading cannot be a child of another heading. -8: End of file seen and there were open elements. -#document -| <html> -| <head> -| <body> -| <h1> -| <h2> - -#data -<a><p><a></a></p></a> -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 9 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 9 End tag (a) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 21 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <a> -| <p> -| <a> -| <a> - -#data -<b><button></b></button></b> -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 15 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <b> -| <button> -| <b> - -#data -<p><b><div><marquee></p></b></div> -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end tag (p). Ignored. -Line: 1 Col: 24 Unexpected end tag (p). Ignored. -Line: 1 Col: 28 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 34 End tag (div) seen too early. Expected other end tag. -Line: 1 Col: 34 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <p> -| <b> -| <div> -| <b> -| <marquee> -| <p> - -#data -<script></script></div><title></title><p><p> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end tag (div). Ignored. -#document -| <html> -| <head> -| <script> -| <title> -| <body> -| <p> -| <p> - -#data -<p><hr></p> -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end tag (p). Ignored. -#document -| <html> -| <head> -| <body> -| <p> -| <hr> -| <p> - -#data -<select><b><option><select><option></b></select> -#errors -Line: 1 Col: 8 Unexpected start tag (select). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected start tag token (b) in the select phase. Ignored. -Line: 1 Col: 27 Unexpected select start tag in the select phase treated as select end tag. -Line: 1 Col: 39 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 48 Unexpected end tag (select). Ignored. -Line: 1 Col: 48 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <select> -| <option> -| <option> - -#data -<html><head><title></title><body></body></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| <body> - -#data -<a><table><td><a><table></table><a></tr><a></table><a> -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 35 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 40 Got table cell end tag (td) while required end tags are missing. -Line: 1 Col: 43 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 43 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 43 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 51 Unexpected implied end tag (a) in the table phase. -Line: 1 Col: 54 Unexpected start tag (a) implies end tag (a). -Line: 1 Col: 54 End tag (a) violates step 1, paragraph 2 of the adoption agency algorithm. -Line: 1 Col: 54 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| <a> -| <table> -| <tbody> -| <tr> -| <td> -| <a> -| <table> -| <a> -| <a> - -#data -<ul><li></li><div><li></div><li><li><div><li><address><li><b><em></b><li></ul> -#errors -Line: 1 Col: 4 Unexpected start tag (ul). Expected DOCTYPE. -Line: 1 Col: 45 Missing end tag (div, li). -Line: 1 Col: 58 Missing end tag (address, li). -Line: 1 Col: 69 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -#document -| <html> -| <head> -| <body> -| <ul> -| <li> -| <div> -| <li> -| <li> -| <li> -| <div> -| <li> -| <address> -| <li> -| <b> -| <em> -| <li> - -#data -<ul><li><ul></li><li>a</li></ul></li></ul> -#errors -XXX: fix me -#document -| <html> -| <head> -| <body> -| <ul> -| <li> -| <ul> -| <li> -| "a" - -#data -<frameset><frame><frameset><frame></frameset><noframes></noframes></frameset> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -#document -| <html> -| <head> -| <frameset> -| <frame> -| <frameset> -| <frame> -| <noframes> - -#data -<h1><table><td><h3></table><h3></h1> -#errors -4: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -15: “td” start tag in table body. -27: Unclosed elements. -31: Heading cannot be a child of another heading. -36: End tag “h1” seen but there were unclosed elements. -#document -| <html> -| <head> -| <body> -| <h1> -| <table> -| <tbody> -| <tr> -| <td> -| <h3> -| <h3> - -#data -<table><colgroup><col><colgroup><col><col><col><colgroup><col><col><thead><tr><td></table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <table> -| <colgroup> -| <col> -| <colgroup> -| <col> -| <col> -| <col> -| <colgroup> -| <col> -| <col> -| <thead> -| <tr> -| <td> - -#data -<table><col><tbody><col><tr><col><td><col></table><col> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 37 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 55 Unexpected start tag col. Ignored. -#document -| <html> -| <head> -| <body> -| <table> -| <colgroup> -| <col> -| <tbody> -| <colgroup> -| <col> -| <tbody> -| <tr> -| <colgroup> -| <col> -| <tbody> -| <tr> -| <td> -| <colgroup> -| <col> - -#data -<table><colgroup><tbody><colgroup><tr><colgroup><td><colgroup></table><colgroup> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 52 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 80 Unexpected start tag colgroup. Ignored. -#document -| <html> -| <head> -| <body> -| <table> -| <colgroup> -| <tbody> -| <colgroup> -| <tbody> -| <tr> -| <colgroup> -| <tbody> -| <tr> -| <td> -| <colgroup> - -#data -</strong></b></em></i></u></strike></s></blink></tt></pre></big></small></font></select></h1></h2></h3></h4></h5></h6></body></br></a></img></title></span></style></script></table></th></td></tr></frame></area></link></param></hr></input></col></base></meta></basefont></bgsound></embed></spacer></p></dd></dt></caption></colgroup></tbody></tfoot></thead></address></blockquote></center></dir></div></dl></fieldset></listing></menu></ol></ul></li></nobr></wbr></form></button></marquee></object></html></frameset></head></iframe></image></isindex></noembed></noframes></noscript></optgroup></option></plaintext></textarea> -#errors -Line: 1 Col: 9 Unexpected end tag (strong). Expected DOCTYPE. -Line: 1 Col: 9 Unexpected end tag (strong) after the (implied) root element. -Line: 1 Col: 13 Unexpected end tag (b) after the (implied) root element. -Line: 1 Col: 18 Unexpected end tag (em) after the (implied) root element. -Line: 1 Col: 22 Unexpected end tag (i) after the (implied) root element. -Line: 1 Col: 26 Unexpected end tag (u) after the (implied) root element. -Line: 1 Col: 35 Unexpected end tag (strike) after the (implied) root element. -Line: 1 Col: 39 Unexpected end tag (s) after the (implied) root element. -Line: 1 Col: 47 Unexpected end tag (blink) after the (implied) root element. -Line: 1 Col: 52 Unexpected end tag (tt) after the (implied) root element. -Line: 1 Col: 58 Unexpected end tag (pre) after the (implied) root element. -Line: 1 Col: 64 Unexpected end tag (big) after the (implied) root element. -Line: 1 Col: 72 Unexpected end tag (small) after the (implied) root element. -Line: 1 Col: 79 Unexpected end tag (font) after the (implied) root element. -Line: 1 Col: 88 Unexpected end tag (select) after the (implied) root element. -Line: 1 Col: 93 Unexpected end tag (h1) after the (implied) root element. -Line: 1 Col: 98 Unexpected end tag (h2) after the (implied) root element. -Line: 1 Col: 103 Unexpected end tag (h3) after the (implied) root element. -Line: 1 Col: 108 Unexpected end tag (h4) after the (implied) root element. -Line: 1 Col: 113 Unexpected end tag (h5) after the (implied) root element. -Line: 1 Col: 118 Unexpected end tag (h6) after the (implied) root element. -Line: 1 Col: 125 Unexpected end tag (body) after the (implied) root element. -Line: 1 Col: 130 Unexpected end tag (br). Treated as br element. -Line: 1 Col: 134 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 140 This element (img) has no end tag. -Line: 1 Col: 148 Unexpected end tag (title). Ignored. -Line: 1 Col: 155 Unexpected end tag (span). Ignored. -Line: 1 Col: 163 Unexpected end tag (style). Ignored. -Line: 1 Col: 172 Unexpected end tag (script). Ignored. -Line: 1 Col: 180 Unexpected end tag (table). Ignored. -Line: 1 Col: 185 Unexpected end tag (th). Ignored. -Line: 1 Col: 190 Unexpected end tag (td). Ignored. -Line: 1 Col: 195 Unexpected end tag (tr). Ignored. -Line: 1 Col: 203 This element (frame) has no end tag. -Line: 1 Col: 210 This element (area) has no end tag. -Line: 1 Col: 217 Unexpected end tag (link). Ignored. -Line: 1 Col: 225 This element (param) has no end tag. -Line: 1 Col: 230 This element (hr) has no end tag. -Line: 1 Col: 238 This element (input) has no end tag. -Line: 1 Col: 244 Unexpected end tag (col). Ignored. -Line: 1 Col: 251 Unexpected end tag (base). Ignored. -Line: 1 Col: 258 Unexpected end tag (meta). Ignored. -Line: 1 Col: 269 This element (basefont) has no end tag. -Line: 1 Col: 279 This element (bgsound) has no end tag. -Line: 1 Col: 287 This element (embed) has no end tag. -Line: 1 Col: 296 This element (spacer) has no end tag. -Line: 1 Col: 300 Unexpected end tag (p). Ignored. -Line: 1 Col: 305 End tag (dd) seen too early. Expected other end tag. -Line: 1 Col: 310 End tag (dt) seen too early. Expected other end tag. -Line: 1 Col: 320 Unexpected end tag (caption). Ignored. -Line: 1 Col: 331 Unexpected end tag (colgroup). Ignored. -Line: 1 Col: 339 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 347 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 355 Unexpected end tag (thead). Ignored. -Line: 1 Col: 365 End tag (address) seen too early. Expected other end tag. -Line: 1 Col: 378 End tag (blockquote) seen too early. Expected other end tag. -Line: 1 Col: 387 End tag (center) seen too early. Expected other end tag. -Line: 1 Col: 393 Unexpected end tag (dir). Ignored. -Line: 1 Col: 399 End tag (div) seen too early. Expected other end tag. -Line: 1 Col: 404 End tag (dl) seen too early. Expected other end tag. -Line: 1 Col: 415 End tag (fieldset) seen too early. Expected other end tag. -Line: 1 Col: 425 End tag (listing) seen too early. Expected other end tag. -Line: 1 Col: 432 End tag (menu) seen too early. Expected other end tag. -Line: 1 Col: 437 End tag (ol) seen too early. Expected other end tag. -Line: 1 Col: 442 End tag (ul) seen too early. Expected other end tag. -Line: 1 Col: 447 End tag (li) seen too early. Expected other end tag. -Line: 1 Col: 454 End tag (nobr) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 460 This element (wbr) has no end tag. -Line: 1 Col: 476 End tag (button) seen too early. Expected other end tag. -Line: 1 Col: 486 End tag (marquee) seen too early. Expected other end tag. -Line: 1 Col: 495 End tag (object) seen too early. Expected other end tag. -Line: 1 Col: 513 Unexpected end tag (html). Ignored. -Line: 1 Col: 513 Unexpected end tag (frameset). Ignored. -Line: 1 Col: 520 Unexpected end tag (head). Ignored. -Line: 1 Col: 529 Unexpected end tag (iframe). Ignored. -Line: 1 Col: 537 This element (image) has no end tag. -Line: 1 Col: 547 This element (isindex) has no end tag. -Line: 1 Col: 557 Unexpected end tag (noembed). Ignored. -Line: 1 Col: 568 Unexpected end tag (noframes). Ignored. -Line: 1 Col: 579 Unexpected end tag (noscript). Ignored. -Line: 1 Col: 590 Unexpected end tag (optgroup). Ignored. -Line: 1 Col: 599 Unexpected end tag (option). Ignored. -Line: 1 Col: 611 Unexpected end tag (plaintext). Ignored. -Line: 1 Col: 622 Unexpected end tag (textarea). Ignored. -#document -| <html> -| <head> -| <body> -| <br> -| <p> - -#data -<table><tr></strong></b></em></i></u></strike></s></blink></tt></pre></big></small></font></select></h1></h2></h3></h4></h5></h6></body></br></a></img></title></span></style></script></table></th></td></tr></frame></area></link></param></hr></input></col></base></meta></basefont></bgsound></embed></spacer></p></dd></dt></caption></colgroup></tbody></tfoot></thead></address></blockquote></center></dir></div></dl></fieldset></listing></menu></ol></ul></li></nobr></wbr></form></button></marquee></object></html></frameset></head></iframe></image></isindex></noembed></noframes></noscript></optgroup></option></plaintext></textarea> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end tag (strong) in table context caused voodoo mode. -Line: 1 Col: 20 End tag (strong) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 24 Unexpected end tag (b) in table context caused voodoo mode. -Line: 1 Col: 24 End tag (b) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 29 Unexpected end tag (em) in table context caused voodoo mode. -Line: 1 Col: 29 End tag (em) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 33 Unexpected end tag (i) in table context caused voodoo mode. -Line: 1 Col: 33 End tag (i) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 37 Unexpected end tag (u) in table context caused voodoo mode. -Line: 1 Col: 37 End tag (u) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 46 Unexpected end tag (strike) in table context caused voodoo mode. -Line: 1 Col: 46 End tag (strike) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 50 Unexpected end tag (s) in table context caused voodoo mode. -Line: 1 Col: 50 End tag (s) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 58 Unexpected end tag (blink) in table context caused voodoo mode. -Line: 1 Col: 58 Unexpected end tag (blink). Ignored. -Line: 1 Col: 63 Unexpected end tag (tt) in table context caused voodoo mode. -Line: 1 Col: 63 End tag (tt) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 69 Unexpected end tag (pre) in table context caused voodoo mode. -Line: 1 Col: 69 End tag (pre) seen too early. Expected other end tag. -Line: 1 Col: 75 Unexpected end tag (big) in table context caused voodoo mode. -Line: 1 Col: 75 End tag (big) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 83 Unexpected end tag (small) in table context caused voodoo mode. -Line: 1 Col: 83 End tag (small) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 90 Unexpected end tag (font) in table context caused voodoo mode. -Line: 1 Col: 90 End tag (font) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 99 Unexpected end tag (select) in table context caused voodoo mode. -Line: 1 Col: 99 Unexpected end tag (select). Ignored. -Line: 1 Col: 104 Unexpected end tag (h1) in table context caused voodoo mode. -Line: 1 Col: 104 End tag (h1) seen too early. Expected other end tag. -Line: 1 Col: 109 Unexpected end tag (h2) in table context caused voodoo mode. -Line: 1 Col: 109 End tag (h2) seen too early. Expected other end tag. -Line: 1 Col: 114 Unexpected end tag (h3) in table context caused voodoo mode. -Line: 1 Col: 114 End tag (h3) seen too early. Expected other end tag. -Line: 1 Col: 119 Unexpected end tag (h4) in table context caused voodoo mode. -Line: 1 Col: 119 End tag (h4) seen too early. Expected other end tag. -Line: 1 Col: 124 Unexpected end tag (h5) in table context caused voodoo mode. -Line: 1 Col: 124 End tag (h5) seen too early. Expected other end tag. -Line: 1 Col: 129 Unexpected end tag (h6) in table context caused voodoo mode. -Line: 1 Col: 129 End tag (h6) seen too early. Expected other end tag. -Line: 1 Col: 136 Unexpected end tag (body) in the table row phase. Ignored. -Line: 1 Col: 141 Unexpected end tag (br) in table context caused voodoo mode. -Line: 1 Col: 141 Unexpected end tag (br). Treated as br element. -Line: 1 Col: 145 Unexpected end tag (a) in table context caused voodoo mode. -Line: 1 Col: 145 End tag (a) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 151 Unexpected end tag (img) in table context caused voodoo mode. -Line: 1 Col: 151 This element (img) has no end tag. -Line: 1 Col: 159 Unexpected end tag (title) in table context caused voodoo mode. -Line: 1 Col: 159 Unexpected end tag (title). Ignored. -Line: 1 Col: 166 Unexpected end tag (span) in table context caused voodoo mode. -Line: 1 Col: 166 Unexpected end tag (span). Ignored. -Line: 1 Col: 174 Unexpected end tag (style) in table context caused voodoo mode. -Line: 1 Col: 174 Unexpected end tag (style). Ignored. -Line: 1 Col: 183 Unexpected end tag (script) in table context caused voodoo mode. -Line: 1 Col: 183 Unexpected end tag (script). Ignored. -Line: 1 Col: 196 Unexpected end tag (th). Ignored. -Line: 1 Col: 201 Unexpected end tag (td). Ignored. -Line: 1 Col: 206 Unexpected end tag (tr). Ignored. -Line: 1 Col: 214 This element (frame) has no end tag. -Line: 1 Col: 221 This element (area) has no end tag. -Line: 1 Col: 228 Unexpected end tag (link). Ignored. -Line: 1 Col: 236 This element (param) has no end tag. -Line: 1 Col: 241 This element (hr) has no end tag. -Line: 1 Col: 249 This element (input) has no end tag. -Line: 1 Col: 255 Unexpected end tag (col). Ignored. -Line: 1 Col: 262 Unexpected end tag (base). Ignored. -Line: 1 Col: 269 Unexpected end tag (meta). Ignored. -Line: 1 Col: 280 This element (basefont) has no end tag. -Line: 1 Col: 290 This element (bgsound) has no end tag. -Line: 1 Col: 298 This element (embed) has no end tag. -Line: 1 Col: 307 This element (spacer) has no end tag. -Line: 1 Col: 311 Unexpected end tag (p). Ignored. -Line: 1 Col: 316 End tag (dd) seen too early. Expected other end tag. -Line: 1 Col: 321 End tag (dt) seen too early. Expected other end tag. -Line: 1 Col: 331 Unexpected end tag (caption). Ignored. -Line: 1 Col: 342 Unexpected end tag (colgroup). Ignored. -Line: 1 Col: 350 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 358 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 366 Unexpected end tag (thead). Ignored. -Line: 1 Col: 376 End tag (address) seen too early. Expected other end tag. -Line: 1 Col: 389 End tag (blockquote) seen too early. Expected other end tag. -Line: 1 Col: 398 End tag (center) seen too early. Expected other end tag. -Line: 1 Col: 404 Unexpected end tag (dir). Ignored. -Line: 1 Col: 410 End tag (div) seen too early. Expected other end tag. -Line: 1 Col: 415 End tag (dl) seen too early. Expected other end tag. -Line: 1 Col: 426 End tag (fieldset) seen too early. Expected other end tag. -Line: 1 Col: 436 End tag (listing) seen too early. Expected other end tag. -Line: 1 Col: 443 End tag (menu) seen too early. Expected other end tag. -Line: 1 Col: 448 End tag (ol) seen too early. Expected other end tag. -Line: 1 Col: 453 End tag (ul) seen too early. Expected other end tag. -Line: 1 Col: 458 End tag (li) seen too early. Expected other end tag. -Line: 1 Col: 465 End tag (nobr) violates step 1, paragraph 1 of the adoption agency algorithm. -Line: 1 Col: 471 This element (wbr) has no end tag. -Line: 1 Col: 487 End tag (button) seen too early. Expected other end tag. -Line: 1 Col: 497 End tag (marquee) seen too early. Expected other end tag. -Line: 1 Col: 506 End tag (object) seen too early. Expected other end tag. -Line: 1 Col: 524 Unexpected end tag (html). Ignored. -Line: 1 Col: 524 Unexpected end tag (frameset). Ignored. -Line: 1 Col: 531 Unexpected end tag (head). Ignored. -Line: 1 Col: 540 Unexpected end tag (iframe). Ignored. -Line: 1 Col: 548 This element (image) has no end tag. -Line: 1 Col: 558 This element (isindex) has no end tag. -Line: 1 Col: 568 Unexpected end tag (noembed). Ignored. -Line: 1 Col: 579 Unexpected end tag (noframes). Ignored. -Line: 1 Col: 590 Unexpected end tag (noscript). Ignored. -Line: 1 Col: 601 Unexpected end tag (optgroup). Ignored. -Line: 1 Col: 610 Unexpected end tag (option). Ignored. -Line: 1 Col: 622 Unexpected end tag (plaintext). Ignored. -Line: 1 Col: 633 Unexpected end tag (textarea). Ignored. -#document -| <html> -| <head> -| <body> -| <br> -| <table> -| <tbody> -| <tr> -| <p> - -#data -<frameset> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 1 Col: 10 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <frameset> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests10.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests10.dat deleted file mode 100644 index 4f8df86f208..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests10.dat +++ /dev/null @@ -1,799 +0,0 @@ -#data -<!DOCTYPE html><svg></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> - -#data -<!DOCTYPE html><svg></svg><![CDATA[a]]> -#errors -29: Bogus comment -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <!-- [CDATA[a]] --> - -#data -<!DOCTYPE html><body><svg></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> - -#data -<!DOCTYPE html><body><select><svg></svg></select> -#errors -35: Stray “svg” start tag. -42: Stray end tag “svg” -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!DOCTYPE html><body><select><option><svg></svg></option></select> -#errors -43: Stray “svg” start tag. -50: Stray end tag “svg” -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> - -#data -<!DOCTYPE html><body><table><svg></svg></table> -#errors -34: Start tag “svg” seen in “table”. -41: Stray end tag “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <table> - -#data -<!DOCTYPE html><body><table><svg><g>foo</g></svg></table> -#errors -34: Start tag “svg” seen in “table”. -46: Stray end tag “g”. -53: Stray end tag “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <table> - -#data -<!DOCTYPE html><body><table><svg><g>foo</g><g>bar</g></svg></table> -#errors -34: Start tag “svg” seen in “table”. -46: Stray end tag “g”. -58: Stray end tag “g”. -65: Stray end tag “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <table> - -#data -<!DOCTYPE html><body><table><tbody><svg><g>foo</g><g>bar</g></svg></tbody></table> -#errors -41: Start tag “svg” seen in “table”. -53: Stray end tag “g”. -65: Stray end tag “g”. -72: Stray end tag “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <table> -| <tbody> - -#data -<!DOCTYPE html><body><table><tbody><tr><svg><g>foo</g><g>bar</g></svg></tr></tbody></table> -#errors -45: Start tag “svg” seen in “table”. -57: Stray end tag “g”. -69: Stray end tag “g”. -76: Stray end tag “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <table> -| <tbody> -| <tr> - -#data -<!DOCTYPE html><body><table><tbody><tr><td><svg><g>foo</g><g>bar</g></svg></td></tr></tbody></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" - -#data -<!DOCTYPE html><body><table><tbody><tr><td><svg><g>foo</g><g>bar</g></svg><p>baz</td></tr></tbody></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body><table><caption><svg><g>foo</g><g>bar</g></svg><p>baz</caption></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body><table><caption><svg><g>foo</g><g>bar</g><p>baz</table><p>quux -#errors -70: HTML start tag “p” in a foreign namespace context. -81: “table” closed but “caption” was still open. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><caption><svg><g>foo</g><g>bar</g>baz</table><p>quux -#errors -78: “table” closed but “caption” was still open. -78: Unclosed elements on stack. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| "baz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><colgroup><svg><g>foo</g><g>bar</g><p>baz</table><p>quux -#errors -44: Start tag “svg” seen in “table”. -56: Stray end tag “g”. -68: Stray end tag “g”. -71: HTML start tag “p” in a foreign namespace context. -71: Start tag “p” seen in “table”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" -| <table> -| <colgroup> -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><tr><td><select><svg><g>foo</g><g>bar</g><p>baz</table><p>quux -#errors -50: Stray “svg” start tag. -54: Stray “g” start tag. -62: Stray end tag “g” -66: Stray “g” start tag. -74: Stray end tag “g” -77: Stray “p” start tag. -88: “table” end tag with “select” open. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <select> -| "foobarbaz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><select><svg><g>foo</g><g>bar</g><p>baz</table><p>quux -#errors -36: Start tag “select” seen in “table”. -42: Stray “svg” start tag. -46: Stray “g” start tag. -54: Stray end tag “g” -58: Stray “g” start tag. -66: Stray end tag “g” -69: Stray “p” start tag. -80: “table” end tag with “select” open. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| "foobarbaz" -| <table> -| <p> -| "quux" - -#data -<!DOCTYPE html><body></body></html><svg><g>foo</g><g>bar</g><p>baz -#errors -41: Stray “svg” start tag. -68: HTML start tag “p” in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body></body><svg><g>foo</g><g>bar</g><p>baz -#errors -34: Stray “svg” start tag. -61: HTML start tag “p” in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg g> -| "foo" -| <svg g> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><frameset><svg><g></g><g></g><p><span> -#errors -31: Stray “svg” start tag. -35: Stray “g” start tag. -40: Stray end tag “g” -44: Stray “g” start tag. -49: Stray end tag “g” -52: Stray “p” start tag. -58: Stray “span” start tag. -58: End of file seen and there were open elements. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><frameset></frameset><svg><g></g><g></g><p><span> -#errors -42: Stray “svg” start tag. -46: Stray “g” start tag. -51: Stray end tag “g” -55: Stray “g” start tag. -60: Stray end tag “g” -63: Stray “p” start tag. -69: Stray “span” start tag. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><body xlink:href=foo><svg xlink:href=foo></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| <svg svg> -| xlink href="foo" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><svg><g xml:lang=en xlink:href=foo></g></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <svg svg> -| <svg g> -| xlink href="foo" -| xml lang="en" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><svg><g xml:lang=en xlink:href=foo /></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <svg svg> -| <svg g> -| xlink href="foo" -| xml lang="en" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><svg><g xml:lang=en xlink:href=foo />bar</svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <svg svg> -| <svg g> -| xlink href="foo" -| xml lang="en" -| "bar" - -#data -<svg></path> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> - -#data -<div><svg></div>a -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| "a" - -#data -<div><svg><path></div>a -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| <svg path> -| "a" - -#data -<div><svg><path></svg><path> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| <svg path> -| <path> - -#data -<div><svg><path><foreignObject><math></div>a -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| <svg path> -| <svg foreignObject> -| <math math> -| "a" - -#data -<div><svg><path><foreignObject><p></div>a -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| <svg path> -| <svg foreignObject> -| <p> -| "a" - -#data -<!DOCTYPE html><svg><desc><div><svg><ul>a -#errors -40: HTML start tag “ul” in a foreign namespace context. -41: End of file in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg desc> -| <div> -| <svg svg> -| <ul> -| "a" - -#data -<!DOCTYPE html><svg><desc><svg><ul>a -#errors -35: HTML start tag “ul” in a foreign namespace context. -36: End of file in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg desc> -| <svg svg> -| <ul> -| "a" - -#data -<!DOCTYPE html><p><svg><desc><p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <svg svg> -| <svg desc> -| <p> - -#data -<!DOCTYPE html><p><svg><title><p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <svg svg> -| <svg title> -| <p> - -#data -<div><svg><path><foreignObject><p></foreignObject><p> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <svg svg> -| <svg path> -| <svg foreignObject> -| <p> -| <p> - -#data -<math><mi><div><object><div><span></span></div></object></div></mi><mi> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| <div> -| <object> -| <div> -| <span> -| <math mi> - -#data -<math><mi><svg><foreignObject><div><div></div></div></foreignObject></svg></mi><mi> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| <svg svg> -| <svg foreignObject> -| <div> -| <div> -| <math mi> - -#data -<svg><script></script><path> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg script> -| <svg path> - -#data -<table><svg></svg><tr> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <table> -| <tbody> -| <tr> - -#data -<math><mi><mglyph> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| <math mglyph> - -#data -<math><mi><malignmark> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| <math malignmark> - -#data -<math><mo><mglyph> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mo> -| <math mglyph> - -#data -<math><mo><malignmark> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mo> -| <math malignmark> - -#data -<math><mn><mglyph> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mn> -| <math mglyph> - -#data -<math><mn><malignmark> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mn> -| <math malignmark> - -#data -<math><ms><mglyph> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math ms> -| <math mglyph> - -#data -<math><ms><malignmark> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math ms> -| <math malignmark> - -#data -<math><mtext><mglyph> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mtext> -| <math mglyph> - -#data -<math><mtext><malignmark> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mtext> -| <math malignmark> - -#data -<math><annotation-xml><svg></svg></annotation-xml><mi> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| <svg svg> -| <math mi> - -#data -<math><annotation-xml><svg><foreignObject><div><math><mi></mi></math><span></span></div></foreignObject><path></path></svg></annotation-xml><mi> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| <svg svg> -| <svg foreignObject> -| <div> -| <math math> -| <math mi> -| <span> -| <svg path> -| <math mi> - -#data -<math><annotation-xml><svg><foreignObject><math><mi><svg></svg></mi><mo></mo></math><span></span></foreignObject><path></path></svg></annotation-xml><mi> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| <svg svg> -| <svg foreignObject> -| <math math> -| <math mi> -| <svg svg> -| <math mo> -| <span> -| <svg path> -| <math mi> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests11.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests11.dat deleted file mode 100644 index 638cde479f7..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests11.dat +++ /dev/null @@ -1,482 +0,0 @@ -#data -<!DOCTYPE html><body><svg attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' contentScriptType='' contentStyleType='' diffuseConstant='' edgeMode='' externalResourcesRequired='' filterRes='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' viewTarget='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| attributeName="" -| attributeType="" -| baseFrequency="" -| baseProfile="" -| calcMode="" -| clipPathUnits="" -| contentScriptType="" -| contentStyleType="" -| diffuseConstant="" -| edgeMode="" -| externalResourcesRequired="" -| filterRes="" -| filterUnits="" -| glyphRef="" -| gradientTransform="" -| gradientUnits="" -| kernelMatrix="" -| kernelUnitLength="" -| keyPoints="" -| keySplines="" -| keyTimes="" -| lengthAdjust="" -| limitingConeAngle="" -| markerHeight="" -| markerUnits="" -| markerWidth="" -| maskContentUnits="" -| maskUnits="" -| numOctaves="" -| pathLength="" -| patternContentUnits="" -| patternTransform="" -| patternUnits="" -| pointsAtX="" -| pointsAtY="" -| pointsAtZ="" -| preserveAlpha="" -| preserveAspectRatio="" -| primitiveUnits="" -| refX="" -| refY="" -| repeatCount="" -| repeatDur="" -| requiredExtensions="" -| requiredFeatures="" -| specularConstant="" -| specularExponent="" -| spreadMethod="" -| startOffset="" -| stdDeviation="" -| stitchTiles="" -| surfaceScale="" -| systemLanguage="" -| tableValues="" -| targetX="" -| targetY="" -| textLength="" -| viewBox="" -| viewTarget="" -| xChannelSelector="" -| yChannelSelector="" -| zoomAndPan="" - -#data -<!DOCTYPE html><BODY><SVG ATTRIBUTENAME='' ATTRIBUTETYPE='' BASEFREQUENCY='' BASEPROFILE='' CALCMODE='' CLIPPATHUNITS='' CONTENTSCRIPTTYPE='' CONTENTSTYLETYPE='' DIFFUSECONSTANT='' EDGEMODE='' EXTERNALRESOURCESREQUIRED='' FILTERRES='' FILTERUNITS='' GLYPHREF='' GRADIENTTRANSFORM='' GRADIENTUNITS='' KERNELMATRIX='' KERNELUNITLENGTH='' KEYPOINTS='' KEYSPLINES='' KEYTIMES='' LENGTHADJUST='' LIMITINGCONEANGLE='' MARKERHEIGHT='' MARKERUNITS='' MARKERWIDTH='' MASKCONTENTUNITS='' MASKUNITS='' NUMOCTAVES='' PATHLENGTH='' PATTERNCONTENTUNITS='' PATTERNTRANSFORM='' PATTERNUNITS='' POINTSATX='' POINTSATY='' POINTSATZ='' PRESERVEALPHA='' PRESERVEASPECTRATIO='' PRIMITIVEUNITS='' REFX='' REFY='' REPEATCOUNT='' REPEATDUR='' REQUIREDEXTENSIONS='' REQUIREDFEATURES='' SPECULARCONSTANT='' SPECULAREXPONENT='' SPREADMETHOD='' STARTOFFSET='' STDDEVIATION='' STITCHTILES='' SURFACESCALE='' SYSTEMLANGUAGE='' TABLEVALUES='' TARGETX='' TARGETY='' TEXTLENGTH='' VIEWBOX='' VIEWTARGET='' XCHANNELSELECTOR='' YCHANNELSELECTOR='' ZOOMANDPAN=''></SVG> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| attributeName="" -| attributeType="" -| baseFrequency="" -| baseProfile="" -| calcMode="" -| clipPathUnits="" -| contentScriptType="" -| contentStyleType="" -| diffuseConstant="" -| edgeMode="" -| externalResourcesRequired="" -| filterRes="" -| filterUnits="" -| glyphRef="" -| gradientTransform="" -| gradientUnits="" -| kernelMatrix="" -| kernelUnitLength="" -| keyPoints="" -| keySplines="" -| keyTimes="" -| lengthAdjust="" -| limitingConeAngle="" -| markerHeight="" -| markerUnits="" -| markerWidth="" -| maskContentUnits="" -| maskUnits="" -| numOctaves="" -| pathLength="" -| patternContentUnits="" -| patternTransform="" -| patternUnits="" -| pointsAtX="" -| pointsAtY="" -| pointsAtZ="" -| preserveAlpha="" -| preserveAspectRatio="" -| primitiveUnits="" -| refX="" -| refY="" -| repeatCount="" -| repeatDur="" -| requiredExtensions="" -| requiredFeatures="" -| specularConstant="" -| specularExponent="" -| spreadMethod="" -| startOffset="" -| stdDeviation="" -| stitchTiles="" -| surfaceScale="" -| systemLanguage="" -| tableValues="" -| targetX="" -| targetY="" -| textLength="" -| viewBox="" -| viewTarget="" -| xChannelSelector="" -| yChannelSelector="" -| zoomAndPan="" - -#data -<!DOCTYPE html><body><svg attributename='' attributetype='' basefrequency='' baseprofile='' calcmode='' clippathunits='' contentscripttype='' contentstyletype='' diffuseconstant='' edgemode='' externalresourcesrequired='' filterres='' filterunits='' glyphref='' gradienttransform='' gradientunits='' kernelmatrix='' kernelunitlength='' keypoints='' keysplines='' keytimes='' lengthadjust='' limitingconeangle='' markerheight='' markerunits='' markerwidth='' maskcontentunits='' maskunits='' numoctaves='' pathlength='' patterncontentunits='' patterntransform='' patternunits='' pointsatx='' pointsaty='' pointsatz='' preservealpha='' preserveaspectratio='' primitiveunits='' refx='' refy='' repeatcount='' repeatdur='' requiredextensions='' requiredfeatures='' specularconstant='' specularexponent='' spreadmethod='' startoffset='' stddeviation='' stitchtiles='' surfacescale='' systemlanguage='' tablevalues='' targetx='' targety='' textlength='' viewbox='' viewtarget='' xchannelselector='' ychannelselector='' zoomandpan=''></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| attributeName="" -| attributeType="" -| baseFrequency="" -| baseProfile="" -| calcMode="" -| clipPathUnits="" -| contentScriptType="" -| contentStyleType="" -| diffuseConstant="" -| edgeMode="" -| externalResourcesRequired="" -| filterRes="" -| filterUnits="" -| glyphRef="" -| gradientTransform="" -| gradientUnits="" -| kernelMatrix="" -| kernelUnitLength="" -| keyPoints="" -| keySplines="" -| keyTimes="" -| lengthAdjust="" -| limitingConeAngle="" -| markerHeight="" -| markerUnits="" -| markerWidth="" -| maskContentUnits="" -| maskUnits="" -| numOctaves="" -| pathLength="" -| patternContentUnits="" -| patternTransform="" -| patternUnits="" -| pointsAtX="" -| pointsAtY="" -| pointsAtZ="" -| preserveAlpha="" -| preserveAspectRatio="" -| primitiveUnits="" -| refX="" -| refY="" -| repeatCount="" -| repeatDur="" -| requiredExtensions="" -| requiredFeatures="" -| specularConstant="" -| specularExponent="" -| spreadMethod="" -| startOffset="" -| stdDeviation="" -| stitchTiles="" -| surfaceScale="" -| systemLanguage="" -| tableValues="" -| targetX="" -| targetY="" -| textLength="" -| viewBox="" -| viewTarget="" -| xChannelSelector="" -| yChannelSelector="" -| zoomAndPan="" - -#data -<!DOCTYPE html><body><math attributeName='' attributeType='' baseFrequency='' baseProfile='' calcMode='' clipPathUnits='' contentScriptType='' contentStyleType='' diffuseConstant='' edgeMode='' externalResourcesRequired='' filterRes='' filterUnits='' glyphRef='' gradientTransform='' gradientUnits='' kernelMatrix='' kernelUnitLength='' keyPoints='' keySplines='' keyTimes='' lengthAdjust='' limitingConeAngle='' markerHeight='' markerUnits='' markerWidth='' maskContentUnits='' maskUnits='' numOctaves='' pathLength='' patternContentUnits='' patternTransform='' patternUnits='' pointsAtX='' pointsAtY='' pointsAtZ='' preserveAlpha='' preserveAspectRatio='' primitiveUnits='' refX='' refY='' repeatCount='' repeatDur='' requiredExtensions='' requiredFeatures='' specularConstant='' specularExponent='' spreadMethod='' startOffset='' stdDeviation='' stitchTiles='' surfaceScale='' systemLanguage='' tableValues='' targetX='' targetY='' textLength='' viewBox='' viewTarget='' xChannelSelector='' yChannelSelector='' zoomAndPan=''></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| attributename="" -| attributetype="" -| basefrequency="" -| baseprofile="" -| calcmode="" -| clippathunits="" -| contentscripttype="" -| contentstyletype="" -| diffuseconstant="" -| edgemode="" -| externalresourcesrequired="" -| filterres="" -| filterunits="" -| glyphref="" -| gradienttransform="" -| gradientunits="" -| kernelmatrix="" -| kernelunitlength="" -| keypoints="" -| keysplines="" -| keytimes="" -| lengthadjust="" -| limitingconeangle="" -| markerheight="" -| markerunits="" -| markerwidth="" -| maskcontentunits="" -| maskunits="" -| numoctaves="" -| pathlength="" -| patterncontentunits="" -| patterntransform="" -| patternunits="" -| pointsatx="" -| pointsaty="" -| pointsatz="" -| preservealpha="" -| preserveaspectratio="" -| primitiveunits="" -| refx="" -| refy="" -| repeatcount="" -| repeatdur="" -| requiredextensions="" -| requiredfeatures="" -| specularconstant="" -| specularexponent="" -| spreadmethod="" -| startoffset="" -| stddeviation="" -| stitchtiles="" -| surfacescale="" -| systemlanguage="" -| tablevalues="" -| targetx="" -| targety="" -| textlength="" -| viewbox="" -| viewtarget="" -| xchannelselector="" -| ychannelselector="" -| zoomandpan="" - -#data -<!DOCTYPE html><body><svg><altGlyph /><altGlyphDef /><altGlyphItem /><animateColor /><animateMotion /><animateTransform /><clipPath /><feBlend /><feColorMatrix /><feComponentTransfer /><feComposite /><feConvolveMatrix /><feDiffuseLighting /><feDisplacementMap /><feDistantLight /><feFlood /><feFuncA /><feFuncB /><feFuncG /><feFuncR /><feGaussianBlur /><feImage /><feMerge /><feMergeNode /><feMorphology /><feOffset /><fePointLight /><feSpecularLighting /><feSpotLight /><feTile /><feTurbulence /><foreignObject /><glyphRef /><linearGradient /><radialGradient /><textPath /></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg altGlyph> -| <svg altGlyphDef> -| <svg altGlyphItem> -| <svg animateColor> -| <svg animateMotion> -| <svg animateTransform> -| <svg clipPath> -| <svg feBlend> -| <svg feColorMatrix> -| <svg feComponentTransfer> -| <svg feComposite> -| <svg feConvolveMatrix> -| <svg feDiffuseLighting> -| <svg feDisplacementMap> -| <svg feDistantLight> -| <svg feFlood> -| <svg feFuncA> -| <svg feFuncB> -| <svg feFuncG> -| <svg feFuncR> -| <svg feGaussianBlur> -| <svg feImage> -| <svg feMerge> -| <svg feMergeNode> -| <svg feMorphology> -| <svg feOffset> -| <svg fePointLight> -| <svg feSpecularLighting> -| <svg feSpotLight> -| <svg feTile> -| <svg feTurbulence> -| <svg foreignObject> -| <svg glyphRef> -| <svg linearGradient> -| <svg radialGradient> -| <svg textPath> - -#data -<!DOCTYPE html><body><svg><altglyph /><altglyphdef /><altglyphitem /><animatecolor /><animatemotion /><animatetransform /><clippath /><feblend /><fecolormatrix /><fecomponenttransfer /><fecomposite /><feconvolvematrix /><fediffuselighting /><fedisplacementmap /><fedistantlight /><feflood /><fefunca /><fefuncb /><fefuncg /><fefuncr /><fegaussianblur /><feimage /><femerge /><femergenode /><femorphology /><feoffset /><fepointlight /><fespecularlighting /><fespotlight /><fetile /><feturbulence /><foreignobject /><glyphref /><lineargradient /><radialgradient /><textpath /></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg altGlyph> -| <svg altGlyphDef> -| <svg altGlyphItem> -| <svg animateColor> -| <svg animateMotion> -| <svg animateTransform> -| <svg clipPath> -| <svg feBlend> -| <svg feColorMatrix> -| <svg feComponentTransfer> -| <svg feComposite> -| <svg feConvolveMatrix> -| <svg feDiffuseLighting> -| <svg feDisplacementMap> -| <svg feDistantLight> -| <svg feFlood> -| <svg feFuncA> -| <svg feFuncB> -| <svg feFuncG> -| <svg feFuncR> -| <svg feGaussianBlur> -| <svg feImage> -| <svg feMerge> -| <svg feMergeNode> -| <svg feMorphology> -| <svg feOffset> -| <svg fePointLight> -| <svg feSpecularLighting> -| <svg feSpotLight> -| <svg feTile> -| <svg feTurbulence> -| <svg foreignObject> -| <svg glyphRef> -| <svg linearGradient> -| <svg radialGradient> -| <svg textPath> - -#data -<!DOCTYPE html><BODY><SVG><ALTGLYPH /><ALTGLYPHDEF /><ALTGLYPHITEM /><ANIMATECOLOR /><ANIMATEMOTION /><ANIMATETRANSFORM /><CLIPPATH /><FEBLEND /><FECOLORMATRIX /><FECOMPONENTTRANSFER /><FECOMPOSITE /><FECONVOLVEMATRIX /><FEDIFFUSELIGHTING /><FEDISPLACEMENTMAP /><FEDISTANTLIGHT /><FEFLOOD /><FEFUNCA /><FEFUNCB /><FEFUNCG /><FEFUNCR /><FEGAUSSIANBLUR /><FEIMAGE /><FEMERGE /><FEMERGENODE /><FEMORPHOLOGY /><FEOFFSET /><FEPOINTLIGHT /><FESPECULARLIGHTING /><FESPOTLIGHT /><FETILE /><FETURBULENCE /><FOREIGNOBJECT /><GLYPHREF /><LINEARGRADIENT /><RADIALGRADIENT /><TEXTPATH /></SVG> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg altGlyph> -| <svg altGlyphDef> -| <svg altGlyphItem> -| <svg animateColor> -| <svg animateMotion> -| <svg animateTransform> -| <svg clipPath> -| <svg feBlend> -| <svg feColorMatrix> -| <svg feComponentTransfer> -| <svg feComposite> -| <svg feConvolveMatrix> -| <svg feDiffuseLighting> -| <svg feDisplacementMap> -| <svg feDistantLight> -| <svg feFlood> -| <svg feFuncA> -| <svg feFuncB> -| <svg feFuncG> -| <svg feFuncR> -| <svg feGaussianBlur> -| <svg feImage> -| <svg feMerge> -| <svg feMergeNode> -| <svg feMorphology> -| <svg feOffset> -| <svg fePointLight> -| <svg feSpecularLighting> -| <svg feSpotLight> -| <svg feTile> -| <svg feTurbulence> -| <svg foreignObject> -| <svg glyphRef> -| <svg linearGradient> -| <svg radialGradient> -| <svg textPath> - -#data -<!DOCTYPE html><body><math><altGlyph /><altGlyphDef /><altGlyphItem /><animateColor /><animateMotion /><animateTransform /><clipPath /><feBlend /><feColorMatrix /><feComponentTransfer /><feComposite /><feConvolveMatrix /><feDiffuseLighting /><feDisplacementMap /><feDistantLight /><feFlood /><feFuncA /><feFuncB /><feFuncG /><feFuncR /><feGaussianBlur /><feImage /><feMerge /><feMergeNode /><feMorphology /><feOffset /><fePointLight /><feSpecularLighting /><feSpotLight /><feTile /><feTurbulence /><foreignObject /><glyphRef /><linearGradient /><radialGradient /><textPath /></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math altglyph> -| <math altglyphdef> -| <math altglyphitem> -| <math animatecolor> -| <math animatemotion> -| <math animatetransform> -| <math clippath> -| <math feblend> -| <math fecolormatrix> -| <math fecomponenttransfer> -| <math fecomposite> -| <math feconvolvematrix> -| <math fediffuselighting> -| <math fedisplacementmap> -| <math fedistantlight> -| <math feflood> -| <math fefunca> -| <math fefuncb> -| <math fefuncg> -| <math fefuncr> -| <math fegaussianblur> -| <math feimage> -| <math femerge> -| <math femergenode> -| <math femorphology> -| <math feoffset> -| <math fepointlight> -| <math fespecularlighting> -| <math fespotlight> -| <math fetile> -| <math feturbulence> -| <math foreignobject> -| <math glyphref> -| <math lineargradient> -| <math radialgradient> -| <math textpath> - -#data -<!DOCTYPE html><body><svg><solidColor /></svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg solidcolor> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests12.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests12.dat deleted file mode 100644 index 63107d277b6..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests12.dat +++ /dev/null @@ -1,62 +0,0 @@ -#data -<!DOCTYPE html><body><p>foo<math><mtext><i>baz</i></mtext><annotation-xml><svg><desc><b>eggs</b></desc><g><foreignObject><P>spam<TABLE><tr><td><img></td></table></foreignObject></g><g>quux</g></svg></annotation-xml></math>bar -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| "foo" -| <math math> -| <math mtext> -| <i> -| "baz" -| <math annotation-xml> -| <svg svg> -| <svg desc> -| <b> -| "eggs" -| <svg g> -| <svg foreignObject> -| <p> -| "spam" -| <table> -| <tbody> -| <tr> -| <td> -| <img> -| <svg g> -| "quux" -| "bar" - -#data -<!DOCTYPE html><body>foo<math><mtext><i>baz</i></mtext><annotation-xml><svg><desc><b>eggs</b></desc><g><foreignObject><P>spam<TABLE><tr><td><img></td></table></foreignObject></g><g>quux</g></svg></annotation-xml></math>bar -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "foo" -| <math math> -| <math mtext> -| <i> -| "baz" -| <math annotation-xml> -| <svg svg> -| <svg desc> -| <b> -| "eggs" -| <svg g> -| <svg foreignObject> -| <p> -| "spam" -| <table> -| <tbody> -| <tr> -| <td> -| <img> -| <svg g> -| "quux" -| "bar" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests14.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests14.dat deleted file mode 100644 index b8713f88582..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests14.dat +++ /dev/null @@ -1,74 +0,0 @@ -#data -<!DOCTYPE html><html><body><xyz:abc></xyz:abc> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <xyz:abc> - -#data -<!DOCTYPE html><html><body><xyz:abc></xyz:abc><span></span> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <xyz:abc> -| <span> - -#data -<!DOCTYPE html><html><html abc:def=gh><xyz:abc></xyz:abc> -#errors -15: Unexpected start tag html -#document -| <!DOCTYPE html> -| <html> -| abc:def="gh" -| <head> -| <body> -| <xyz:abc> - -#data -<!DOCTYPE html><html xml:lang=bar><html xml:lang=foo> -#errors -15: Unexpected start tag html -#document -| <!DOCTYPE html> -| <html> -| xml:lang="bar" -| <head> -| <body> - -#data -<!DOCTYPE html><html 123=456> -#errors -#document -| <!DOCTYPE html> -| <html> -| 123="456" -| <head> -| <body> - -#data -<!DOCTYPE html><html 123=456><html 789=012> -#errors -#document -| <!DOCTYPE html> -| <html> -| 123="456" -| 789="012" -| <head> -| <body> - -#data -<!DOCTYPE html><html><body 789=012> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| 789="012" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests15.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests15.dat deleted file mode 100644 index 6ce1c0d1663..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests15.dat +++ /dev/null @@ -1,208 +0,0 @@ -#data -<!DOCTYPE html><p><b><i><u></p> <p>X -#errors -Line: 1 Col: 31 Unexpected end tag (p). Ignored. -Line: 1 Col: 36 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <b> -| <i> -| <u> -| <b> -| <i> -| <u> -| " " -| <p> -| "X" - -#data -<p><b><i><u></p> -<p>X -#errors -Line: 1 Col: 3 Unexpected start tag (p). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected end tag (p). Ignored. -Line: 2 Col: 4 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <p> -| <b> -| <i> -| <u> -| <b> -| <i> -| <u> -| " -" -| <p> -| "X" - -#data -<!doctype html></html> <head> -#errors -Line: 1 Col: 22 Unexpected end tag (html) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " " - -#data -<!doctype html></body><meta> -#errors -Line: 1 Col: 22 Unexpected end tag (body) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <meta> - -#data -<html></html><!-- foo --> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end tag (html) after the (implied) root element. -#document -| <html> -| <head> -| <body> -| <!-- foo --> - -#data -<!doctype html></body><title>X</title> -#errors -Line: 1 Col: 22 Unexpected end tag (body) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <title> -| "X" - -#data -<!doctype html><table> X<meta></table> -#errors -Line: 1 Col: 24 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 30 Unexpected start tag (meta) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " X" -| <meta> -| <table> - -#data -<!doctype html><table> x</table> -#errors -Line: 1 Col: 24 Unexpected non-space characters in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " x" -| <table> - -#data -<!doctype html><table> x </table> -#errors -Line: 1 Col: 25 Unexpected non-space characters in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " x " -| <table> - -#data -<!doctype html><table><tr> x</table> -#errors -Line: 1 Col: 28 Unexpected non-space characters in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " x" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><table>X<style> <tr>x </style> </table> -#errors -Line: 1 Col: 23 Unexpected non-space characters in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" -| <table> -| <style> -| " <tr>x " -| " " - -#data -<!doctype html><div><table><a>foo</a> <tr><td>bar</td> </tr></table></div> -#errors -Line: 1 Col: 30 Unexpected start tag (a) in table context caused voodoo mode. -Line: 1 Col: 37 Unexpected end tag (a) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> -| <a> -| "foo" -| <table> -| " " -| <tbody> -| <tr> -| <td> -| "bar" -| " " - -#data -<frame></frame></frame><frameset><frame><frameset><frame></frameset><noframes></frameset><noframes> -#errors -6: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -13: Stray start tag “frame”. -21: Stray end tag “frame”. -29: Stray end tag “frame”. -39: “frameset” start tag after “body” already open. -105: End of file seen inside an [R]CDATA element. -105: End of file seen and there were open elements. -XXX: These errors are wrong, please fix me! -#document -| <html> -| <head> -| <frameset> -| <frame> -| <frameset> -| <frame> -| <noframes> -| "</frameset><noframes>" - -#data -<!DOCTYPE html><object></html> -#errors -1: Expected closing tag. Unexpected end of file -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <object> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests16.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests16.dat deleted file mode 100644 index c8ef66f0e6e..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests16.dat +++ /dev/null @@ -1,2299 +0,0 @@ -#data -<!doctype html><script> -#errors -Line: 1 Col: 23 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| <body> - -#data -<!doctype html><script>a -#errors -Line: 1 Col: 24 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "a" -| <body> - -#data -<!doctype html><script>< -#errors -Line: 1 Col: 24 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<" -| <body> - -#data -<!doctype html><script></ -#errors -Line: 1 Col: 25 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</" -| <body> - -#data -<!doctype html><script></S -#errors -Line: 1 Col: 26 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</S" -| <body> - -#data -<!doctype html><script></SC -#errors -Line: 1 Col: 27 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</SC" -| <body> - -#data -<!doctype html><script></SCR -#errors -Line: 1 Col: 28 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</SCR" -| <body> - -#data -<!doctype html><script></SCRI -#errors -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</SCRI" -| <body> - -#data -<!doctype html><script></SCRIP -#errors -Line: 1 Col: 30 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</SCRIP" -| <body> - -#data -<!doctype html><script></SCRIPT -#errors -Line: 1 Col: 31 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</SCRIPT" -| <body> - -#data -<!doctype html><script></SCRIPT -#errors -Line: 1 Col: 32 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| <body> - -#data -<!doctype html><script></s -#errors -Line: 1 Col: 26 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</s" -| <body> - -#data -<!doctype html><script></sc -#errors -Line: 1 Col: 27 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</sc" -| <body> - -#data -<!doctype html><script></scr -#errors -Line: 1 Col: 28 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</scr" -| <body> - -#data -<!doctype html><script></scri -#errors -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</scri" -| <body> - -#data -<!doctype html><script></scrip -#errors -Line: 1 Col: 30 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</scrip" -| <body> - -#data -<!doctype html><script></script -#errors -Line: 1 Col: 31 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "</script" -| <body> - -#data -<!doctype html><script></script -#errors -Line: 1 Col: 32 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| <body> - -#data -<!doctype html><script><! -#errors -Line: 1 Col: 25 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!" -| <body> - -#data -<!doctype html><script><!a -#errors -Line: 1 Col: 26 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!a" -| <body> - -#data -<!doctype html><script><!- -#errors -Line: 1 Col: 26 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!-" -| <body> - -#data -<!doctype html><script><!-a -#errors -Line: 1 Col: 27 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!-a" -| <body> - -#data -<!doctype html><script><!-- -#errors -Line: 1 Col: 27 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--" -| <body> - -#data -<!doctype html><script><!--a -#errors -Line: 1 Col: 28 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--a" -| <body> - -#data -<!doctype html><script><!--< -#errors -Line: 1 Col: 28 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<" -| <body> - -#data -<!doctype html><script><!--<a -#errors -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<a" -| <body> - -#data -<!doctype html><script><!--</ -#errors -Line: 1 Col: 27 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--</" -| <body> - -#data -<!doctype html><script><!--</script -#errors -Line: 1 Col: 35 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--</script" -| <body> - -#data -<!doctype html><script><!--</script -#errors -Line: 1 Col: 36 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--" -| <body> - -#data -<!doctype html><script><!--<s -#errors -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<s" -| <body> - -#data -<!doctype html><script><!--<script -#errors -Line: 1 Col: 34 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script" -| <body> - -#data -<!doctype html><script><!--<script -#errors -Line: 1 Col: 35 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script " -| <body> - -#data -<!doctype html><script><!--<script < -#errors -Line: 1 Col: 36 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script <" -| <body> - -#data -<!doctype html><script><!--<script <a -#errors -Line: 1 Col: 37 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script <a" -| <body> - -#data -<!doctype html><script><!--<script </ -#errors -Line: 1 Col: 37 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </" -| <body> - -#data -<!doctype html><script><!--<script </s -#errors -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </s" -| <body> - -#data -<!doctype html><script><!--<script </script -#errors -Line: 1 Col: 43 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script" -| <body> - -#data -<!doctype html><script><!--<script </scripta -#errors -Line: 1 Col: 44 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </scripta" -| <body> - -#data -<!doctype html><script><!--<script </script -#errors -Line: 1 Col: 44 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<!doctype html><script><!--<script </script> -#errors -Line: 1 Col: 44 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script>" -| <body> - -#data -<!doctype html><script><!--<script </script/ -#errors -Line: 1 Col: 44 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script/" -| <body> - -#data -<!doctype html><script><!--<script </script < -#errors -Line: 1 Col: 45 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script <" -| <body> - -#data -<!doctype html><script><!--<script </script <a -#errors -Line: 1 Col: 46 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script <a" -| <body> - -#data -<!doctype html><script><!--<script </script </ -#errors -Line: 1 Col: 46 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script </" -| <body> - -#data -<!doctype html><script><!--<script </script </script -#errors -Line: 1 Col: 52 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script </script" -| <body> - -#data -<!doctype html><script><!--<script </script </script -#errors -Line: 1 Col: 53 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<!doctype html><script><!--<script </script </script/ -#errors -Line: 1 Col: 53 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<!doctype html><script><!--<script </script </script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<!doctype html><script><!--<script - -#errors -Line: 1 Col: 36 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -" -| <body> - -#data -<!doctype html><script><!--<script -a -#errors -Line: 1 Col: 37 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -a" -| <body> - -#data -<!doctype html><script><!--<script -< -#errors -Line: 1 Col: 37 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -<" -| <body> - -#data -<!doctype html><script><!--<script -- -#errors -Line: 1 Col: 37 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --" -| <body> - -#data -<!doctype html><script><!--<script --a -#errors -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --a" -| <body> - -#data -<!doctype html><script><!--<script --< -#errors -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --<" -| <body> - -#data -<!doctype html><script><!--<script --> -#errors -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<!doctype html><script><!--<script -->< -#errors -Line: 1 Col: 39 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --><" -| <body> - -#data -<!doctype html><script><!--<script --></ -#errors -Line: 1 Col: 40 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --></" -| <body> - -#data -<!doctype html><script><!--<script --></script -#errors -Line: 1 Col: 46 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script --></script" -| <body> - -#data -<!doctype html><script><!--<script --></script -#errors -Line: 1 Col: 47 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<!doctype html><script><!--<script --></script/ -#errors -Line: 1 Col: 47 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<!doctype html><script><!--<script --></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<!doctype html><script><!--<script><\/script>--></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script><\/script>-->" -| <body> - -#data -<!doctype html><script><!--<script></scr'+'ipt>--></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></scr'+'ipt>-->" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script>--><!--</script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>--><!--" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script>-- ></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>-- >" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script>- -></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>- ->" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script>- - ></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>- - >" -| <body> - -#data -<!doctype html><script><!--<script></script><script></script>-></script> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>->" -| <body> - -#data -<!doctype html><script><!--<script>--!></script>X -#errors -Line: 1 Col: 49 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script>--!></script>X" -| <body> - -#data -<!doctype html><script><!--<scr'+'ipt></script>--></script> -#errors -Line: 1 Col: 59 Unexpected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<scr'+'ipt>" -| <body> -| "-->" - -#data -<!doctype html><script><!--<script></scr'+'ipt></script>X -#errors -Line: 1 Col: 57 Unexpected end of file. Expected end tag (script). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| "<!--<script></scr'+'ipt></script>X" -| <body> - -#data -<!doctype html><style><!--<style></style>--></style> -#errors -Line: 1 Col: 52 Unexpected end tag (style). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--<style>" -| <body> -| "-->" - -#data -<!doctype html><style><!--</style>X -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--" -| <body> -| "X" - -#data -<!doctype html><style><!--...</style>...--></style> -#errors -Line: 1 Col: 51 Unexpected end tag (style). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--..." -| <body> -| "...-->" - -#data -<!doctype html><style><!--<br><html xmlns:v="urn:schemas-microsoft-com:vml"><!--[if !mso]><style></style>X -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--<br><html xmlns:v="urn:schemas-microsoft-com:vml"><!--[if !mso]><style>" -| <body> -| "X" - -#data -<!doctype html><style><!--...<style><!--...--!></style>--></style> -#errors -Line: 1 Col: 66 Unexpected end tag (style). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--...<style><!--...--!>" -| <body> -| "-->" - -#data -<!doctype html><style><!--...</style><!-- --><style>@import ...</style> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "<!--..." -| <!-- --> -| <style> -| "@import ..." -| <body> - -#data -<!doctype html><style>...<style><!--...</style><!-- --></style> -#errors -Line: 1 Col: 63 Unexpected end tag (style). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "...<style><!--..." -| <!-- --> -| <body> - -#data -<!doctype html><style>...<!--[if IE]><style>...</style>X -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <style> -| "...<!--[if IE]><style>..." -| <body> -| "X" - -#data -<!doctype html><title><!--<title></title>--></title> -#errors -Line: 1 Col: 52 Unexpected end tag (title). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "<!--<title>" -| <body> -| "-->" - -#data -<!doctype html><title>&lt;/title></title> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "</title>" -| <body> - -#data -<!doctype html><title>foo/title><link></head><body>X -#errors -Line: 1 Col: 52 Unexpected end of file. Expected end tag (title). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "foo/title><link></head><body>X" -| <body> - -#data -<!doctype html><noscript><!--<noscript></noscript>--></noscript> -#errors -Line: 1 Col: 64 Unexpected end tag (noscript). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <noscript> -| "<!--<noscript>" -| <body> -| "-->" - -#data -<!doctype html><noscript><!--</noscript>X<noscript>--></noscript> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <noscript> -| "<!--" -| <body> -| "X" -| <noscript> -| "-->" - -#data -<!doctype html><noscript><iframe></noscript>X -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <noscript> -| "<iframe>" -| <body> -| "X" - -#data -<!doctype html><noframes><!--<noframes></noframes>--></noframes> -#errors -Line: 1 Col: 64 Unexpected end tag (noframes). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <noframes> -| "<!--<noframes>" -| <body> -| "-->" - -#data -<!doctype html><noframes><body><script><!--...</script></body></noframes></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <noframes> -| "<body><script><!--...</script></body>" -| <body> - -#data -<!doctype html><textarea><!--<textarea></textarea>--></textarea> -#errors -Line: 1 Col: 64 Unexpected end tag (textarea). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| "<!--<textarea>" -| "-->" - -#data -<!doctype html><textarea>&lt;/textarea></textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| "</textarea>" - -#data -<!doctype html><textarea>&lt;</textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| "<" - -#data -<!doctype html><textarea>a&lt;b</textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| "a<b" - -#data -<!doctype html><iframe><!--<iframe></iframe>--></iframe> -#errors -Line: 1 Col: 56 Unexpected end tag (iframe). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <iframe> -| "<!--<iframe>" -| "-->" - -#data -<!doctype html><iframe>...<!--X->...<!--/X->...</iframe> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <iframe> -| "...<!--X->...<!--/X->..." - -#data -<!doctype html><xmp><!--<xmp></xmp>--></xmp> -#errors -Line: 1 Col: 44 Unexpected end tag (xmp). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <xmp> -| "<!--<xmp>" -| "-->" - -#data -<!doctype html><noembed><!--<noembed></noembed>--></noembed> -#errors -Line: 1 Col: 60 Unexpected end tag (noembed). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <noembed> -| "<!--<noembed>" -| "-->" - -#data -<script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 8 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| <body> - -#data -<script>a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 9 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "a" -| <body> - -#data -<script>< -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 9 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<" -| <body> - -#data -<script></ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 10 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</" -| <body> - -#data -<script></S -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</S" -| <body> - -#data -<script></SC -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</SC" -| <body> - -#data -<script></SCR -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</SCR" -| <body> - -#data -<script></SCRI -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</SCRI" -| <body> - -#data -<script></SCRIP -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 15 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</SCRIP" -| <body> - -#data -<script></SCRIPT -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</SCRIPT" -| <body> - -#data -<script></SCRIPT -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 17 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| <body> - -#data -<script></s -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</s" -| <body> - -#data -<script></sc -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</sc" -| <body> - -#data -<script></scr -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</scr" -| <body> - -#data -<script></scri -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</scri" -| <body> - -#data -<script></scrip -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 15 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</scrip" -| <body> - -#data -<script></script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</script" -| <body> - -#data -<script></script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 17 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| <body> - -#data -<script><! -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 10 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!" -| <body> - -#data -<script><!a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!a" -| <body> - -#data -<script><!- -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!-" -| <body> - -#data -<script><!-a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!-a" -| <body> - -#data -<script><!-- -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--" -| <body> - -#data -<script><!--a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--a" -| <body> - -#data -<script><!--< -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<" -| <body> - -#data -<script><!--<a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<a" -| <body> - -#data -<script><!--</ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--</" -| <body> - -#data -<script><!--</script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--</script" -| <body> - -#data -<script><!--</script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 21 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--" -| <body> - -#data -<script><!--<s -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<s" -| <body> - -#data -<script><!--<script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 19 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script" -| <body> - -#data -<script><!--<script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script " -| <body> - -#data -<script><!--<script < -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 21 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script <" -| <body> - -#data -<script><!--<script <a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script <a" -| <body> - -#data -<script><!--<script </ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </" -| <body> - -#data -<script><!--<script </s -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </s" -| <body> - -#data -<script><!--<script </script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 28 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script" -| <body> - -#data -<script><!--<script </scripta -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </scripta" -| <body> - -#data -<script><!--<script </script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<script><!--<script </script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script>" -| <body> - -#data -<script><!--<script </script/ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 29 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script/" -| <body> - -#data -<script><!--<script </script < -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 30 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script <" -| <body> - -#data -<script><!--<script </script <a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 31 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script <a" -| <body> - -#data -<script><!--<script </script </ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 31 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script </" -| <body> - -#data -<script><!--<script </script </script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script </script" -| <body> - -#data -<script><!--<script </script </script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<script><!--<script </script </script/ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 38 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<script><!--<script </script </script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script </script " -| <body> - -#data -<script><!--<script - -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 21 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script -" -| <body> - -#data -<script><!--<script -a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script -a" -| <body> - -#data -<script><!--<script -- -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script --" -| <body> - -#data -<script><!--<script --a -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script --a" -| <body> - -#data -<script><!--<script --> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<script><!--<script -->< -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 24 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script --><" -| <body> - -#data -<script><!--<script --></ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 25 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script --></" -| <body> - -#data -<script><!--<script --></script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 31 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script --></script" -| <body> - -#data -<script><!--<script --></script -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 32 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<script><!--<script --></script/ -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 32 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<script><!--<script --></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script -->" -| <body> - -#data -<script><!--<script><\/script>--></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script><\/script>-->" -| <body> - -#data -<script><!--<script></scr'+'ipt>--></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></scr'+'ipt>-->" -| <body> - -#data -<script><!--<script></script><script></script></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>" -| <body> - -#data -<script><!--<script></script><script></script>--><!--</script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>--><!--" -| <body> - -#data -<script><!--<script></script><script></script>-- ></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>-- >" -| <body> - -#data -<script><!--<script></script><script></script>- -></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>- ->" -| <body> - -#data -<script><!--<script></script><script></script>- - ></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>- - >" -| <body> - -#data -<script><!--<script></script><script></script>-></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| "<!--<script></script><script></script>->" -| <body> - -#data -<script><!--<script>--!></script>X -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 34 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script>--!></script>X" -| <body> - -#data -<script><!--<scr'+'ipt></script>--></script> -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 44 Unexpected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<scr'+'ipt>" -| <body> -| "-->" - -#data -<script><!--<script></scr'+'ipt></script>X -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 42 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "<!--<script></scr'+'ipt></script>X" -| <body> - -#data -<style><!--<style></style>--></style> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 37 Unexpected end tag (style). -#document -| <html> -| <head> -| <style> -| "<!--<style>" -| <body> -| "-->" - -#data -<style><!--</style>X -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| "<!--" -| <body> -| "X" - -#data -<style><!--...</style>...--></style> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 36 Unexpected end tag (style). -#document -| <html> -| <head> -| <style> -| "<!--..." -| <body> -| "...-->" - -#data -<style><!--<br><html xmlns:v="urn:schemas-microsoft-com:vml"><!--[if !mso]><style></style>X -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| "<!--<br><html xmlns:v="urn:schemas-microsoft-com:vml"><!--[if !mso]><style>" -| <body> -| "X" - -#data -<style><!--...<style><!--...--!></style>--></style> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 51 Unexpected end tag (style). -#document -| <html> -| <head> -| <style> -| "<!--...<style><!--...--!>" -| <body> -| "-->" - -#data -<style><!--...</style><!-- --><style>@import ...</style> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| "<!--..." -| <!-- --> -| <style> -| "@import ..." -| <body> - -#data -<style>...<style><!--...</style><!-- --></style> -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 48 Unexpected end tag (style). -#document -| <html> -| <head> -| <style> -| "...<style><!--..." -| <!-- --> -| <body> - -#data -<style>...<!--[if IE]><style>...</style>X -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| "...<!--[if IE]><style>..." -| <body> -| "X" - -#data -<title><!--<title></title>--></title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -Line: 1 Col: 37 Unexpected end tag (title). -#document -| <html> -| <head> -| <title> -| "<!--<title>" -| <body> -| "-->" - -#data -<title>&lt;/title></title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| "</title>" -| <body> - -#data -<title>foo/title><link></head><body>X -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -Line: 1 Col: 37 Unexpected end of file. Expected end tag (title). -#document -| <html> -| <head> -| <title> -| "foo/title><link></head><body>X" -| <body> - -#data -<noscript><!--<noscript></noscript>--></noscript> -#errors -Line: 1 Col: 10 Unexpected start tag (noscript). Expected DOCTYPE. -Line: 1 Col: 49 Unexpected end tag (noscript). -#document -| <html> -| <head> -| <noscript> -| "<!--<noscript>" -| <body> -| "-->" - -#data -<noscript><!--</noscript>X<noscript>--></noscript> -#errors -Line: 1 Col: 10 Unexpected start tag (noscript). Expected DOCTYPE. -#document -| <html> -| <head> -| <noscript> -| "<!--" -| <body> -| "X" -| <noscript> -| "-->" - -#data -<noscript><iframe></noscript>X -#errors -Line: 1 Col: 10 Unexpected start tag (noscript). Expected DOCTYPE. -#document -| <html> -| <head> -| <noscript> -| "<iframe>" -| <body> -| "X" - -#data -<noframes><!--<noframes></noframes>--></noframes> -#errors -Line: 1 Col: 10 Unexpected start tag (noframes). Expected DOCTYPE. -Line: 1 Col: 49 Unexpected end tag (noframes). -#document -| <html> -| <head> -| <noframes> -| "<!--<noframes>" -| <body> -| "-->" - -#data -<noframes><body><script><!--...</script></body></noframes></html> -#errors -Line: 1 Col: 10 Unexpected start tag (noframes). Expected DOCTYPE. -#document -| <html> -| <head> -| <noframes> -| "<body><script><!--...</script></body>" -| <body> - -#data -<textarea><!--<textarea></textarea>--></textarea> -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -Line: 1 Col: 49 Unexpected end tag (textarea). -#document -| <html> -| <head> -| <body> -| <textarea> -| "<!--<textarea>" -| "-->" - -#data -<textarea>&lt;/textarea></textarea> -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <textarea> -| "</textarea>" - -#data -<iframe><!--<iframe></iframe>--></iframe> -#errors -Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. -Line: 1 Col: 41 Unexpected end tag (iframe). -#document -| <html> -| <head> -| <body> -| <iframe> -| "<!--<iframe>" -| "-->" - -#data -<iframe>...<!--X->...<!--/X->...</iframe> -#errors -Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <iframe> -| "...<!--X->...<!--/X->..." - -#data -<xmp><!--<xmp></xmp>--></xmp> -#errors -Line: 1 Col: 5 Unexpected start tag (xmp). Expected DOCTYPE. -Line: 1 Col: 29 Unexpected end tag (xmp). -#document -| <html> -| <head> -| <body> -| <xmp> -| "<!--<xmp>" -| "-->" - -#data -<noembed><!--<noembed></noembed>--></noembed> -#errors -Line: 1 Col: 9 Unexpected start tag (noembed). Expected DOCTYPE. -Line: 1 Col: 45 Unexpected end tag (noembed). -#document -| <html> -| <head> -| <body> -| <noembed> -| "<!--<noembed>" -| "-->" - -#data -<!doctype html><table> - -#errors -Line 2 Col 0 Unexpected end of file. Expected table content. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| " -" - -#data -<!doctype html><table><td><span><font></span><span> -#errors -Line 1 Col 26 Unexpected table cell start tag (td) in the table body phase. -Line 1 Col 45 Unexpected end tag (span). -Line 1 Col 51 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <span> -| <font> -| <font> -| <span> - -#data -<!doctype html><form><table></form><form></table></form> -#errors -35: Stray end tag “form”. -41: Start tag “form” seen in “table”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <table> -| <form> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests17.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests17.dat deleted file mode 100644 index 7b555f888de..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests17.dat +++ /dev/null @@ -1,153 +0,0 @@ -#data -<!doctype html><table><tbody><select><tr> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><table><tr><select><td> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<!doctype html><table><tr><td><select><td> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <select> -| <td> - -#data -<!doctype html><table><tr><th><select><td> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <th> -| <select> -| <td> - -#data -<!doctype html><table><caption><select><tr> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <select> -| <tbody> -| <tr> - -#data -<!doctype html><select><tr> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><td> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><th> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><tbody> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><thead> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><tfoot> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><select><caption> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><table><tr></table>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| "a" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests18.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests18.dat deleted file mode 100644 index 680e1f068a6..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests18.dat +++ /dev/null @@ -1,269 +0,0 @@ -#data -<!doctype html><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" - -#data -<!doctype html><table><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" -| <table> - -#data -<!doctype html><table><tbody><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" -| <table> -| <tbody> - -#data -<!doctype html><table><tbody><tr><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><table><tbody><tr><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><table><td><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <plaintext> -| "</plaintext>" - -#data -<!doctype html><table><caption><plaintext></plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <plaintext> -| "</plaintext>" - -#data -<!doctype html><table><tr><style></script></style>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "abc" -| <table> -| <tbody> -| <tr> -| <style> -| "</script>" - -#data -<!doctype html><table><tr><script></style></script>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "abc" -| <table> -| <tbody> -| <tr> -| <script> -| "</style>" - -#data -<!doctype html><table><caption><style></script></style>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <style> -| "</script>" -| "abc" - -#data -<!doctype html><table><td><style></script></style>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <style> -| "</script>" -| "abc" - -#data -<!doctype html><select><script></style></script>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <script> -| "</style>" -| "abc" - -#data -<!doctype html><table><select><script></style></script>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <script> -| "</style>" -| "abc" -| <table> - -#data -<!doctype html><table><tr><select><script></style></script>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <script> -| "</style>" -| "abc" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><frameset></frameset><noframes>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <noframes> -| "abc" - -#data -<!doctype html><frameset></frameset><noframes>abc</noframes><!--abc--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <noframes> -| "abc" -| <!-- abc --> - -#data -<!doctype html><frameset></frameset></html><noframes>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <noframes> -| "abc" - -#data -<!doctype html><frameset></frameset></html><noframes>abc</noframes><!--abc--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <noframes> -| "abc" -| <!-- abc --> - -#data -<!doctype html><table><tr></tbody><tfoot> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <tfoot> - -#data -<!doctype html><table><td><svg></svg>abc<td> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| "abc" -| <td> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests19.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests19.dat deleted file mode 100644 index 0d62f5a5b02..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests19.dat +++ /dev/null @@ -1,1237 +0,0 @@ -#data -<!doctype html><math><mn DefinitionUrl="foo"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mn> -| definitionURL="foo" - -#data -<!doctype html><html></p><!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <!-- foo --> -| <head> -| <body> - -#data -<!doctype html><head></head></p><!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <!-- foo --> -| <body> - -#data -<!doctype html><body><p><pre> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <pre> - -#data -<!doctype html><body><p><listing> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <listing> - -#data -<!doctype html><p><plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <plaintext> - -#data -<!doctype html><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <h1> - -#data -<!doctype html><form><isindex> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> - -#data -<!doctype html><isindex action="POST"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| action="POST" -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| <hr> - -#data -<!doctype html><isindex prompt="this is isindex"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <hr> -| <label> -| "this is isindex" -| <input> -| name="isindex" -| <hr> - -#data -<!doctype html><isindex type="hidden"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| type="hidden" -| <hr> - -#data -<!doctype html><isindex name="foo"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| <hr> - -#data -<!doctype html><ruby><p><rp> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <p> -| <rp> - -#data -<!doctype html><ruby><div><span><rp> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <span> -| <rp> - -#data -<!doctype html><ruby><div><p><rp> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <p> -| <rp> - -#data -<!doctype html><ruby><p><rt> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <p> -| <rt> - -#data -<!doctype html><ruby><div><span><rt> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <span> -| <rt> - -#data -<!doctype html><ruby><div><p><rt> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <p> -| <rt> - -#data -<!doctype html><math/><foo> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <foo> - -#data -<!doctype html><svg/><foo> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <foo> - -#data -<!doctype html><div></body><!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> -| <!-- foo --> - -#data -<!doctype html><h1><div><h3><span></h1>foo -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <h1> -| <div> -| <h3> -| <span> -| "foo" - -#data -<!doctype html><p></h3>foo -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| "foo" - -#data -<!doctype html><h3><li>abc</h2>foo -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <h3> -| <li> -| "abc" -| "foo" - -#data -<!doctype html><table>abc<!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "abc" -| <table> -| <!-- foo --> - -#data -<!doctype html><table> <!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| " " -| <!-- foo --> - -#data -<!doctype html><table> b <!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| " b " -| <table> -| <!-- foo --> - -#data -<!doctype html><select><option><option> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> -| <option> - -#data -<!doctype html><select><option></optgroup> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> - -#data -<!doctype html><select><option></optgroup> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> - -#data -<!doctype html><p><math><mi><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math mi> -| <p> -| <h1> - -#data -<!doctype html><p><math><mo><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math mo> -| <p> -| <h1> - -#data -<!doctype html><p><math><mn><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math mn> -| <p> -| <h1> - -#data -<!doctype html><p><math><ms><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math ms> -| <p> -| <h1> - -#data -<!doctype html><p><math><mtext><p><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math mtext> -| <p> -| <h1> - -#data -<!doctype html><frameset></noframes> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!doctype html><html c=d><body></html><html a=b> -#errors -#document -| <!DOCTYPE html> -| <html> -| a="b" -| c="d" -| <head> -| <body> - -#data -<!doctype html><html c=d><frameset></frameset></html><html a=b> -#errors -#document -| <!DOCTYPE html> -| <html> -| a="b" -| c="d" -| <head> -| <frameset> - -#data -<!doctype html><html><frameset></frameset></html><!--foo--> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <!-- foo --> - -#data -<!doctype html><html><frameset></frameset></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| " " - -#data -<!doctype html><html><frameset></frameset></html>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!doctype html><html><frameset></frameset></html><p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!doctype html><html><frameset></frameset></html></p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<html><frameset></frameset></html><!doctype html> -#errors -#document -| <html> -| <head> -| <frameset> - -#data -<!doctype html><body><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<!doctype html><p><frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<!doctype html><p>a<frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| "a" - -#data -<!doctype html><p> <frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<!doctype html><pre><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> - -#data -<!doctype html><listing><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <listing> - -#data -<!doctype html><li><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <li> - -#data -<!doctype html><dd><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <dd> - -#data -<!doctype html><dt><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <dt> - -#data -<!doctype html><button><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <button> - -#data -<!doctype html><applet><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <applet> - -#data -<!doctype html><marquee><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <marquee> - -#data -<!doctype html><object><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <object> - -#data -<!doctype html><table><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> - -#data -<!doctype html><area><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <area> - -#data -<!doctype html><basefont><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <basefont> -| <frameset> - -#data -<!doctype html><bgsound><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <bgsound> -| <frameset> - -#data -<!doctype html><br><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <br> - -#data -<!doctype html><embed><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <embed> - -#data -<!doctype html><img><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <img> - -#data -<!doctype html><input><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <input> - -#data -<!doctype html><keygen><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <keygen> - -#data -<!doctype html><wbr><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <wbr> - -#data -<!doctype html><hr><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <hr> - -#data -<!doctype html><textarea></textarea><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> - -#data -<!doctype html><xmp></xmp><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <xmp> - -#data -<!doctype html><iframe></iframe><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <iframe> - -#data -<!doctype html><select></select><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!doctype html><svg></svg><frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<!doctype html><math></math><frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<!doctype html><svg><foreignObject><div> <frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<!doctype html><svg>a</svg><frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| "a" - -#data -<!doctype html><svg> </svg><frameset><frame> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> -| <frame> - -#data -<html>aaa<frameset></frameset> -#errors -#document -| <html> -| <head> -| <body> -| "aaa" - -#data -<html> a <frameset></frameset> -#errors -#document -| <html> -| <head> -| <body> -| "a " - -#data -<!doctype html><div><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!doctype html><div><body><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> - -#data -<!doctype html><p><math></p>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| "a" - -#data -<!doctype html><p><math><mn><span></p>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <math math> -| <math mn> -| <span> -| <p> -| "a" - -#data -<!doctype html><math></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> - -#data -<!doctype html><meta charset="ascii"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <meta> -| charset="ascii" -| <body> - -#data -<!doctype html><meta http-equiv="content-type" content="text/html;charset=ascii"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <meta> -| content="text/html;charset=ascii" -| http-equiv="content-type" -| <body> - -#data -<!doctype html><head><!--aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa--><meta charset="utf8"> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <!-- aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --> -| <meta> -| charset="utf8" -| <body> - -#data -<!doctype html><html a=b><head></head><html c=d> -#errors -#document -| <!DOCTYPE html> -| <html> -| a="b" -| c="d" -| <head> -| <body> - -#data -<!doctype html><image/> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <img> - -#data -<!doctype html>a<i>b<table>c<b>d</i>e</b>f -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "a" -| <i> -| "bc" -| <b> -| "de" -| "f" -| <table> - -#data -<!doctype html><table><i>a<b>b<div>c<a>d</i>e</b>f -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <i> -| "a" -| <b> -| "b" -| <b> -| <div> -| <b> -| <i> -| "c" -| <a> -| "d" -| <a> -| "e" -| <a> -| "f" -| <table> - -#data -<!doctype html><i>a<b>b<div>c<a>d</i>e</b>f -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <i> -| "a" -| <b> -| "b" -| <b> -| <div> -| <b> -| <i> -| "c" -| <a> -| "d" -| <a> -| "e" -| <a> -| "f" - -#data -<!doctype html><table><i>a<b>b<div>c</i> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <i> -| "a" -| <b> -| "b" -| <b> -| <div> -| <i> -| "c" -| <table> - -#data -<!doctype html><table><i>a<b>b<div>c<a>d</i>e</b>f -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <i> -| "a" -| <b> -| "b" -| <b> -| <div> -| <b> -| <i> -| "c" -| <a> -| "d" -| <a> -| "e" -| <a> -| "f" -| <table> - -#data -<!doctype html><table><i>a<div>b<tr>c<b>d</i>e -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <i> -| "a" -| <div> -| "b" -| <i> -| "c" -| <b> -| "d" -| <b> -| "e" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><table><td><table><i>a<div>b<b>c</i>d -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <i> -| "a" -| <div> -| <i> -| "b" -| <b> -| "c" -| <b> -| "d" -| <table> - -#data -<!doctype html><body><bgsound> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <bgsound> - -#data -<!doctype html><body><basefont> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <basefont> - -#data -<!doctype html><a><b></a><basefont> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <a> -| <b> -| <basefont> - -#data -<!doctype html><a><b></a><bgsound> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <a> -| <b> -| <bgsound> - -#data -<!doctype html><figcaption><article></figcaption>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <figcaption> -| <article> -| "a" - -#data -<!doctype html><summary><article></summary>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <summary> -| <article> -| "a" - -#data -<!doctype html><p><a><plaintext>b -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <a> -| <plaintext> -| <a> -| "b" - -#data -<!DOCTYPE html><div>a<a></div>b<p>c</p>d -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> -| "a" -| <a> -| <a> -| "b" -| <p> -| "c" -| "d" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests2.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests2.dat deleted file mode 100644 index 60d85922162..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests2.dat +++ /dev/null @@ -1,763 +0,0 @@ -#data -<!DOCTYPE html>Test -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "Test" - -#data -<textarea>test</div>test -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -Line: 1 Col: 24 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <textarea> -| "test</div>test" - -#data -<table><td> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 11 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<table><td>test</tbody></table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected table cell start tag (td) in the table body phase. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "test" - -#data -<frame>test -#errors -Line: 1 Col: 7 Unexpected start tag (frame). Expected DOCTYPE. -Line: 1 Col: 7 Unexpected start tag frame. Ignored. -#document -| <html> -| <head> -| <body> -| "test" - -#data -<!DOCTYPE html><frameset>test -#errors -Line: 1 Col: 29 Unepxected characters in the frameset phase. Characters ignored. -Line: 1 Col: 29 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><frameset><!DOCTYPE html> -#errors -Line: 1 Col: 40 Unexpected DOCTYPE. Ignored. -Line: 1 Col: 40 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><font><p><b>test</font> -#errors -Line: 1 Col: 38 End tag (font) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 38 End tag (font) violates step 1, paragraph 3 of the adoption agency algorithm. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <font> -| <p> -| <font> -| <b> -| "test" - -#data -<!DOCTYPE html><dt><div><dd> -#errors -Line: 1 Col: 28 Missing end tag (div, dt). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <dt> -| <div> -| <dd> - -#data -<script></x -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -Line: 1 Col: 11 Unexpected end of file. Expected end tag (script). -#document -| <html> -| <head> -| <script> -| "</x" -| <body> - -#data -<table><plaintext><td> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 18 Unexpected start tag (plaintext) in table context caused voodoo mode. -Line: 1 Col: 22 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <plaintext> -| "<td>" -| <table> - -#data -<plaintext></plaintext> -#errors -Line: 1 Col: 11 Unexpected start tag (plaintext). Expected DOCTYPE. -Line: 1 Col: 23 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <plaintext> -| "</plaintext>" - -#data -<!DOCTYPE html><table><tr>TEST -#errors -Line: 1 Col: 30 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 30 Unexpected end of file. Expected table content. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "TEST" -| <table> -| <tbody> -| <tr> - -#data -<!DOCTYPE html><body t1=1><body t2=2><body t3=3 t4=4> -#errors -Line: 1 Col: 37 Unexpected start tag (body). -Line: 1 Col: 53 Unexpected start tag (body). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| t1="1" -| t2="2" -| t3="3" -| t4="4" - -#data -</b test -#errors -Line: 1 Col: 8 Unexpected end of file in attribute name. -Line: 1 Col: 8 End tag contains unexpected attributes. -Line: 1 Col: 8 Unexpected end tag (b). Expected DOCTYPE. -Line: 1 Col: 8 Unexpected end tag (b) after the (implied) root element. -#document -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html></b test<b &=&amp>X -#errors -Line: 1 Col: 32 Named entity didn't end with ';'. -Line: 1 Col: 33 End tag contains unexpected attributes. -Line: 1 Col: 33 Unexpected end tag (b) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" - -#data -<!doctypehtml><scrIPt type=text/x-foobar;baz>X</SCRipt -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -Line: 1 Col: 54 Unexpected end of file in the tag name. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| type="text/x-foobar;baz" -| "X</SCRipt" -| <body> - -#data -& -#errors -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&" - -#data -&# -#errors -Line: 1 Col: 1 Numeric entity expected. Got end of file instead. -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&#" - -#data -&#X -#errors -Line: 1 Col: 3 Numeric entity expected but none found. -Line: 1 Col: 3 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&#X" - -#data -&#x -#errors -Line: 1 Col: 3 Numeric entity expected but none found. -Line: 1 Col: 3 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&#x" - -#data -&#45 -#errors -Line: 1 Col: 4 Numeric entity didn't end with ';'. -Line: 1 Col: 4 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "-" - -#data -&x-test -#errors -Line: 1 Col: 1 Named entity expected. Got none. -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&x-test" - -#data -<!doctypehtml><p><li> -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <li> - -#data -<!doctypehtml><p><dt> -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <dt> - -#data -<!doctypehtml><p><dd> -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <dd> - -#data -<!doctypehtml><p><form> -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -Line: 1 Col: 23 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <form> - -#data -<!DOCTYPE html><p></P>X -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| "X" - -#data -&AMP -#errors -Line: 1 Col: 4 Named entity didn't end with ';'. -Line: 1 Col: 4 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&" - -#data -&AMp; -#errors -Line: 1 Col: 1 Named entity expected. Got none. -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "&AMp;" - -#data -<!DOCTYPE html><html><head></head><body><thisISasillyTESTelementNameToMakeSureCrazyTagNamesArePARSEDcorrectLY> -#errors -Line: 1 Col: 110 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <thisisasillytestelementnametomakesurecrazytagnamesareparsedcorrectly> - -#data -<!DOCTYPE html>X</body>X -#errors -Line: 1 Col: 24 Unexpected non-space characters in the after body phase. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "XX" - -#data -<!DOCTYPE html><!-- X -#errors -Line: 1 Col: 21 Unexpected end of file in comment. -#document -| <!DOCTYPE html> -| <!-- X --> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><table><caption>test TEST</caption><td>test -#errors -Line: 1 Col: 54 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 58 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| "test TEST" -| <tbody> -| <tr> -| <td> -| "test" - -#data -<!DOCTYPE html><select><option><optgroup> -#errors -Line: 1 Col: 41 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> -| <optgroup> - -#data -<!DOCTYPE html><select><optgroup><option></optgroup><option><select><option> -#errors -Line: 1 Col: 68 Unexpected select start tag in the select phase treated as select end tag. -Line: 1 Col: 76 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <optgroup> -| <option> -| <option> -| <option> - -#data -<!DOCTYPE html><select><optgroup><option><optgroup> -#errors -Line: 1 Col: 51 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <optgroup> -| <option> -| <optgroup> - -#data -<!DOCTYPE html><datalist><option>foo</datalist>bar -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <datalist> -| <option> -| "foo" -| "bar" - -#data -<!DOCTYPE html><font><input><input></font> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <font> -| <input> -| <input> - -#data -<!DOCTYPE html><!-- XXX - XXX --> -#errors -#document -| <!DOCTYPE html> -| <!-- XXX - XXX --> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><!-- XXX - XXX -#errors -Line: 1 Col: 29 Unexpected end of file in comment (-) -#document -| <!DOCTYPE html> -| <!-- XXX - XXX --> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><!-- XXX - XXX - XXX --> -#errors -#document -| <!DOCTYPE html> -| <!-- XXX - XXX - XXX --> -| <html> -| <head> -| <body> - -#data -<isindex test=x name=x> -#errors -Line: 1 Col: 23 Unexpected start tag (isindex). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected start tag isindex. Don't use it! -#document -| <html> -| <head> -| <body> -| <form> -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| test="x" -| <hr> - -#data -test -test -#errors -Line: 2 Col: 4 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "test -test" - -#data -<!DOCTYPE html><body><title>test</body></title> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <title> -| "test</body>" - -#data -<!DOCTYPE html><body><title>X</title><meta name=z><link rel=foo><style> -x { content:"</style" } </style> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <title> -| "X" -| <meta> -| name="z" -| <link> -| rel="foo" -| <style> -| " -x { content:"</style" } " - -#data -<!DOCTYPE html><select><optgroup></optgroup></select> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <optgroup> - -#data - - -#errors -Line: 2 Col: 1 Unexpected End of file. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html> <html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><script> -</script> <title>x</title> </head> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <script> -| " -" -| " " -| <title> -| "x" -| " " -| <body> - -#data -<!DOCTYPE html><html><body><html id=x> -#errors -Line: 1 Col: 38 html needs to be the first start tag. -#document -| <!DOCTYPE html> -| <html> -| id="x" -| <head> -| <body> - -#data -<!DOCTYPE html>X</body><html id="x"> -#errors -Line: 1 Col: 36 Unexpected start tag token (html) in the after body phase. -Line: 1 Col: 36 html needs to be the first start tag. -#document -| <!DOCTYPE html> -| <html> -| id="x" -| <head> -| <body> -| "X" - -#data -<!DOCTYPE html><head><html id=x> -#errors -Line: 1 Col: 32 html needs to be the first start tag. -#document -| <!DOCTYPE html> -| <html> -| id="x" -| <head> -| <body> - -#data -<!DOCTYPE html>X</html>X -#errors -Line: 1 Col: 24 Unexpected non-space characters in the after body phase. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "XX" - -#data -<!DOCTYPE html>X</html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X " - -#data -<!DOCTYPE html>X</html><p>X -#errors -Line: 1 Col: 26 Unexpected start tag (p). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" -| <p> -| "X" - -#data -<!DOCTYPE html>X<p/x/y/z> -#errors -Line: 1 Col: 19 Expected a > after the /. -Line: 1 Col: 21 Solidus (/) incorrectly placed in tag. -Line: 1 Col: 23 Solidus (/) incorrectly placed in tag. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" -| <p> -| x="" -| y="" -| z="" - -#data -<!DOCTYPE html><!--x-- -#errors -Line: 1 Col: 22 Unexpected end of file in comment (--). -#document -| <!DOCTYPE html> -| <!-- x --> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE html><table><tr><td></p></table> -#errors -Line: 1 Col: 34 Unexpected end tag (p). Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <p> - -#data -<!DOCTYPE <!DOCTYPE HTML>><!--<!--x-->--> -#errors -Line: 1 Col: 20 Expected space or '>'. Got '' -Line: 1 Col: 25 Erroneous DOCTYPE. -Line: 1 Col: 35 Unexpected character in comment found. -#document -| <!DOCTYPE <!doctype> -| <html> -| <head> -| <body> -| ">" -| <!-- <!--x --> -| "-->" - -#data -<!doctype html><div><form></form><div></div></div> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> -| <form> -| <div> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests20.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests20.dat deleted file mode 100644 index 6bd825608f1..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests20.dat +++ /dev/null @@ -1,455 +0,0 @@ -#data -<!doctype html><p><button><button> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <button> - -#data -<!doctype html><p><button><address> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <address> - -#data -<!doctype html><p><button><blockquote> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <blockquote> - -#data -<!doctype html><p><button><menu> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <menu> - -#data -<!doctype html><p><button><p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <p> - -#data -<!doctype html><p><button><ul> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <ul> - -#data -<!doctype html><p><button><h1> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <h1> - -#data -<!doctype html><p><button><h6> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <h6> - -#data -<!doctype html><p><button><listing> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <listing> - -#data -<!doctype html><p><button><pre> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <pre> - -#data -<!doctype html><p><button><form> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <form> - -#data -<!doctype html><p><button><li> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <li> - -#data -<!doctype html><p><button><dd> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <dd> - -#data -<!doctype html><p><button><dt> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <dt> - -#data -<!doctype html><p><button><plaintext> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <plaintext> - -#data -<!doctype html><p><button><table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <table> - -#data -<!doctype html><p><button><hr> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <hr> - -#data -<!doctype html><p><button><xmp> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <xmp> - -#data -<!doctype html><p><button></p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <button> -| <p> - -#data -<!doctype html><address><button></address>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <address> -| <button> -| "a" - -#data -<!doctype html><address><button></address>a -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <address> -| <button> -| "a" - -#data -<p><table></p> -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <p> -| <table> - -#data -<!doctype html><svg> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> - -#data -<!doctype html><p><figcaption> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <figcaption> - -#data -<!doctype html><p><summary> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <summary> - -#data -<!doctype html><form><table><form> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <table> - -#data -<!doctype html><table><form><form> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <form> - -#data -<!doctype html><table><form></table><form> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <form> - -#data -<!doctype html><svg><foreignObject><p> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg foreignObject> -| <p> - -#data -<!doctype html><svg><title>abc -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg title> -| "abc" - -#data -<option><span><option> -#errors -#document -| <html> -| <head> -| <body> -| <option> -| <span> -| <option> - -#data -<option><option> -#errors -#document -| <html> -| <head> -| <body> -| <option> -| <option> - -#data -<math><annotation-xml><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| <div> - -#data -<math><annotation-xml encoding="application/svg+xml"><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding="application/svg+xml" -| <div> - -#data -<math><annotation-xml encoding="application/xhtml+xml"><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding="application/xhtml+xml" -| <div> - -#data -<math><annotation-xml encoding="aPPlication/xhtmL+xMl"><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding="aPPlication/xhtmL+xMl" -| <div> - -#data -<math><annotation-xml encoding="text/html"><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding="text/html" -| <div> - -#data -<math><annotation-xml encoding="Text/htmL"><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding="Text/htmL" -| <div> - -#data -<math><annotation-xml encoding=" text/html "><div> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| encoding=" text/html " -| <div> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests21.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests21.dat deleted file mode 100644 index 1260ec03e20..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests21.dat +++ /dev/null @@ -1,221 +0,0 @@ -#data -<svg><![CDATA[foo]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "foo" - -#data -<math><![CDATA[foo]]> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| "foo" - -#data -<div><![CDATA[foo]]> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <!-- [CDATA[foo]] --> - -#data -<svg><![CDATA[foo -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "foo" - -#data -<svg><![CDATA[foo -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "foo" - -#data -<svg><![CDATA[ -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> - -#data -<svg><![CDATA[]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> - -#data -<svg><![CDATA[]] >]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "]] >" - -#data -<svg><![CDATA[]] >]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "]] >" - -#data -<svg><![CDATA[]] -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "]]" - -#data -<svg><![CDATA[] -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "]" - -#data -<svg><![CDATA[]>a -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "]>a" - -#data -<svg><foreignObject><div><![CDATA[foo]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg foreignObject> -| <div> -| <!-- [CDATA[foo]] --> - -#data -<svg><![CDATA[<svg>]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>" - -#data -<svg><![CDATA[</svg>a]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "</svg>a" - -#data -<svg><![CDATA[<svg>a -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>a" - -#data -<svg><![CDATA[</svg>a -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "</svg>a" - -#data -<svg><![CDATA[<svg>]]><path> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>" -| <svg path> - -#data -<svg><![CDATA[<svg>]]></path> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>" - -#data -<svg><![CDATA[<svg>]]><!--path--> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>" -| <!-- path --> - -#data -<svg><![CDATA[<svg>]]>path -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<svg>path" - -#data -<svg><![CDATA[<!--svg-->]]> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| "<!--svg-->" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests22.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests22.dat deleted file mode 100644 index aab27b2e904..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests22.dat +++ /dev/null @@ -1,157 +0,0 @@ -#data -<a><b><big><em><strong><div>X</a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <b> -| <big> -| <em> -| <strong> -| <big> -| <em> -| <strong> -| <div> -| <a> -| "X" - -#data -<a><b><div id=1><div id=2><div id=3><div id=4><div id=5><div id=6><div id=7><div id=8>A</a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <b> -| <b> -| <div> -| id="1" -| <a> -| <div> -| id="2" -| <a> -| <div> -| id="3" -| <a> -| <div> -| id="4" -| <a> -| <div> -| id="5" -| <a> -| <div> -| id="6" -| <a> -| <div> -| id="7" -| <a> -| <div> -| id="8" -| <a> -| "A" - -#data -<a><b><div id=1><div id=2><div id=3><div id=4><div id=5><div id=6><div id=7><div id=8><div id=9>A</a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <b> -| <b> -| <div> -| id="1" -| <a> -| <div> -| id="2" -| <a> -| <div> -| id="3" -| <a> -| <div> -| id="4" -| <a> -| <div> -| id="5" -| <a> -| <div> -| id="6" -| <a> -| <div> -| id="7" -| <a> -| <div> -| id="8" -| <a> -| <div> -| id="9" -| "A" - -#data -<a><b><div id=1><div id=2><div id=3><div id=4><div id=5><div id=6><div id=7><div id=8><div id=9><div id=10>A</a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <b> -| <b> -| <div> -| id="1" -| <a> -| <div> -| id="2" -| <a> -| <div> -| id="3" -| <a> -| <div> -| id="4" -| <a> -| <div> -| id="5" -| <a> -| <div> -| id="6" -| <a> -| <div> -| id="7" -| <a> -| <div> -| id="8" -| <a> -| <div> -| id="9" -| <div> -| id="10" -| "A" - -#data -<cite><b><cite><i><cite><i><cite><i><div>X</b>TEST -#errors -Line: 1 Col: 6 Unexpected start tag (cite). Expected DOCTYPE. -Line: 1 Col: 46 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 50 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <cite> -| <b> -| <cite> -| <i> -| <cite> -| <i> -| <cite> -| <i> -| <i> -| <i> -| <div> -| <b> -| "X" -| "TEST" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests23.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests23.dat deleted file mode 100644 index 34d2a73f1c7..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests23.dat +++ /dev/null @@ -1,155 +0,0 @@ -#data -<p><font size=4><font color=red><font size=4><font size=4><font size=4><font size=4><font size=4><font color=red><p>X -#errors -3: Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -116: Unclosed elements. -117: End of file seen and there were open elements. -#document -| <html> -| <head> -| <body> -| <p> -| <font> -| size="4" -| <font> -| color="red" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| color="red" -| <p> -| <font> -| color="red" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| color="red" -| "X" - -#data -<p><font size=4><font size=4><font size=4><font size=4><p>X -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <p> -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| "X" - -#data -<p><font size=4><font size=4><font size=4><font size="5"><font size=4><p>X -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="5" -| <font> -| size="4" -| <p> -| <font> -| size="4" -| <font> -| size="4" -| <font> -| size="5" -| <font> -| size="4" -| "X" - -#data -<p><font size=4 id=a><font size=4 id=b><font size=4><font size=4><p>X -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <font> -| id="a" -| size="4" -| <font> -| id="b" -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| <p> -| <font> -| id="a" -| size="4" -| <font> -| id="b" -| size="4" -| <font> -| size="4" -| <font> -| size="4" -| "X" - -#data -<p><b id=a><b id=a><b id=a><b><object><b id=a><b id=a>X</object><p>Y -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <b> -| id="a" -| <b> -| id="a" -| <b> -| id="a" -| <b> -| <object> -| <b> -| id="a" -| <b> -| id="a" -| "X" -| <p> -| <b> -| id="a" -| <b> -| id="a" -| <b> -| id="a" -| <b> -| "Y" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests24.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests24.dat deleted file mode 100644 index f6dc7eb48a5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests24.dat +++ /dev/null @@ -1,79 +0,0 @@ -#data -<!DOCTYPE html>&NotEqualTilde; -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "≂̸" - -#data -<!DOCTYPE html>&NotEqualTilde;A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "≂̸A" - -#data -<!DOCTYPE html>&ThickSpace; -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "  " - -#data -<!DOCTYPE html>&ThickSpace;A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "  A" - -#data -<!DOCTYPE html>&NotSubset; -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "⊂⃒" - -#data -<!DOCTYPE html>&NotSubset;A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "⊂⃒A" - -#data -<!DOCTYPE html>&Gopf; -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "𝔾" - -#data -<!DOCTYPE html>&Gopf;A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "𝔾A" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests25.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests25.dat deleted file mode 100644 index 00de7295b71..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests25.dat +++ /dev/null @@ -1,219 +0,0 @@ -#data -<!DOCTYPE html><body><foo>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <foo> -| "A" - -#data -<!DOCTYPE html><body><area>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <area> -| "A" - -#data -<!DOCTYPE html><body><base>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <base> -| "A" - -#data -<!DOCTYPE html><body><basefont>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <basefont> -| "A" - -#data -<!DOCTYPE html><body><bgsound>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <bgsound> -| "A" - -#data -<!DOCTYPE html><body><br>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <br> -| "A" - -#data -<!DOCTYPE html><body><col>A -#errors -26: Stray start tag “col”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "A" - -#data -<!DOCTYPE html><body><command>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <command> -| "A" - -#data -<!DOCTYPE html><body><embed>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <embed> -| "A" - -#data -<!DOCTYPE html><body><frame>A -#errors -26: Stray start tag “frame”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "A" - -#data -<!DOCTYPE html><body><hr>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <hr> -| "A" - -#data -<!DOCTYPE html><body><img>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <img> -| "A" - -#data -<!DOCTYPE html><body><input>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <input> -| "A" - -#data -<!DOCTYPE html><body><keygen>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <keygen> -| "A" - -#data -<!DOCTYPE html><body><link>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <link> -| "A" - -#data -<!DOCTYPE html><body><meta>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <meta> -| "A" - -#data -<!DOCTYPE html><body><param>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <param> -| "A" - -#data -<!DOCTYPE html><body><source>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <source> -| "A" - -#data -<!DOCTYPE html><body><track>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <track> -| "A" - -#data -<!DOCTYPE html><body><wbr>A -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <wbr> -| "A" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests26.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests26.dat deleted file mode 100644 index fae11ffdf96..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests26.dat +++ /dev/null @@ -1,313 +0,0 @@ -#data -<!DOCTYPE html><body><a href='#1'><nobr>1<nobr></a><br><a href='#2'><nobr>2<nobr></a><br><a href='#3'><nobr>3<nobr></a> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <a> -| href="#1" -| <nobr> -| "1" -| <nobr> -| <nobr> -| <br> -| <a> -| href="#2" -| <a> -| href="#2" -| <nobr> -| "2" -| <nobr> -| <nobr> -| <br> -| <a> -| href="#3" -| <a> -| href="#3" -| <nobr> -| "3" -| <nobr> - -#data -<!DOCTYPE html><body><b><nobr>1<nobr></b><i><nobr>2<nobr></i>3 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <nobr> -| <nobr> -| <i> -| <i> -| <nobr> -| "2" -| <nobr> -| <nobr> -| "3" - -#data -<!DOCTYPE html><body><b><nobr>1<table><nobr></b><i><nobr>2<nobr></i>3 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <nobr> -| <i> -| <i> -| <nobr> -| "2" -| <nobr> -| <nobr> -| "3" -| <table> - -#data -<!DOCTYPE html><body><b><nobr>1<table><tr><td><nobr></b><i><nobr>2<nobr></i>3 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <table> -| <tbody> -| <tr> -| <td> -| <nobr> -| <i> -| <i> -| <nobr> -| "2" -| <nobr> -| <nobr> -| "3" - -#data -<!DOCTYPE html><body><b><nobr>1<div><nobr></b><i><nobr>2<nobr></i>3 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <div> -| <b> -| <nobr> -| <nobr> -| <nobr> -| <i> -| <i> -| <nobr> -| "2" -| <nobr> -| <nobr> -| "3" - -#data -<!DOCTYPE html><body><b><nobr>1<nobr></b><div><i><nobr>2<nobr></i>3 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <nobr> -| <div> -| <nobr> -| <i> -| <i> -| <nobr> -| "2" -| <nobr> -| <nobr> -| "3" - -#data -<!DOCTYPE html><body><b><nobr>1<nobr><ins></b><i><nobr> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <nobr> -| <ins> -| <nobr> -| <i> -| <i> -| <nobr> - -#data -<!DOCTYPE html><body><b><nobr>1<ins><nobr></b><i>2 -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| <nobr> -| "1" -| <ins> -| <nobr> -| <nobr> -| <i> -| "2" - -#data -<!DOCTYPE html><body><b>1<nobr></b><i><nobr>2</i> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <b> -| "1" -| <nobr> -| <nobr> -| <i> -| <i> -| <nobr> -| "2" - -#data -<p><code x</code></p> - -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <code> -| code="" -| x<="" -| <code> -| code="" -| x<="" -| " -" - -#data -<!DOCTYPE html><svg><foreignObject><p><i></p>a -#errors -45: End tag “p” seen, but there were open elements. -41: Unclosed element “i”. -46: End of file seen and there were open elements. -35: Unclosed element “foreignObject”. -20: Unclosed element “svg”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <svg svg> -| <svg foreignObject> -| <p> -| <i> -| <i> -| "a" - -#data -<!DOCTYPE html><table><tr><td><svg><foreignObject><p><i></p>a -#errors -56: End tag “p” seen, but there were open elements. -52: Unclosed element “i”. -57: End of file seen and there were open elements. -46: Unclosed element “foreignObject”. -31: Unclosed element “svg”. -22: Unclosed element “table”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg foreignObject> -| <p> -| <i> -| <i> -| "a" - -#data -<!DOCTYPE html><math><mtext><p><i></p>a -#errors -38: End tag “p” seen, but there were open elements. -34: Unclosed element “i”. -39: End of file in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mtext> -| <p> -| <i> -| <i> -| "a" - -#data -<!DOCTYPE html><table><tr><td><math><mtext><p><i></p>a -#errors -53: End tag “p” seen, but there were open elements. -49: Unclosed element “i”. -54: End of file in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <math math> -| <math mtext> -| <p> -| <i> -| <i> -| "a" - -#data -<!DOCTYPE html><body><div><!/div>a -#errors -29: Bogus comment. -34: End of file seen and there were open elements. -26: Unclosed element “div”. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <div> -| <!-- /div --> -| "a" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests3.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests3.dat deleted file mode 100644 index 38dc501be35..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests3.dat +++ /dev/null @@ -1,305 +0,0 @@ -#data -<head></head><style></style> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected start tag (style) that can be in head. Moved. -#document -| <html> -| <head> -| <style> -| <body> - -#data -<head></head><script></script> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 21 Unexpected start tag (script) that can be in head. Moved. -#document -| <html> -| <head> -| <script> -| <body> - -#data -<head></head><!-- --><style></style><!-- --><script></script> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -Line: 1 Col: 28 Unexpected start tag (style) that can be in head. Moved. -#document -| <html> -| <head> -| <style> -| <script> -| <!-- --> -| <!-- --> -| <body> - -#data -<head></head><!-- -->x<style></style><!-- --><script></script> -#errors -Line: 1 Col: 6 Unexpected start tag (head). Expected DOCTYPE. -#document -| <html> -| <head> -| <!-- --> -| <body> -| "x" -| <style> -| <!-- --> -| <script> - -#data -<!DOCTYPE html><html><head></head><body><pre> -</pre></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> - -#data -<!DOCTYPE html><html><head></head><body><pre> -foo</pre></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| "foo" - -#data -<!DOCTYPE html><html><head></head><body><pre> - -foo</pre></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| " -foo" - -#data -<!DOCTYPE html><html><head></head><body><pre> -foo -</pre></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| "foo -" - -#data -<!DOCTYPE html><html><head></head><body><pre>x</pre><span> -</span></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| "x" -| <span> -| " -" - -#data -<!DOCTYPE html><html><head></head><body><pre>x -y</pre></body></html> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| "x -y" - -#data -<!DOCTYPE html><html><head></head><body><pre>x<div> -y</pre></body></html> -#errors -Line: 2 Col: 7 End tag (pre) seen too early. Expected other end tag. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| "x" -| <div> -| " -y" - -#data -<!DOCTYPE html><pre>&#x0a;&#x0a;A</pre> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <pre> -| " -A" - -#data -<!DOCTYPE html><HTML><META><HEAD></HEAD></HTML> -#errors -Line: 1 Col: 33 Unexpected start tag head in existing head. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <meta> -| <body> - -#data -<!DOCTYPE html><HTML><HEAD><head></HEAD></HTML> -#errors -Line: 1 Col: 33 Unexpected start tag head in existing head. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<textarea>foo<span>bar</span><i>baz -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -Line: 1 Col: 35 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <textarea> -| "foo<span>bar</span><i>baz" - -#data -<title>foo<span>bar</em><i>baz -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -Line: 1 Col: 30 Unexpected end of file. Expected end tag (title). -#document -| <html> -| <head> -| <title> -| "foo<span>bar</em><i>baz" -| <body> - -#data -<!DOCTYPE html><textarea> -</textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> - -#data -<!DOCTYPE html><textarea> -foo</textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| "foo" - -#data -<!DOCTYPE html><textarea> - -foo</textarea> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <textarea> -| " -foo" - -#data -<!DOCTYPE html><html><head></head><body><ul><li><div><p><li></ul></body></html> -#errors -Line: 1 Col: 60 Missing end tag (div, li). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <ul> -| <li> -| <div> -| <p> -| <li> - -#data -<!doctype html><nobr><nobr><nobr> -#errors -Line: 1 Col: 27 Unexpected start tag (nobr) implies end tag (nobr). -Line: 1 Col: 33 Unexpected start tag (nobr) implies end tag (nobr). -Line: 1 Col: 33 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <nobr> -| <nobr> -| <nobr> - -#data -<!doctype html><nobr><nobr></nobr><nobr> -#errors -Line: 1 Col: 27 Unexpected start tag (nobr) implies end tag (nobr). -Line: 1 Col: 40 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <nobr> -| <nobr> -| <nobr> - -#data -<!doctype html><html><body><p><table></table></body></html> -#errors -Not known -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <table> - -#data -<p><table></table> -#errors -Not known -#document -| <html> -| <head> -| <body> -| <p> -| <table> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests4.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests4.dat deleted file mode 100644 index 3c506326d1f..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests4.dat +++ /dev/null @@ -1,59 +0,0 @@ -#data -direct div content -#errors -#document-fragment -div -#document -| "direct div content" - -#data -direct textarea content -#errors -#document-fragment -textarea -#document -| "direct textarea content" - -#data -textarea content with <em>pseudo</em> <foo>markup -#errors -#document-fragment -textarea -#document -| "textarea content with <em>pseudo</em> <foo>markup" - -#data -this is &#x0043;DATA inside a <style> element -#errors -#document-fragment -style -#document -| "this is &#x0043;DATA inside a <style> element" - -#data -</plaintext> -#errors -#document-fragment -plaintext -#document -| "</plaintext>" - -#data -setting html's innerHTML -#errors -Line: 1 Col: 24 Unexpected EOF in inner html mode. -#document-fragment -html -#document -| <head> -| <body> -| "setting html's innerHTML" - -#data -<title>setting head's innerHTML</title> -#errors -#document-fragment -head -#document -| <title> -| "setting head's innerHTML" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests5.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests5.dat deleted file mode 100644 index d7b5128a44d..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests5.dat +++ /dev/null @@ -1,191 +0,0 @@ -#data -<style> <!-- </style>x -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end of file. Expected end tag (style). -#document -| <html> -| <head> -| <style> -| " <!-- " -| <body> -| "x" - -#data -<style> <!-- </style> --> </style>x -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| " <!-- " -| " " -| <body> -| "--> x" - -#data -<style> <!--> </style>x -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| " <!--> " -| <body> -| "x" - -#data -<style> <!---> </style>x -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| " <!---> " -| <body> -| "x" - -#data -<iframe> <!---> </iframe>x -#errors -Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <iframe> -| " <!---> " -| "x" - -#data -<iframe> <!--- </iframe>->x</iframe> --> </iframe>x -#errors -Line: 1 Col: 8 Unexpected start tag (iframe). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <iframe> -| " <!--- " -| "->x --> x" - -#data -<script> <!-- </script> --> </script>x -#errors -Line: 1 Col: 8 Unexpected start tag (script). Expected DOCTYPE. -#document -| <html> -| <head> -| <script> -| " <!-- " -| " " -| <body> -| "--> x" - -#data -<title> <!-- </title> --> </title>x -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| " <!-- " -| " " -| <body> -| "--> x" - -#data -<textarea> <!--- </textarea>->x</textarea> --> </textarea>x -#errors -Line: 1 Col: 10 Unexpected start tag (textarea). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <textarea> -| " <!--- " -| "->x --> x" - -#data -<style> <!</-- </style>x -#errors -Line: 1 Col: 7 Unexpected start tag (style). Expected DOCTYPE. -#document -| <html> -| <head> -| <style> -| " <!</-- " -| <body> -| "x" - -#data -<p><xmp></xmp> -#errors -XXX: Unknown -#document -| <html> -| <head> -| <body> -| <p> -| <xmp> - -#data -<xmp> <!-- > --> </xmp> -#errors -Line: 1 Col: 5 Unexpected start tag (xmp). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <xmp> -| " <!-- > --> " - -#data -<title>&amp;</title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| "&" -| <body> - -#data -<title><!--&amp;--></title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -#document -| <html> -| <head> -| <title> -| "<!--&-->" -| <body> - -#data -<title><!--</title> -#errors -Line: 1 Col: 7 Unexpected start tag (title). Expected DOCTYPE. -Line: 1 Col: 19 Unexpected end of file. Expected end tag (title). -#document -| <html> -| <head> -| <title> -| "<!--" -| <body> - -#data -<noscript><!--</noscript>--></noscript> -#errors -Line: 1 Col: 10 Unexpected start tag (noscript). Expected DOCTYPE. -#document -| <html> -| <head> -| <noscript> -| "<!--" -| <body> -| "-->" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests6.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests6.dat deleted file mode 100644 index f28ece4fb00..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests6.dat +++ /dev/null @@ -1,663 +0,0 @@ -#data -<!doctype html></head> <head> -#errors -Line: 1 Col: 29 Unexpected start tag head. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| " " -| <body> - -#data -<!doctype html><form><div></form><div> -#errors -33: End tag "form" seen but there were unclosed elements. -38: End of file seen and there were open elements. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <form> -| <div> -| <div> - -#data -<!doctype html><title>&amp;</title> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "&" -| <body> - -#data -<!doctype html><title><!--&amp;--></title> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "<!--&-->" -| <body> - -#data -<!doctype> -#errors -Line: 1 Col: 9 No space after literal string 'DOCTYPE'. -Line: 1 Col: 10 Unexpected > character. Expected DOCTYPE name. -Line: 1 Col: 10 Erroneous DOCTYPE. -#document -| <!DOCTYPE > -| <html> -| <head> -| <body> - -#data -<!---x -#errors -Line: 1 Col: 6 Unexpected end of file in comment. -Line: 1 Col: 6 Unexpected End of file. Expected DOCTYPE. -#document -| <!-- -x --> -| <html> -| <head> -| <body> - -#data -<body> -<div> -#errors -Line: 1 Col: 6 Unexpected start tag (body). -Line: 2 Col: 5 Expected closing tag. Unexpected end of file. -#document-fragment -div -#document -| " -" -| <div> - -#data -<frameset></frameset> -foo -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 2 Col: 3 Unexpected non-space characters in the after frameset phase. Ignored. -#document -| <html> -| <head> -| <frameset> -| " -" - -#data -<frameset></frameset> -<noframes> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 2 Col: 10 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <frameset> -| " -" -| <noframes> - -#data -<frameset></frameset> -<div> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 2 Col: 5 Unexpected start tag (div) in the after frameset phase. Ignored. -#document -| <html> -| <head> -| <frameset> -| " -" - -#data -<frameset></frameset> -</html> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -#document -| <html> -| <head> -| <frameset> -| " -" - -#data -<frameset></frameset> -</div> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 2 Col: 6 Unexpected end tag (div) in the after frameset phase. Ignored. -#document -| <html> -| <head> -| <frameset> -| " -" - -#data -<form><form> -#errors -Line: 1 Col: 6 Unexpected start tag (form). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected start tag (form). -Line: 1 Col: 12 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <form> - -#data -<button><button> -#errors -Line: 1 Col: 8 Unexpected start tag (button). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected start tag (button) implies end tag (button). -Line: 1 Col: 16 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <button> -| <button> - -#data -<table><tr><td></th> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end tag (th). Ignored. -Line: 1 Col: 20 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<table><caption><td> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end tag (td). Ignored. -Line: 1 Col: 20 Unexpected table cell start tag (td) in the table body phase. -Line: 1 Col: 20 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> -| <tbody> -| <tr> -| <td> - -#data -<table><caption><div> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 21 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> -| <div> - -#data -</caption><div> -#errors -Line: 1 Col: 10 Unexpected end tag (caption). Ignored. -Line: 1 Col: 15 Expected closing tag. Unexpected end of file. -#document-fragment -caption -#document -| <div> - -#data -<table><caption><div></caption> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 31 Unexpected end tag (caption). Missing end tag (div). -Line: 1 Col: 31 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> -| <div> - -#data -<table><caption></table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 24 Unexpected end table tag in caption. Generates implied end caption. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> - -#data -</table><div> -#errors -Line: 1 Col: 8 Unexpected end table tag in caption. Generates implied end caption. -Line: 1 Col: 8 Unexpected end tag (caption). Ignored. -Line: 1 Col: 13 Expected closing tag. Unexpected end of file. -#document-fragment -caption -#document -| <div> - -#data -<table><caption></body></col></colgroup></html></tbody></td></tfoot></th></thead></tr> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 23 Unexpected end tag (body). Ignored. -Line: 1 Col: 29 Unexpected end tag (col). Ignored. -Line: 1 Col: 40 Unexpected end tag (colgroup). Ignored. -Line: 1 Col: 47 Unexpected end tag (html). Ignored. -Line: 1 Col: 55 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 60 Unexpected end tag (td). Ignored. -Line: 1 Col: 68 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 73 Unexpected end tag (th). Ignored. -Line: 1 Col: 81 Unexpected end tag (thead). Ignored. -Line: 1 Col: 86 Unexpected end tag (tr). Ignored. -Line: 1 Col: 86 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> - -#data -<table><caption><div></div> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 27 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <caption> -| <div> - -#data -<table><tr><td></body></caption></col></colgroup></html> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end tag (body). Ignored. -Line: 1 Col: 32 Unexpected end tag (caption). Ignored. -Line: 1 Col: 38 Unexpected end tag (col). Ignored. -Line: 1 Col: 49 Unexpected end tag (colgroup). Ignored. -Line: 1 Col: 56 Unexpected end tag (html). Ignored. -Line: 1 Col: 56 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> - -#data -</table></tbody></tfoot></thead></tr><div> -#errors -Line: 1 Col: 8 Unexpected end tag (table). Ignored. -Line: 1 Col: 16 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 24 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 32 Unexpected end tag (thead). Ignored. -Line: 1 Col: 37 Unexpected end tag (tr). Ignored. -Line: 1 Col: 42 Expected closing tag. Unexpected end of file. -#document-fragment -td -#document -| <div> - -#data -<table><colgroup>foo -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 20 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| "foo" -| <table> -| <colgroup> - -#data -foo<col> -#errors -Line: 1 Col: 3 Unexpected end tag (colgroup). Ignored. -#document-fragment -colgroup -#document -| <col> - -#data -<table><colgroup></col> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 23 This element (col) has no end tag. -Line: 1 Col: 23 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <table> -| <colgroup> - -#data -<frameset><div> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 1 Col: 15 Unexpected start tag token (div) in the frameset phase. Ignored. -Line: 1 Col: 15 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <frameset> - -#data -</frameset><frame> -#errors -Line: 1 Col: 11 Unexpected end tag token (frameset) in the frameset phase (innerHTML). -#document-fragment -frameset -#document -| <frame> - -#data -<frameset></div> -#errors -Line: 1 Col: 10 Unexpected start tag (frameset). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected end tag token (div) in the frameset phase. Ignored. -Line: 1 Col: 16 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <frameset> - -#data -</body><div> -#errors -Line: 1 Col: 7 Unexpected end tag (body). Ignored. -Line: 1 Col: 12 Expected closing tag. Unexpected end of file. -#document-fragment -body -#document -| <div> - -#data -<table><tr><div> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected start tag (div) in table context caused voodoo mode. -Line: 1 Col: 16 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <div> -| <table> -| <tbody> -| <tr> - -#data -</tr><td> -#errors -Line: 1 Col: 5 Unexpected end tag (tr). Ignored. -#document-fragment -tr -#document -| <td> - -#data -</tbody></tfoot></thead><td> -#errors -Line: 1 Col: 8 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 16 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 24 Unexpected end tag (thead). Ignored. -#document-fragment -tr -#document -| <td> - -#data -<table><tr><div><td> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 16 Unexpected start tag (div) in table context caused voodoo mode. -Line: 1 Col: 20 Unexpected implied end tag (div) in the table row phase. -Line: 1 Col: 20 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| <table> -| <tbody> -| <tr> -| <td> - -#data -<caption><col><colgroup><tbody><tfoot><thead><tr> -#errors -Line: 1 Col: 9 Unexpected start tag (caption). -Line: 1 Col: 14 Unexpected start tag (col). -Line: 1 Col: 24 Unexpected start tag (colgroup). -Line: 1 Col: 31 Unexpected start tag (tbody). -Line: 1 Col: 38 Unexpected start tag (tfoot). -Line: 1 Col: 45 Unexpected start tag (thead). -Line: 1 Col: 49 Unexpected end of file. Expected table content. -#document-fragment -tbody -#document -| <tr> - -#data -<table><tbody></thead> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 22 Unexpected end tag (thead) in the table body phase. Ignored. -Line: 1 Col: 22 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> - -#data -</table><tr> -#errors -Line: 1 Col: 8 Unexpected end tag (table). Ignored. -Line: 1 Col: 12 Unexpected end of file. Expected table content. -#document-fragment -tbody -#document -| <tr> - -#data -<table><tbody></body></caption></col></colgroup></html></td></th></tr> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 21 Unexpected end tag (body) in the table body phase. Ignored. -Line: 1 Col: 31 Unexpected end tag (caption) in the table body phase. Ignored. -Line: 1 Col: 37 Unexpected end tag (col) in the table body phase. Ignored. -Line: 1 Col: 48 Unexpected end tag (colgroup) in the table body phase. Ignored. -Line: 1 Col: 55 Unexpected end tag (html) in the table body phase. Ignored. -Line: 1 Col: 60 Unexpected end tag (td) in the table body phase. Ignored. -Line: 1 Col: 65 Unexpected end tag (th) in the table body phase. Ignored. -Line: 1 Col: 70 Unexpected end tag (tr) in the table body phase. Ignored. -Line: 1 Col: 70 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> - -#data -<table><tbody></div> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 20 Unexpected end tag (div) in table context caused voodoo mode. -Line: 1 Col: 20 End tag (div) seen too early. Expected other end tag. -Line: 1 Col: 20 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> - -#data -<table><table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected start tag (table) implies end tag (table). -Line: 1 Col: 14 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> -| <table> - -#data -<table></body></caption></col></colgroup></html></tbody></td></tfoot></th></thead></tr> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 14 Unexpected end tag (body). Ignored. -Line: 1 Col: 24 Unexpected end tag (caption). Ignored. -Line: 1 Col: 30 Unexpected end tag (col). Ignored. -Line: 1 Col: 41 Unexpected end tag (colgroup). Ignored. -Line: 1 Col: 48 Unexpected end tag (html). Ignored. -Line: 1 Col: 56 Unexpected end tag (tbody). Ignored. -Line: 1 Col: 61 Unexpected end tag (td). Ignored. -Line: 1 Col: 69 Unexpected end tag (tfoot). Ignored. -Line: 1 Col: 74 Unexpected end tag (th). Ignored. -Line: 1 Col: 82 Unexpected end tag (thead). Ignored. -Line: 1 Col: 87 Unexpected end tag (tr). Ignored. -Line: 1 Col: 87 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <table> - -#data -</table><tr> -#errors -Line: 1 Col: 8 Unexpected end tag (table). Ignored. -Line: 1 Col: 12 Unexpected end of file. Expected table content. -#document-fragment -table -#document -| <tbody> -| <tr> - -#data -<body></body></html> -#errors -Line: 1 Col: 20 Unexpected html end tag in inner html mode. -Line: 1 Col: 20 Unexpected EOF in inner html mode. -#document-fragment -html -#document -| <head> -| <body> - -#data -<html><frameset></frameset></html> -#errors -Line: 1 Col: 6 Unexpected start tag (html). Expected DOCTYPE. -#document -| <html> -| <head> -| <frameset> -| " " - -#data -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"><html></html> -#errors -Line: 1 Col: 50 Erroneous DOCTYPE. -Line: 1 Col: 63 Unexpected end tag (html) after the (implied) root element. -#document -| <!DOCTYPE html "-//W3C//DTD HTML 4.01//EN" ""> -| <html> -| <head> -| <body> - -#data -<param><frameset></frameset> -#errors -Line: 1 Col: 7 Unexpected start tag (param). Expected DOCTYPE. -Line: 1 Col: 17 Unexpected start tag (frameset). -#document -| <html> -| <head> -| <frameset> - -#data -<source><frameset></frameset> -#errors -Line: 1 Col: 7 Unexpected start tag (source). Expected DOCTYPE. -Line: 1 Col: 17 Unexpected start tag (frameset). -#document -| <html> -| <head> -| <frameset> - -#data -<track><frameset></frameset> -#errors -Line: 1 Col: 7 Unexpected start tag (track). Expected DOCTYPE. -Line: 1 Col: 17 Unexpected start tag (frameset). -#document -| <html> -| <head> -| <frameset> - -#data -</html><frameset></frameset> -#errors -7: End tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -17: Stray “frameset” start tag. -17: “frameset” start tag seen. -#document -| <html> -| <head> -| <frameset> - -#data -</body><frameset></frameset> -#errors -7: End tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”. -17: Stray “frameset” start tag. -17: “frameset” start tag seen. -#document -| <html> -| <head> -| <frameset> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests7.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests7.dat deleted file mode 100644 index f5193c660bc..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests7.dat +++ /dev/null @@ -1,390 +0,0 @@ -#data -<!doctype html><body><title>X</title> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <title> -| "X" - -#data -<!doctype html><table><title>X</title></table> -#errors -Line: 1 Col: 29 Unexpected start tag (title) in table context caused voodoo mode. -Line: 1 Col: 38 Unexpected end tag (title) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <title> -| "X" -| <table> - -#data -<!doctype html><head></head><title>X</title> -#errors -Line: 1 Col: 35 Unexpected start tag (title) that can be in head. Moved. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "X" -| <body> - -#data -<!doctype html></head><title>X</title> -#errors -Line: 1 Col: 29 Unexpected start tag (title) that can be in head. Moved. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <title> -| "X" -| <body> - -#data -<!doctype html><table><meta></table> -#errors -Line: 1 Col: 28 Unexpected start tag (meta) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <meta> -| <table> - -#data -<!doctype html><table>X<tr><td><table> <meta></table></table> -#errors -Line: 1 Col: 23 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 45 Unexpected start tag (meta) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" -| <table> -| <tbody> -| <tr> -| <td> -| <meta> -| <table> -| " " - -#data -<!doctype html><html> <head> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<!doctype html> <head> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<!doctype html><table><style> <tr>x </style> </table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <style> -| " <tr>x " -| " " - -#data -<!doctype html><table><TBODY><script> <tr>x </script> </table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <script> -| " <tr>x " -| " " - -#data -<!doctype html><p><applet><p>X</p></applet> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <p> -| <applet> -| <p> -| "X" - -#data -<!doctype html><listing> -X</listing> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <listing> -| "X" - -#data -<!doctype html><select><input>X -#errors -Line: 1 Col: 30 Unexpected input start tag in the select phase. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <input> -| "X" - -#data -<!doctype html><select><select>X -#errors -Line: 1 Col: 31 Unexpected select start tag in the select phase treated as select end tag. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| "X" - -#data -<!doctype html><table><input type=hidDEN></table> -#errors -Line: 1 Col: 41 Unexpected input with type hidden in table context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <input> -| type="hidDEN" - -#data -<!doctype html><table>X<input type=hidDEN></table> -#errors -Line: 1 Col: 23 Unexpected non-space characters in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| "X" -| <table> -| <input> -| type="hidDEN" - -#data -<!doctype html><table> <input type=hidDEN></table> -#errors -Line: 1 Col: 43 Unexpected input with type hidden in table context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| " " -| <input> -| type="hidDEN" - -#data -<!doctype html><table> <input type='hidDEN'></table> -#errors -Line: 1 Col: 45 Unexpected input with type hidden in table context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| " " -| <input> -| type="hidDEN" - -#data -<!doctype html><table><input type=" hidden"><input type=hidDEN></table> -#errors -Line: 1 Col: 44 Unexpected start tag (input) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <input> -| type=" hidden" -| <table> -| <input> -| type="hidDEN" - -#data -<!doctype html><table><select>X<tr> -#errors -Line: 1 Col: 30 Unexpected start tag (select) in table context caused voodoo mode. -Line: 1 Col: 35 Unexpected table element start tag (trs) in the select in table phase. -Line: 1 Col: 35 Unexpected end of file. Expected table content. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| "X" -| <table> -| <tbody> -| <tr> - -#data -<!doctype html><select>X</select> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| "X" - -#data -<!DOCTYPE hTmL><html></html> -#errors -Line: 1 Col: 28 Unexpected end tag (html) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<!DOCTYPE HTML><html></html> -#errors -Line: 1 Col: 28 Unexpected end tag (html) after the (implied) root element. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> - -#data -<body>X</body></body> -#errors -Line: 1 Col: 21 Unexpected end tag token (body) in the after body phase. -Line: 1 Col: 21 Unexpected EOF in inner html mode. -#document-fragment -html -#document -| <head> -| <body> -| "X" - -#data -<div><p>a</x> b -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 13 Unexpected end tag (x). Ignored. -Line: 1 Col: 15 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| <p> -| "a b" - -#data -<table><tr><td><code></code> </table> -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <code> -| " " - -#data -<table><b><tr><td>aaa</td></tr>bbb</table>ccc -#errors -XXX: Fix me -#document -| <html> -| <head> -| <body> -| <b> -| <b> -| "bbb" -| <table> -| <tbody> -| <tr> -| <td> -| "aaa" -| <b> -| "ccc" - -#data -A<table><tr> B</tr> B</table> -#errors -XXX: Fix me -#document -| <html> -| <head> -| <body> -| "A B B" -| <table> -| <tbody> -| <tr> - -#data -A<table><tr> B</tr> </em>C</table> -#errors -XXX: Fix me -#document -| <html> -| <head> -| <body> -| "A BC" -| <table> -| <tbody> -| <tr> -| " " - -#data -<select><keygen> -#errors -Not known -#document -| <html> -| <head> -| <body> -| <select> -| <keygen> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests8.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests8.dat deleted file mode 100644 index 90e6c919e84..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests8.dat +++ /dev/null @@ -1,148 +0,0 @@ -#data -<div> -<div></div> -</span>x -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 3 Col: 7 Unexpected end tag (span). Ignored. -Line: 3 Col: 8 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| " -" -| <div> -| " -x" - -#data -<div>x<div></div> -</span>x -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 2 Col: 7 Unexpected end tag (span). Ignored. -Line: 2 Col: 8 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| "x" -| <div> -| " -x" - -#data -<div>x<div></div>x</span>x -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 25 Unexpected end tag (span). Ignored. -Line: 1 Col: 26 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| "x" -| <div> -| "xx" - -#data -<div>x<div></div>y</span>z -#errors -Line: 1 Col: 5 Unexpected start tag (div). Expected DOCTYPE. -Line: 1 Col: 25 Unexpected end tag (span). Ignored. -Line: 1 Col: 26 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <div> -| "x" -| <div> -| "yz" - -#data -<table><div>x<div></div>x</span>x -#errors -Line: 1 Col: 7 Unexpected start tag (table). Expected DOCTYPE. -Line: 1 Col: 12 Unexpected start tag (div) in table context caused voodoo mode. -Line: 1 Col: 18 Unexpected start tag (div) in table context caused voodoo mode. -Line: 1 Col: 24 Unexpected end tag (div) in table context caused voodoo mode. -Line: 1 Col: 32 Unexpected end tag (span) in table context caused voodoo mode. -Line: 1 Col: 32 Unexpected end tag (span). Ignored. -Line: 1 Col: 33 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| <div> -| "x" -| <div> -| "xx" -| <table> - -#data -x<table>x -#errors -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -Line: 1 Col: 9 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 9 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| "xx" -| <table> - -#data -x<table><table>x -#errors -Line: 1 Col: 1 Unexpected non-space characters. Expected DOCTYPE. -Line: 1 Col: 15 Unexpected start tag (table) implies end tag (table). -Line: 1 Col: 16 Unexpected non-space characters in table context caused voodoo mode. -Line: 1 Col: 16 Unexpected end of file. Expected table content. -#document -| <html> -| <head> -| <body> -| "x" -| <table> -| "x" -| <table> - -#data -<b>a<div></div><div></b>y -#errors -Line: 1 Col: 3 Unexpected start tag (b). Expected DOCTYPE. -Line: 1 Col: 24 End tag (b) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 25 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <b> -| "a" -| <div> -| <div> -| <b> -| "y" - -#data -<a><div><p></a> -#errors -Line: 1 Col: 3 Unexpected start tag (a). Expected DOCTYPE. -Line: 1 Col: 15 End tag (a) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 15 End tag (a) violates step 1, paragraph 3 of the adoption agency algorithm. -Line: 1 Col: 15 Expected closing tag. Unexpected end of file. -#document -| <html> -| <head> -| <body> -| <a> -| <div> -| <a> -| <p> -| <a> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests9.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests9.dat deleted file mode 100644 index 554e27aecf6..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests9.dat +++ /dev/null @@ -1,457 +0,0 @@ -#data -<!DOCTYPE html><math></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> - -#data -<!DOCTYPE html><body><math></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> - -#data -<!DOCTYPE html><math><mi> -#errors -25: End of file in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> - -#data -<!DOCTYPE html><math><annotation-xml><svg><u> -#errors -45: HTML start tag “u” in a foreign namespace context. -45: End of file seen and there were open elements. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math annotation-xml> -| <svg svg> -| <u> - -#data -<!DOCTYPE html><body><select><math></math></select> -#errors -Line: 1 Col: 35 Unexpected start tag token (math) in the select phase. Ignored. -Line: 1 Col: 42 Unexpected end tag (math) in the select phase. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> - -#data -<!DOCTYPE html><body><select><option><math></math></option></select> -#errors -Line: 1 Col: 43 Unexpected start tag token (math) in the select phase. Ignored. -Line: 1 Col: 50 Unexpected end tag (math) in the select phase. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| <option> - -#data -<!DOCTYPE html><body><table><math></math></table> -#errors -Line: 1 Col: 34 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 41 Unexpected end tag (math) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <table> - -#data -<!DOCTYPE html><body><table><math><mi>foo</mi></math></table> -#errors -Line: 1 Col: 34 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 46 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 53 Unexpected end tag (math) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <table> - -#data -<!DOCTYPE html><body><table><math><mi>foo</mi><mi>bar</mi></math></table> -#errors -Line: 1 Col: 34 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 46 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 58 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 65 Unexpected end tag (math) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <table> - -#data -<!DOCTYPE html><body><table><tbody><math><mi>foo</mi><mi>bar</mi></math></tbody></table> -#errors -Line: 1 Col: 41 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 53 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 65 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 72 Unexpected end tag (math) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <table> -| <tbody> - -#data -<!DOCTYPE html><body><table><tbody><tr><math><mi>foo</mi><mi>bar</mi></math></tr></tbody></table> -#errors -Line: 1 Col: 45 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 57 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 69 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 76 Unexpected end tag (math) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <table> -| <tbody> -| <tr> - -#data -<!DOCTYPE html><body><table><tbody><tr><td><math><mi>foo</mi><mi>bar</mi></math></td></tr></tbody></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" - -#data -<!DOCTYPE html><body><table><tbody><tr><td><math><mi>foo</mi><mi>bar</mi></math><p>baz</td></tr></tbody></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body><table><caption><math><mi>foo</mi><mi>bar</mi></math><p>baz</caption></table> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body><table><caption><math><mi>foo</mi><mi>bar</mi><p>baz</table><p>quux -#errors -Line: 1 Col: 70 HTML start tag "p" in a foreign namespace context. -Line: 1 Col: 81 Unexpected end table tag in caption. Generates implied end caption. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><caption><math><mi>foo</mi><mi>bar</mi>baz</table><p>quux -#errors -Line: 1 Col: 78 Unexpected end table tag in caption. Generates implied end caption. -Line: 1 Col: 78 Unexpected end tag (caption). Missing end tag (math). -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <caption> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| "baz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><colgroup><math><mi>foo</mi><mi>bar</mi><p>baz</table><p>quux -#errors -Line: 1 Col: 44 Unexpected start tag (math) in table context caused voodoo mode. -Line: 1 Col: 56 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 68 Unexpected end tag (mi) in table context caused voodoo mode. -Line: 1 Col: 71 HTML start tag "p" in a foreign namespace context. -Line: 1 Col: 71 Unexpected start tag (p) in table context caused voodoo mode. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" -| <table> -| <colgroup> -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><tr><td><select><math><mi>foo</mi><mi>bar</mi><p>baz</table><p>quux -#errors -Line: 1 Col: 50 Unexpected start tag token (math) in the select phase. Ignored. -Line: 1 Col: 54 Unexpected start tag token (mi) in the select phase. Ignored. -Line: 1 Col: 62 Unexpected end tag (mi) in the select phase. Ignored. -Line: 1 Col: 66 Unexpected start tag token (mi) in the select phase. Ignored. -Line: 1 Col: 74 Unexpected end tag (mi) in the select phase. Ignored. -Line: 1 Col: 77 Unexpected start tag token (p) in the select phase. Ignored. -Line: 1 Col: 88 Unexpected table element end tag (tables) in the select in table phase. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <select> -| "foobarbaz" -| <p> -| "quux" - -#data -<!DOCTYPE html><body><table><select><math><mi>foo</mi><mi>bar</mi><p>baz</table><p>quux -#errors -Line: 1 Col: 36 Unexpected start tag (select) in table context caused voodoo mode. -Line: 1 Col: 42 Unexpected start tag token (math) in the select phase. Ignored. -Line: 1 Col: 46 Unexpected start tag token (mi) in the select phase. Ignored. -Line: 1 Col: 54 Unexpected end tag (mi) in the select phase. Ignored. -Line: 1 Col: 58 Unexpected start tag token (mi) in the select phase. Ignored. -Line: 1 Col: 66 Unexpected end tag (mi) in the select phase. Ignored. -Line: 1 Col: 69 Unexpected start tag token (p) in the select phase. Ignored. -Line: 1 Col: 80 Unexpected table element end tag (tables) in the select in table phase. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <select> -| "foobarbaz" -| <table> -| <p> -| "quux" - -#data -<!DOCTYPE html><body></body></html><math><mi>foo</mi><mi>bar</mi><p>baz -#errors -Line: 1 Col: 41 Unexpected start tag (math). -Line: 1 Col: 68 HTML start tag "p" in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><body></body><math><mi>foo</mi><mi>bar</mi><p>baz -#errors -Line: 1 Col: 34 Unexpected start tag token (math) in the after body phase. -Line: 1 Col: 61 HTML start tag "p" in a foreign namespace context. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <math math> -| <math mi> -| "foo" -| <math mi> -| "bar" -| <p> -| "baz" - -#data -<!DOCTYPE html><frameset><math><mi></mi><mi></mi><p><span> -#errors -Line: 1 Col: 31 Unexpected start tag token (math) in the frameset phase. Ignored. -Line: 1 Col: 35 Unexpected start tag token (mi) in the frameset phase. Ignored. -Line: 1 Col: 40 Unexpected end tag token (mi) in the frameset phase. Ignored. -Line: 1 Col: 44 Unexpected start tag token (mi) in the frameset phase. Ignored. -Line: 1 Col: 49 Unexpected end tag token (mi) in the frameset phase. Ignored. -Line: 1 Col: 52 Unexpected start tag token (p) in the frameset phase. Ignored. -Line: 1 Col: 58 Unexpected start tag token (span) in the frameset phase. Ignored. -Line: 1 Col: 58 Expected closing tag. Unexpected end of file. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><frameset></frameset><math><mi></mi><mi></mi><p><span> -#errors -Line: 1 Col: 42 Unexpected start tag (math) in the after frameset phase. Ignored. -Line: 1 Col: 46 Unexpected start tag (mi) in the after frameset phase. Ignored. -Line: 1 Col: 51 Unexpected end tag (mi) in the after frameset phase. Ignored. -Line: 1 Col: 55 Unexpected start tag (mi) in the after frameset phase. Ignored. -Line: 1 Col: 60 Unexpected end tag (mi) in the after frameset phase. Ignored. -Line: 1 Col: 63 Unexpected start tag (p) in the after frameset phase. Ignored. -Line: 1 Col: 69 Unexpected start tag (span) in the after frameset phase. Ignored. -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!DOCTYPE html><body xlink:href=foo><math xlink:href=foo></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| <math math> -| xlink href="foo" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><math><mi xml:lang=en xlink:href=foo></mi></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <math math> -| <math mi> -| xlink href="foo" -| xml lang="en" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><math><mi xml:lang=en xlink:href=foo /></math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <math math> -| <math mi> -| xlink href="foo" -| xml lang="en" - -#data -<!DOCTYPE html><body xlink:href=foo xml:lang=en><math><mi xml:lang=en xlink:href=foo />bar</math> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| xlink:href="foo" -| xml:lang="en" -| <math math> -| <math mi> -| xlink href="foo" -| xml lang="en" -| "bar" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests_innerHTML_1.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests_innerHTML_1.dat deleted file mode 100644 index 6c78661e0cb..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tests_innerHTML_1.dat +++ /dev/null @@ -1,741 +0,0 @@ -#data -<body><span> -#errors -#document-fragment -body -#document -| <span> - -#data -<span><body> -#errors -#document-fragment -body -#document -| <span> - -#data -<span><body> -#errors -#document-fragment -div -#document -| <span> - -#data -<body><span> -#errors -#document-fragment -html -#document -| <head> -| <body> -| <span> - -#data -<frameset><span> -#errors -#document-fragment -body -#document -| <span> - -#data -<span><frameset> -#errors -#document-fragment -body -#document -| <span> - -#data -<span><frameset> -#errors -#document-fragment -div -#document -| <span> - -#data -<frameset><span> -#errors -#document-fragment -html -#document -| <head> -| <frameset> - -#data -<table><tr> -#errors -#document-fragment -table -#document -| <tbody> -| <tr> - -#data -</table><tr> -#errors -#document-fragment -table -#document -| <tbody> -| <tr> - -#data -<a> -#errors -#document-fragment -table -#document -| <a> - -#data -<a> -#errors -#document-fragment -table -#document -| <a> - -#data -<a><caption>a -#errors -#document-fragment -table -#document -| <a> -| <caption> -| "a" - -#data -<a><colgroup><col> -#errors -#document-fragment -table -#document -| <a> -| <colgroup> -| <col> - -#data -<a><tbody><tr> -#errors -#document-fragment -table -#document -| <a> -| <tbody> -| <tr> - -#data -<a><tfoot><tr> -#errors -#document-fragment -table -#document -| <a> -| <tfoot> -| <tr> - -#data -<a><thead><tr> -#errors -#document-fragment -table -#document -| <a> -| <thead> -| <tr> - -#data -<a><tr> -#errors -#document-fragment -table -#document -| <a> -| <tbody> -| <tr> - -#data -<a><th> -#errors -#document-fragment -table -#document -| <a> -| <tbody> -| <tr> -| <th> - -#data -<a><td> -#errors -#document-fragment -table -#document -| <a> -| <tbody> -| <tr> -| <td> - -#data -<table></table><tbody> -#errors -#document-fragment -caption -#document -| <table> - -#data -</table><span> -#errors -#document-fragment -caption -#document -| <span> - -#data -<span></table> -#errors -#document-fragment -caption -#document -| <span> - -#data -</caption><span> -#errors -#document-fragment -caption -#document -| <span> - -#data -<span></caption><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><caption><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><col><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><colgroup><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><html><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><tbody><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><td><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><tfoot><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><thead><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><th><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span><tr><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -<span></table><span> -#errors -#document-fragment -caption -#document -| <span> -| <span> - -#data -</colgroup><col> -#errors -#document-fragment -colgroup -#document -| <col> - -#data -<a><col> -#errors -#document-fragment -colgroup -#document -| <col> - -#data -<caption><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<col><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<colgroup><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<tbody><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<tfoot><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<thead><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -</table><a> -#errors -#document-fragment -tbody -#document -| <a> - -#data -<a><tr> -#errors -#document-fragment -tbody -#document -| <a> -| <tr> - -#data -<a><td> -#errors -#document-fragment -tbody -#document -| <a> -| <tr> -| <td> - -#data -<a><td> -#errors -#document-fragment -tbody -#document -| <a> -| <tr> -| <td> - -#data -<a><td> -#errors -#document-fragment -tbody -#document -| <a> -| <tr> -| <td> - -#data -<td><table><tbody><a><tr> -#errors -#document-fragment -tbody -#document -| <tr> -| <td> -| <a> -| <table> -| <tbody> -| <tr> - -#data -</tr><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<td><table><a><tr></tr><tr> -#errors -#document-fragment -tr -#document -| <td> -| <a> -| <table> -| <tbody> -| <tr> -| <tr> - -#data -<caption><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<col><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<colgroup><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<tbody><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<tfoot><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<thead><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<tr><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -</table><td> -#errors -#document-fragment -tr -#document -| <td> - -#data -<td><table></table><td> -#errors -#document-fragment -tr -#document -| <td> -| <table> -| <td> - -#data -<td><table></table><td> -#errors -#document-fragment -tr -#document -| <td> -| <table> -| <td> - -#data -<caption><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<col><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<colgroup><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<tbody><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<tfoot><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<th><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<thead><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<tr><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</table><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</tbody><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</td><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</tfoot><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</thead><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</th><a> -#errors -#document-fragment -td -#document -| <a> - -#data -</tr><a> -#errors -#document-fragment -td -#document -| <a> - -#data -<table><td><td> -#errors -#document-fragment -td -#document -| <table> -| <tbody> -| <tr> -| <td> -| <td> - -#data -</select><option> -#errors -#document-fragment -select -#document -| <option> - -#data -<input><option> -#errors -#document-fragment -select -#document -| <option> - -#data -<keygen><option> -#errors -#document-fragment -select -#document -| <option> - -#data -<textarea><option> -#errors -#document-fragment -select -#document -| <option> - -#data -</html><!--abc--> -#errors -#document-fragment -html -#document -| <head> -| <body> -| <!-- abc --> - -#data -</frameset><frame> -#errors -#document-fragment -frameset -#document -| <frame> - -#data -#errors -#document-fragment -html -#document -| <head> -| <body> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tricky01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tricky01.dat deleted file mode 100644 index 08419924486..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/tricky01.dat +++ /dev/null @@ -1,261 +0,0 @@ -#data -<b><p>Bold </b> Not bold</p> -Also not bold. -#errors -#document -| <html> -| <head> -| <body> -| <b> -| <p> -| <b> -| "Bold " -| " Not bold" -| " -Also not bold." - -#data -<html> -<font color=red><i>Italic and Red<p>Italic and Red </font> Just italic.</p> Italic only.</i> Plain -<p>I should not be red. <font color=red>Red. <i>Italic and red.</p> -<p>Italic and red. </i> Red.</font> I should not be red.</p> -<b>Bold <i>Bold and italic</b> Only Italic </i> Plain -#errors -#document -| <html> -| <head> -| <body> -| <font> -| color="red" -| <i> -| "Italic and Red" -| <i> -| <p> -| <font> -| color="red" -| "Italic and Red " -| " Just italic." -| " Italic only." -| " Plain -" -| <p> -| "I should not be red. " -| <font> -| color="red" -| "Red. " -| <i> -| "Italic and red." -| <font> -| color="red" -| <i> -| " -" -| <p> -| <font> -| color="red" -| <i> -| "Italic and red. " -| " Red." -| " I should not be red." -| " -" -| <b> -| "Bold " -| <i> -| "Bold and italic" -| <i> -| " Only Italic " -| " Plain" - -#data -<html><body> -<p><font size="7">First paragraph.</p> -<p>Second paragraph.</p></font> -<b><p><i>Bold and Italic</b> Italic</p> -#errors -#document -| <html> -| <head> -| <body> -| " -" -| <p> -| <font> -| size="7" -| "First paragraph." -| <font> -| size="7" -| " -" -| <p> -| "Second paragraph." -| " -" -| <b> -| <p> -| <b> -| <i> -| "Bold and Italic" -| <i> -| " Italic" - -#data -<html> -<dl> -<dt><b>Boo -<dd>Goo? -</dl> -</html> -#errors -#document -| <html> -| <head> -| <body> -| <dl> -| " -" -| <dt> -| <b> -| "Boo -" -| <dd> -| <b> -| "Goo? -" -| <b> -| " -" - -#data -<html><body> -<label><a><div>Hello<div>World</div></a></label> -</body></html> -#errors -#document -| <html> -| <head> -| <body> -| " -" -| <label> -| <a> -| <div> -| <a> -| "Hello" -| <div> -| "World" -| " -" - -#data -<table><center> <font>a</center> <img> <tr><td> </td> </tr> </table> -#errors -#document -| <html> -| <head> -| <body> -| <center> -| " " -| <font> -| "a" -| <font> -| <img> -| " " -| <table> -| " " -| <tbody> -| <tr> -| <td> -| " " -| " " -| " " - -#data -<table><tr><p><a><p>You should see this text. -#errors -#document -| <html> -| <head> -| <body> -| <p> -| <a> -| <p> -| <a> -| "You should see this text." -| <table> -| <tbody> -| <tr> - -#data -<TABLE> -<TR> -<CENTER><CENTER><TD></TD></TR><TR> -<FONT> -<TABLE><tr></tr></TABLE> -</P> -<a></font><font></a> -This page contains an insanely badly-nested tag sequence. -#errors -#document -| <html> -| <head> -| <body> -| <center> -| <center> -| <font> -| " -" -| <table> -| " -" -| <tbody> -| <tr> -| " -" -| <td> -| <tr> -| " -" -| <table> -| <tbody> -| <tr> -| <font> -| " -" -| <p> -| " -" -| <a> -| <a> -| <font> -| <font> -| " -This page contains an insanely badly-nested tag sequence." - -#data -<html> -<body> -<b><nobr><div>This text is in a div inside a nobr</nobr>More text that should not be in the nobr, i.e., the -nobr should have closed the div inside it implicitly. </b><pre>A pre tag outside everything else.</pre> -</body> -</html> -#errors -#document -| <html> -| <head> -| <body> -| " -" -| <b> -| <nobr> -| <div> -| <b> -| <nobr> -| "This text is in a div inside a nobr" -| "More text that should not be in the nobr, i.e., the -nobr should have closed the div inside it implicitly. " -| <pre> -| "A pre tag outside everything else." -| " - -" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit01.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit01.dat deleted file mode 100644 index 9d425e99d5f..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit01.dat +++ /dev/null @@ -1,610 +0,0 @@ -#data -Test -#errors -Line: 1 Col: 4 Unexpected non-space characters. Expected DOCTYPE. -#document -| <html> -| <head> -| <body> -| "Test" - -#data -<div></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> - -#data -<div>Test</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "Test" - -#data -<di -#errors -#document -| <html> -| <head> -| <body> - -#data -<div>Hello</div> -<script> -console.log("PASS"); -</script> -<div>Bye</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "Hello" -| " -" -| <script> -| " -console.log("PASS"); -" -| " -" -| <div> -| "Bye" - -#data -<div foo="bar">Hello</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| foo="bar" -| "Hello" - -#data -<div>Hello</div> -<script> -console.log("FOO<span>BAR</span>BAZ"); -</script> -<div>Bye</div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| "Hello" -| " -" -| <script> -| " -console.log("FOO<span>BAR</span>BAZ"); -" -| " -" -| <div> -| "Bye" - -#data -<foo bar="baz"></foo><potato quack="duck"></potato> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| bar="baz" -| <potato> -| quack="duck" - -#data -<foo bar="baz"><potato quack="duck"></potato></foo> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| bar="baz" -| <potato> -| quack="duck" - -#data -<foo></foo bar="baz"><potato></potato quack="duck"> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| <potato> - -#data -</ tttt> -#errors -#document -| <!-- tttt --> -| <html> -| <head> -| <body> - -#data -<div FOO ><img><img></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| foo="" -| <img> -| <img> - -#data -<p>Test</p<p>Test2</p> -#errors -#document -| <html> -| <head> -| <body> -| <p> -| "TestTest2" - -#data -<rdar://problem/6869687> -#errors -#document -| <html> -| <head> -| <body> -| <rdar:> -| 6869687="" -| problem="" - -#data -<A>test< /A> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| "test< /A>" - -#data -&lt; -#errors -#document -| <html> -| <head> -| <body> -| "<" - -#data -<body foo='bar'><body foo='baz' yo='mama'> -#errors -#document -| <html> -| <head> -| <body> -| foo="bar" -| yo="mama" - -#data -<body></br foo="bar"></body> -#errors -#document -| <html> -| <head> -| <body> -| <br> - -#data -<bdy><br foo="bar"></body> -#errors -#document -| <html> -| <head> -| <body> -| <bdy> -| <br> -| foo="bar" - -#data -<body></body></br foo="bar"> -#errors -#document -| <html> -| <head> -| <body> -| <br> - -#data -<bdy></body><br foo="bar"> -#errors -#document -| <html> -| <head> -| <body> -| <bdy> -| <br> -| foo="bar" - -#data -<html><body></body></html><!-- Hi there --> -#errors -#document -| <html> -| <head> -| <body> -| <!-- Hi there --> - -#data -<html><body></body></html>x<!-- Hi there --> -#errors -#document -| <html> -| <head> -| <body> -| "x" -| <!-- Hi there --> - -#data -<html><body></body></html>x<!-- Hi there --></html><!-- Again --> -#errors -#document -| <html> -| <head> -| <body> -| "x" -| <!-- Hi there --> -| <!-- Again --> - -#data -<html><body></body></html>x<!-- Hi there --></body></html><!-- Again --> -#errors -#document -| <html> -| <head> -| <body> -| "x" -| <!-- Hi there --> -| <!-- Again --> - -#data -<html><body><ruby><div><rp>xx</rp></div></ruby></body></html> -#errors -#document -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <rp> -| "xx" - -#data -<html><body><ruby><div><rt>xx</rt></div></ruby></body></html> -#errors -#document -| <html> -| <head> -| <body> -| <ruby> -| <div> -| <rt> -| "xx" - -#data -<html><frameset><!--1--><noframes>A</noframes><!--2--></frameset><!--3--><noframes>B</noframes><!--4--></html><!--5--><noframes>C</noframes><!--6--> -#errors -#document -| <html> -| <head> -| <frameset> -| <!-- 1 --> -| <noframes> -| "A" -| <!-- 2 --> -| <!-- 3 --> -| <noframes> -| "B" -| <!-- 4 --> -| <noframes> -| "C" -| <!-- 5 --> -| <!-- 6 --> - -#data -<select><option>A<select><option>B<select><option>C<select><option>D<select><option>E<select><option>F<select><option>G<select> -#errors -#document -| <html> -| <head> -| <body> -| <select> -| <option> -| "A" -| <option> -| "B" -| <select> -| <option> -| "C" -| <option> -| "D" -| <select> -| <option> -| "E" -| <option> -| "F" -| <select> -| <option> -| "G" - -#data -<dd><dd><dt><dt><dd><li><li> -#errors -#document -| <html> -| <head> -| <body> -| <dd> -| <dd> -| <dt> -| <dt> -| <dd> -| <li> -| <li> - -#data -<div><b></div><div><nobr>a<nobr> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <b> -| <div> -| <b> -| <nobr> -| "a" -| <nobr> - -#data -<head></head> -<body></body> -#errors -#document -| <html> -| <head> -| " -" -| <body> - -#data -<head></head> <style></style>ddd -#errors -#document -| <html> -| <head> -| <style> -| " " -| <body> -| "ddd" - -#data -<kbd><table></kbd><col><select><tr> -#errors -#document -| <html> -| <head> -| <body> -| <kbd> -| <select> -| <table> -| <colgroup> -| <col> -| <tbody> -| <tr> - -#data -<kbd><table></kbd><col><select><tr></table><div> -#errors -#document -| <html> -| <head> -| <body> -| <kbd> -| <select> -| <table> -| <colgroup> -| <col> -| <tbody> -| <tr> -| <div> - -#data -<a><li><style></style><title></title></a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <li> -| <a> -| <style> -| <title> - -#data -<font></p><p><meta><title></title></font> -#errors -#document -| <html> -| <head> -| <body> -| <font> -| <p> -| <p> -| <font> -| <meta> -| <title> - -#data -<a><center><title></title><a> -#errors -#document -| <html> -| <head> -| <body> -| <a> -| <center> -| <a> -| <title> -| <a> - -#data -<svg><title><div> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg title> -| <div> - -#data -<svg><title><rect><div> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg title> -| <rect> -| <div> - -#data -<svg><title><svg><div> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg title> -| <svg svg> -| <div> - -#data -<img <="" FAIL> -#errors -#document -| <html> -| <head> -| <body> -| <img> -| <="" -| fail="" - -#data -<ul><li><div id='foo'/>A</li><li>B<div>C</div></li></ul> -#errors -#document -| <html> -| <head> -| <body> -| <ul> -| <li> -| <div> -| id="foo" -| "A" -| <li> -| "B" -| <div> -| "C" - -#data -<svg><em><desc></em> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <em> -| <desc> - -#data -<table><tr><td><svg><desc><td></desc><circle> -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| <svg svg> -| <svg desc> -| <td> -| <circle> - -#data -<svg><tfoot></mi><td> -#errors -#document -| <html> -| <head> -| <body> -| <svg svg> -| <svg tfoot> -| <svg td> - -#data -<math><mrow><mrow><mn>1</mn></mrow><mi>a</mi></mrow></math> -#errors -#document -| <html> -| <head> -| <body> -| <math math> -| <math mrow> -| <math mrow> -| <math mn> -| "1" -| <math mi> -| "a" - -#data -<!doctype html><input type="hidden"><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <frameset> - -#data -<!doctype html><input type="button"><frameset> -#errors -#document -| <!DOCTYPE html> -| <html> -| <head> -| <body> -| <input> -| type="button" diff --git a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit02.dat b/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit02.dat deleted file mode 100644 index 905783d3cdf..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/testdata/webkit/webkit02.dat +++ /dev/null @@ -1,159 +0,0 @@ -#data -<foo bar=qux/> -#errors -#document -| <html> -| <head> -| <body> -| <foo> -| bar="qux/" - -#data -<p id="status"><noscript><strong>A</strong></noscript><span>B</span></p> -#errors -#document -| <html> -| <head> -| <body> -| <p> -| id="status" -| <noscript> -| "<strong>A</strong>" -| <span> -| "B" - -#data -<div><sarcasm><div></div></sarcasm></div> -#errors -#document -| <html> -| <head> -| <body> -| <div> -| <sarcasm> -| <div> - -#data -<html><body><img src="" border="0" alt="><div>A</div></body></html> -#errors -#document -| <html> -| <head> -| <body> - -#data -<table><td></tbody>A -#errors -#document -| <html> -| <head> -| <body> -| "A" -| <table> -| <tbody> -| <tr> -| <td> - -#data -<table><td></thead>A -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "A" - -#data -<table><td></tfoot>A -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <tbody> -| <tr> -| <td> -| "A" - -#data -<table><thead><td></tbody>A -#errors -#document -| <html> -| <head> -| <body> -| <table> -| <thead> -| <tr> -| <td> -| "A" - -#data -<legend>test</legend> -#errors -#document -| <html> -| <head> -| <body> -| <legend> -| "test" - -#data -<table><input> -#errors -#document -| <html> -| <head> -| <body> -| <input> -| <table> - -#data -<b><em><dcell><postfield><postfield><postfield><postfield><missing_glyph><missing_glyph><missing_glyph><missing_glyph><hkern><aside></b></em> -#errors -#document-fragment -div -#document -| <b> -| <em> -| <dcell> -| <postfield> -| <postfield> -| <postfield> -| <postfield> -| <missing_glyph> -| <missing_glyph> -| <missing_glyph> -| <missing_glyph> -| <hkern> -| <aside> -| <em> -| <b> - -#data -<isindex action="x"> -#errors -#document-fragment -table -#document -| <form> -| action="x" -| <hr> -| <label> -| "This is a searchable index. Enter search keywords: " -| <input> -| name="isindex" -| <hr> - -#data -<option><XH<optgroup></optgroup> -#errors -#document-fragment -select -#document -| <option> diff --git a/Godeps/_workspace/src/golang.org/x/net/html/token_test.go b/Godeps/_workspace/src/golang.org/x/net/html/token_test.go deleted file mode 100644 index 20221c32840..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/html/token_test.go +++ /dev/null @@ -1,748 +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 html - -import ( - "bytes" - "io" - "io/ioutil" - "reflect" - "runtime" - "strings" - "testing" -) - -type tokenTest struct { - // A short description of the test case. - desc string - // The HTML to parse. - html string - // The string representations of the expected tokens, joined by '$'. - golden string -} - -var tokenTests = []tokenTest{ - { - "empty", - "", - "", - }, - // A single text node. The tokenizer should not break text nodes on whitespace, - // nor should it normalize whitespace within a text node. - { - "text", - "foo bar", - "foo bar", - }, - // An entity. - { - "entity", - "one &lt; two", - "one &lt; two", - }, - // A start, self-closing and end tag. The tokenizer does not care if the start - // and end tokens don't match; that is the job of the parser. - { - "tags", - "<a>b<c/>d</e>", - "<a>$b$<c/>$d$</e>", - }, - // Angle brackets that aren't a tag. - { - "not a tag #0", - "<", - "&lt;", - }, - { - "not a tag #1", - "</", - "&lt;/", - }, - { - "not a tag #2", - "</>", - "<!---->", - }, - { - "not a tag #3", - "a</>b", - "a$<!---->$b", - }, - { - "not a tag #4", - "</ >", - "<!-- -->", - }, - { - "not a tag #5", - "</.", - "<!--.-->", - }, - { - "not a tag #6", - "</.>", - "<!--.-->", - }, - { - "not a tag #7", - "a < b", - "a &lt; b", - }, - { - "not a tag #8", - "<.>", - "&lt;.&gt;", - }, - { - "not a tag #9", - "a<<<b>>>c", - "a&lt;&lt;$<b>$&gt;&gt;c", - }, - { - "not a tag #10", - "if x<0 and y < 0 then x*y>0", - "if x&lt;0 and y &lt; 0 then x*y&gt;0", - }, - { - "not a tag #11", - "<<p>", - "&lt;$<p>", - }, - // EOF in a tag name. - { - "tag name eof #0", - "<a", - "", - }, - { - "tag name eof #1", - "<a ", - "", - }, - { - "tag name eof #2", - "a<b", - "a", - }, - { - "tag name eof #3", - "<a><b", - "<a>", - }, - { - "tag name eof #4", - `<a x`, - ``, - }, - // Some malformed tags that are missing a '>'. - { - "malformed tag #0", - `<p</p>`, - `<p< p="">`, - }, - { - "malformed tag #1", - `<p </p>`, - `<p <="" p="">`, - }, - { - "malformed tag #2", - `<p id`, - ``, - }, - { - "malformed tag #3", - `<p id=`, - ``, - }, - { - "malformed tag #4", - `<p id=>`, - `<p id="">`, - }, - { - "malformed tag #5", - `<p id=0`, - ``, - }, - { - "malformed tag #6", - `<p id=0</p>`, - `<p id="0&lt;/p">`, - }, - { - "malformed tag #7", - `<p id="0</p>`, - ``, - }, - { - "malformed tag #8", - `<p id="0"</p>`, - `<p id="0" <="" p="">`, - }, - { - "malformed tag #9", - `<p></p id`, - `<p>`, - }, - // Raw text and RCDATA. - { - "basic raw text", - "<script><a></b></script>", - "<script>$&lt;a&gt;&lt;/b&gt;$</script>", - }, - { - "unfinished script end tag", - "<SCRIPT>a</SCR", - "<script>$a&lt;/SCR", - }, - { - "broken script end tag", - "<SCRIPT>a</SCR ipt>", - "<script>$a&lt;/SCR ipt&gt;", - }, - { - "EOF in script end tag", - "<SCRIPT>a</SCRipt", - "<script>$a&lt;/SCRipt", - }, - { - "scriptx end tag", - "<SCRIPT>a</SCRiptx", - "<script>$a&lt;/SCRiptx", - }, - { - "' ' completes script end tag", - "<SCRIPT>a</SCRipt ", - "<script>$a", - }, - { - "'>' completes script end tag", - "<SCRIPT>a</SCRipt>", - "<script>$a$</script>", - }, - { - "self-closing script end tag", - "<SCRIPT>a</SCRipt/>", - "<script>$a$</script>", - }, - { - "nested script tag", - "<SCRIPT>a</SCRipt<script>", - "<script>$a&lt;/SCRipt&lt;script&gt;", - }, - { - "script end tag after unfinished", - "<SCRIPT>a</SCRipt</script>", - "<script>$a&lt;/SCRipt$</script>", - }, - { - "script/style mismatched tags", - "<script>a</style>", - "<script>$a&lt;/style&gt;", - }, - { - "style element with entity", - "<style>&apos;", - "<style>$&amp;apos;", - }, - { - "textarea with tag", - "<textarea><div></textarea>", - "<textarea>$&lt;div&gt;$</textarea>", - }, - { - "title with tag and entity", - "<title><b>K&amp;R C</b></title>", - "<title>$&lt;b&gt;K&amp;R C&lt;/b&gt;$</title>", - }, - // DOCTYPE tests. - { - "Proper DOCTYPE", - "<!DOCTYPE html>", - "<!DOCTYPE html>", - }, - { - "DOCTYPE with no space", - "<!doctypehtml>", - "<!DOCTYPE html>", - }, - { - "DOCTYPE with two spaces", - "<!doctype html>", - "<!DOCTYPE html>", - }, - { - "looks like DOCTYPE but isn't", - "<!DOCUMENT html>", - "<!--DOCUMENT html-->", - }, - { - "DOCTYPE at EOF", - "<!DOCtype", - "<!DOCTYPE >", - }, - // XML processing instructions. - { - "XML processing instruction", - "<?xml?>", - "<!--?xml?-->", - }, - // Comments. - { - "comment0", - "abc<b><!-- skipme --></b>def", - "abc$<b>$<!-- skipme -->$</b>$def", - }, - { - "comment1", - "a<!-->z", - "a$<!---->$z", - }, - { - "comment2", - "a<!--->z", - "a$<!---->$z", - }, - { - "comment3", - "a<!--x>-->z", - "a$<!--x>-->$z", - }, - { - "comment4", - "a<!--x->-->z", - "a$<!--x->-->$z", - }, - { - "comment5", - "a<!>z", - "a$<!---->$z", - }, - { - "comment6", - "a<!->z", - "a$<!----->$z", - }, - { - "comment7", - "a<!---<>z", - "a$<!---<>z-->", - }, - { - "comment8", - "a<!--z", - "a$<!--z-->", - }, - { - "comment9", - "a<!--z-", - "a$<!--z-->", - }, - { - "comment10", - "a<!--z--", - "a$<!--z-->", - }, - { - "comment11", - "a<!--z---", - "a$<!--z--->", - }, - { - "comment12", - "a<!--z----", - "a$<!--z---->", - }, - { - "comment13", - "a<!--x--!>z", - "a$<!--x-->$z", - }, - // An attribute with a backslash. - { - "backslash", - `<p id="a\"b">`, - `<p id="a\" b"="">`, - }, - // Entities, tag name and attribute key lower-casing, and whitespace - // normalization within a tag. - { - "tricky", - "<p \t\n iD=\"a&quot;B\" foo=\"bar\"><EM>te&lt;&amp;;xt</em></p>", - `<p id="a&#34;B" foo="bar">$<em>$te&lt;&amp;;xt$</em>$</p>`, - }, - // A nonexistent entity. Tokenizing and converting back to a string should - // escape the "&" to become "&amp;". - { - "noSuchEntity", - `<a b="c&noSuchEntity;d">&lt;&alsoDoesntExist;&`, - `<a b="c&amp;noSuchEntity;d">$&lt;&amp;alsoDoesntExist;&amp;`, - }, - { - "entity without semicolon", - `&notit;&notin;<a b="q=z&amp=5&notice=hello&not;=world">`, - `¬it;∉$<a b="q=z&amp;amp=5&amp;notice=hello¬=world">`, - }, - { - "entity with digits", - "&frac12;", - "½", - }, - // Attribute tests: - // http://dev.w3.org/html5/pf-summary/Overview.html#attributes - { - "Empty attribute", - `<input disabled FOO>`, - `<input disabled="" foo="">`, - }, - { - "Empty attribute, whitespace", - `<input disabled FOO >`, - `<input disabled="" foo="">`, - }, - { - "Unquoted attribute value", - `<input value=yes FOO=BAR>`, - `<input value="yes" foo="BAR">`, - }, - { - "Unquoted attribute value, spaces", - `<input value = yes FOO = BAR>`, - `<input value="yes" foo="BAR">`, - }, - { - "Unquoted attribute value, trailing space", - `<input value=yes FOO=BAR >`, - `<input value="yes" foo="BAR">`, - }, - { - "Single-quoted attribute value", - `<input value='yes' FOO='BAR'>`, - `<input value="yes" foo="BAR">`, - }, - { - "Single-quoted attribute value, trailing space", - `<input value='yes' FOO='BAR' >`, - `<input value="yes" foo="BAR">`, - }, - { - "Double-quoted attribute value", - `<input value="I'm an attribute" FOO="BAR">`, - `<input value="I&#39;m an attribute" foo="BAR">`, - }, - { - "Attribute name characters", - `<meta http-equiv="content-type">`, - `<meta http-equiv="content-type">`, - }, - { - "Mixed attributes", - `a<P V="0 1" w='2' X=3 y>z`, - `a$<p v="0 1" w="2" x="3" y="">$z`, - }, - { - "Attributes with a solitary single quote", - `<p id=can't><p id=won't>`, - `<p id="can&#39;t">$<p id="won&#39;t">`, - }, -} - -func TestTokenizer(t *testing.T) { -loop: - for _, tt := range tokenTests { - z := NewTokenizer(strings.NewReader(tt.html)) - if tt.golden != "" { - for i, s := range strings.Split(tt.golden, "$") { - if z.Next() == ErrorToken { - t.Errorf("%s token %d: want %q got error %v", tt.desc, i, s, z.Err()) - continue loop - } - actual := z.Token().String() - if s != actual { - t.Errorf("%s token %d: want %q got %q", tt.desc, i, s, actual) - continue loop - } - } - } - z.Next() - if z.Err() != io.EOF { - t.Errorf("%s: want EOF got %q", tt.desc, z.Err()) - } - } -} - -func TestMaxBuffer(t *testing.T) { - // Exceeding the maximum buffer size generates ErrBufferExceeded. - z := NewTokenizer(strings.NewReader("<" + strings.Repeat("t", 10))) - z.SetMaxBuf(5) - tt := z.Next() - if got, want := tt, ErrorToken; got != want { - t.Fatalf("token type: got: %v want: %v", got, want) - } - if got, want := z.Err(), ErrBufferExceeded; got != want { - t.Errorf("error type: got: %v want: %v", got, want) - } - if got, want := string(z.Raw()), "<tttt"; got != want { - t.Fatalf("buffered before overflow: got: %q want: %q", got, want) - } -} - -func TestMaxBufferReconstruction(t *testing.T) { - // Exceeding the maximum buffer size at any point while tokenizing permits - // reconstructing the original input. -tests: - for _, test := range tokenTests { - for maxBuf := 1; ; maxBuf++ { - r := strings.NewReader(test.html) - z := NewTokenizer(r) - z.SetMaxBuf(maxBuf) - var tokenized bytes.Buffer - for { - tt := z.Next() - tokenized.Write(z.Raw()) - if tt == ErrorToken { - if err := z.Err(); err != io.EOF && err != ErrBufferExceeded { - t.Errorf("%s: unexpected error: %v", test.desc, err) - } - break - } - } - // Anything tokenized along with untokenized input or data left in the reader. - assembled, err := ioutil.ReadAll(io.MultiReader(&tokenized, bytes.NewReader(z.Buffered()), r)) - if err != nil { - t.Errorf("%s: ReadAll: %v", test.desc, err) - continue tests - } - if got, want := string(assembled), test.html; got != want { - t.Errorf("%s: reassembled html:\n got: %q\nwant: %q", test.desc, got, want) - continue tests - } - // EOF indicates that we completed tokenization and hence found the max - // maxBuf that generates ErrBufferExceeded, so continue to the next test. - if z.Err() == io.EOF { - break - } - } // buffer sizes - } // tests -} - -func TestPassthrough(t *testing.T) { - // Accumulating the raw output for each parse event should reconstruct the - // original input. - for _, test := range tokenTests { - z := NewTokenizer(strings.NewReader(test.html)) - var parsed bytes.Buffer - for { - tt := z.Next() - parsed.Write(z.Raw()) - if tt == ErrorToken { - break - } - } - if got, want := parsed.String(), test.html; got != want { - t.Errorf("%s: parsed output:\n got: %q\nwant: %q", test.desc, got, want) - } - } -} - -func TestBufAPI(t *testing.T) { - s := "0<a>1</a>2<b>3<a>4<a>5</a>6</b>7</a>8<a/>9" - z := NewTokenizer(bytes.NewBufferString(s)) - var result bytes.Buffer - depth := 0 -loop: - for { - tt := z.Next() - switch tt { - case ErrorToken: - if z.Err() != io.EOF { - t.Error(z.Err()) - } - break loop - case TextToken: - if depth > 0 { - result.Write(z.Text()) - } - case StartTagToken, EndTagToken: - tn, _ := z.TagName() - if len(tn) == 1 && tn[0] == 'a' { - if tt == StartTagToken { - depth++ - } else { - depth-- - } - } - } - } - u := "14567" - v := string(result.Bytes()) - if u != v { - t.Errorf("TestBufAPI: want %q got %q", u, v) - } -} - -func TestConvertNewlines(t *testing.T) { - testCases := map[string]string{ - "Mac\rDOS\r\nUnix\n": "Mac\nDOS\nUnix\n", - "Unix\nMac\rDOS\r\n": "Unix\nMac\nDOS\n", - "DOS\r\nDOS\r\nDOS\r\n": "DOS\nDOS\nDOS\n", - "": "", - "\n": "\n", - "\n\r": "\n\n", - "\r": "\n", - "\r\n": "\n", - "\r\n\n": "\n\n", - "\r\n\r": "\n\n", - "\r\n\r\n": "\n\n", - "\r\r": "\n\n", - "\r\r\n": "\n\n", - "\r\r\n\n": "\n\n\n", - "\r\r\r\n": "\n\n\n", - "\r \n": "\n \n", - "xyz": "xyz", - } - for in, want := range testCases { - if got := string(convertNewlines([]byte(in))); got != want { - t.Errorf("input %q: got %q, want %q", in, got, want) - } - } -} - -func TestReaderEdgeCases(t *testing.T) { - const s = "<p>An io.Reader can return (0, nil) or (n, io.EOF).</p>" - testCases := []io.Reader{ - &zeroOneByteReader{s: s}, - &eofStringsReader{s: s}, - &stuckReader{}, - } - for i, tc := range testCases { - got := []TokenType{} - z := NewTokenizer(tc) - for { - tt := z.Next() - if tt == ErrorToken { - break - } - got = append(got, tt) - } - if err := z.Err(); err != nil && err != io.EOF { - if err != io.ErrNoProgress { - t.Errorf("i=%d: %v", i, err) - } - continue - } - want := []TokenType{ - StartTagToken, - TextToken, - EndTagToken, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("i=%d: got %v, want %v", i, got, want) - continue - } - } -} - -// zeroOneByteReader is like a strings.Reader that alternates between -// returning 0 bytes and 1 byte at a time. -type zeroOneByteReader struct { - s string - n int -} - -func (r *zeroOneByteReader) Read(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - if len(r.s) == 0 { - return 0, io.EOF - } - r.n++ - if r.n%2 != 0 { - return 0, nil - } - p[0], r.s = r.s[0], r.s[1:] - return 1, nil -} - -// eofStringsReader is like a strings.Reader but can return an (n, err) where -// n > 0 && err != nil. -type eofStringsReader struct { - s string -} - -func (r *eofStringsReader) Read(p []byte) (int, error) { - n := copy(p, r.s) - r.s = r.s[n:] - if r.s != "" { - return n, nil - } - return n, io.EOF -} - -// stuckReader is an io.Reader that always returns no data and no error. -type stuckReader struct{} - -func (*stuckReader) Read(p []byte) (int, error) { - return 0, nil -} - -const ( - rawLevel = iota - lowLevel - highLevel -) - -func benchmarkTokenizer(b *testing.B, level int) { - buf, err := ioutil.ReadFile("testdata/go1.html") - if err != nil { - b.Fatalf("could not read testdata/go1.html: %v", err) - } - b.SetBytes(int64(len(buf))) - runtime.GC() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - z := NewTokenizer(bytes.NewBuffer(buf)) - for { - tt := z.Next() - if tt == ErrorToken { - if err := z.Err(); err != nil && err != io.EOF { - b.Fatalf("tokenizer error: %v", err) - } - break - } - switch level { - case rawLevel: - // Calling z.Raw just returns the raw bytes of the token. It does - // not unescape &lt; to <, or lower-case tag names and attribute keys. - z.Raw() - case lowLevel: - // Caling z.Text, z.TagName and z.TagAttr returns []byte values - // whose contents may change on the next call to z.Next. - switch tt { - case TextToken, CommentToken, DoctypeToken: - z.Text() - case StartTagToken, SelfClosingTagToken: - _, more := z.TagName() - for more { - _, _, more = z.TagAttr() - } - case EndTagToken: - z.TagName() - } - case highLevel: - // Calling z.Token converts []byte values to strings whose validity - // extend beyond the next call to z.Next. - z.Token() - } - } - } -} - -func BenchmarkRawLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, rawLevel) } -func BenchmarkLowLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, lowLevel) } -func BenchmarkHighLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, highLevel) } diff --git a/Godeps/_workspace/src/golang.org/x/net/websocket/exampledial_test.go b/Godeps/_workspace/src/golang.org/x/net/websocket/exampledial_test.go deleted file mode 100644 index 72bb9d48eba..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/websocket/exampledial_test.go +++ /dev/null @@ -1,31 +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 websocket_test - -import ( - "fmt" - "log" - - "golang.org/x/net/websocket" -) - -// This example demonstrates a trivial client. -func ExampleDial() { - origin := "http://localhost/" - url := "ws://localhost:12345/ws" - ws, err := websocket.Dial(url, "", origin) - if err != nil { - log.Fatal(err) - } - if _, err := ws.Write([]byte("hello, world!\n")); err != nil { - log.Fatal(err) - } - var msg = make([]byte, 512) - var n int - if n, err = ws.Read(msg); err != nil { - log.Fatal(err) - } - fmt.Printf("Received: %s.\n", msg[:n]) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/websocket/examplehandler_test.go b/Godeps/_workspace/src/golang.org/x/net/websocket/examplehandler_test.go deleted file mode 100644 index f22a98fcd43..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/websocket/examplehandler_test.go +++ /dev/null @@ -1,26 +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 websocket_test - -import ( - "io" - "net/http" - - "golang.org/x/net/websocket" -) - -// Echo the data received on the WebSocket. -func EchoServer(ws *websocket.Conn) { - io.Copy(ws, ws) -} - -// This example demonstrates a trivial echo server. -func ExampleHandler() { - http.Handle("/echo", websocket.Handler(EchoServer)) - err := http.ListenAndServe(":12345", nil) - if err != nil { - panic("ListenAndServe: " + err.Error()) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/websocket/hybi_test.go b/Godeps/_workspace/src/golang.org/x/net/websocket/hybi_test.go deleted file mode 100644 index 9504aa2d30b..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/websocket/hybi_test.go +++ /dev/null @@ -1,608 +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 websocket - -import ( - "bufio" - "bytes" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "testing" -) - -// Test the getNonceAccept function with values in -// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 -func TestSecWebSocketAccept(t *testing.T) { - nonce := []byte("dGhlIHNhbXBsZSBub25jZQ==") - expected := []byte("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") - accept, err := getNonceAccept(nonce) - if err != nil { - t.Errorf("getNonceAccept: returned error %v", err) - return - } - if !bytes.Equal(expected, accept) { - t.Errorf("getNonceAccept: expected %q got %q", expected, accept) - } -} - -func TestHybiClientHandshake(t *testing.T) { - type test struct { - url, host string - } - tests := []test{ - {"ws://server.example.com/chat", "server.example.com"}, - {"ws://127.0.0.1/chat", "127.0.0.1"}, - } - if _, err := url.ParseRequestURI("http://[fe80::1%25lo0]"); err == nil { - tests = append(tests, test{"ws://[fe80::1%25lo0]/chat", "[fe80::1]"}) - } - - for _, tt := range tests { - var b bytes.Buffer - bw := bufio.NewWriter(&b) - br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols -Upgrade: websocket -Connection: Upgrade -Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= -Sec-WebSocket-Protocol: chat - -`)) - var err error - var config Config - config.Location, err = url.ParseRequestURI(tt.url) - if err != nil { - t.Fatal("location url", err) - } - config.Origin, err = url.ParseRequestURI("http://example.com") - if err != nil { - t.Fatal("origin url", err) - } - config.Protocol = append(config.Protocol, "chat") - config.Protocol = append(config.Protocol, "superchat") - config.Version = ProtocolVersionHybi13 - config.handshakeData = map[string]string{ - "key": "dGhlIHNhbXBsZSBub25jZQ==", - } - if err := hybiClientHandshake(&config, br, bw); err != nil { - t.Fatal("handshake", err) - } - req, err := http.ReadRequest(bufio.NewReader(&b)) - if err != nil { - t.Fatal("read request", err) - } - if req.Method != "GET" { - t.Errorf("request method expected GET, but got %s", req.Method) - } - if req.URL.Path != "/chat" { - t.Errorf("request path expected /chat, but got %s", req.URL.Path) - } - if req.Proto != "HTTP/1.1" { - t.Errorf("request proto expected HTTP/1.1, but got %s", req.Proto) - } - if req.Host != tt.host { - t.Errorf("request host expected %s, but got %s", tt.host, req.Host) - } - var expectedHeader = map[string]string{ - "Connection": "Upgrade", - "Upgrade": "websocket", - "Sec-Websocket-Key": config.handshakeData["key"], - "Origin": config.Origin.String(), - "Sec-Websocket-Protocol": "chat, superchat", - "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), - } - for k, v := range expectedHeader { - if req.Header.Get(k) != v { - t.Errorf("%s expected %s, but got %v", k, v, req.Header.Get(k)) - } - } - } -} - -func TestHybiClientHandshakeWithHeader(t *testing.T) { - b := bytes.NewBuffer([]byte{}) - bw := bufio.NewWriter(b) - br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols -Upgrade: websocket -Connection: Upgrade -Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= -Sec-WebSocket-Protocol: chat - -`)) - var err error - config := new(Config) - config.Location, err = url.ParseRequestURI("ws://server.example.com/chat") - if err != nil { - t.Fatal("location url", err) - } - config.Origin, err = url.ParseRequestURI("http://example.com") - if err != nil { - t.Fatal("origin url", err) - } - config.Protocol = append(config.Protocol, "chat") - config.Protocol = append(config.Protocol, "superchat") - config.Version = ProtocolVersionHybi13 - config.Header = http.Header(make(map[string][]string)) - config.Header.Add("User-Agent", "test") - - config.handshakeData = map[string]string{ - "key": "dGhlIHNhbXBsZSBub25jZQ==", - } - err = hybiClientHandshake(config, br, bw) - if err != nil { - t.Errorf("handshake failed: %v", err) - } - req, err := http.ReadRequest(bufio.NewReader(b)) - if err != nil { - t.Fatalf("read request: %v", err) - } - if req.Method != "GET" { - t.Errorf("request method expected GET, but got %q", req.Method) - } - if req.URL.Path != "/chat" { - t.Errorf("request path expected /chat, but got %q", req.URL.Path) - } - if req.Proto != "HTTP/1.1" { - t.Errorf("request proto expected HTTP/1.1, but got %q", req.Proto) - } - if req.Host != "server.example.com" { - t.Errorf("request Host expected server.example.com, but got %v", req.Host) - } - var expectedHeader = map[string]string{ - "Connection": "Upgrade", - "Upgrade": "websocket", - "Sec-Websocket-Key": config.handshakeData["key"], - "Origin": config.Origin.String(), - "Sec-Websocket-Protocol": "chat, superchat", - "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), - "User-Agent": "test", - } - for k, v := range expectedHeader { - if req.Header.Get(k) != v { - t.Errorf(fmt.Sprintf("%s expected %q but got %q", k, v, req.Header.Get(k))) - } - } -} - -func TestHybiServerHandshake(t *testing.T) { - config := new(Config) - handshaker := &hybiServerHandshaker{Config: config} - br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 -Host: server.example.com -Upgrade: websocket -Connection: Upgrade -Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== -Origin: http://example.com -Sec-WebSocket-Protocol: chat, superchat -Sec-WebSocket-Version: 13 - -`)) - req, err := http.ReadRequest(br) - if err != nil { - t.Fatal("request", err) - } - code, err := handshaker.ReadHandshake(br, req) - if err != nil { - t.Errorf("handshake failed: %v", err) - } - if code != http.StatusSwitchingProtocols { - t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) - } - expectedProtocols := []string{"chat", "superchat"} - if fmt.Sprintf("%v", config.Protocol) != fmt.Sprintf("%v", expectedProtocols) { - t.Errorf("protocol expected %q but got %q", expectedProtocols, config.Protocol) - } - b := bytes.NewBuffer([]byte{}) - bw := bufio.NewWriter(b) - - config.Protocol = config.Protocol[:1] - - err = handshaker.AcceptHandshake(bw) - if err != nil { - t.Errorf("handshake response failed: %v", err) - } - expectedResponse := strings.Join([]string{ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", - "Sec-WebSocket-Protocol: chat", - "", ""}, "\r\n") - - if b.String() != expectedResponse { - t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) - } -} - -func TestHybiServerHandshakeNoSubProtocol(t *testing.T) { - config := new(Config) - handshaker := &hybiServerHandshaker{Config: config} - br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 -Host: server.example.com -Upgrade: websocket -Connection: Upgrade -Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== -Origin: http://example.com -Sec-WebSocket-Version: 13 - -`)) - req, err := http.ReadRequest(br) - if err != nil { - t.Fatal("request", err) - } - code, err := handshaker.ReadHandshake(br, req) - if err != nil { - t.Errorf("handshake failed: %v", err) - } - if code != http.StatusSwitchingProtocols { - t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) - } - if len(config.Protocol) != 0 { - t.Errorf("len(config.Protocol) expected 0, but got %q", len(config.Protocol)) - } - b := bytes.NewBuffer([]byte{}) - bw := bufio.NewWriter(b) - - err = handshaker.AcceptHandshake(bw) - if err != nil { - t.Errorf("handshake response failed: %v", err) - } - expectedResponse := strings.Join([]string{ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", - "", ""}, "\r\n") - - if b.String() != expectedResponse { - t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) - } -} - -func TestHybiServerHandshakeHybiBadVersion(t *testing.T) { - config := new(Config) - handshaker := &hybiServerHandshaker{Config: config} - br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 -Host: server.example.com -Upgrade: websocket -Connection: Upgrade -Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== -Sec-WebSocket-Origin: http://example.com -Sec-WebSocket-Protocol: chat, superchat -Sec-WebSocket-Version: 9 - -`)) - req, err := http.ReadRequest(br) - if err != nil { - t.Fatal("request", err) - } - code, err := handshaker.ReadHandshake(br, req) - if err != ErrBadWebSocketVersion { - t.Errorf("handshake expected err %q but got %q", ErrBadWebSocketVersion, err) - } - if code != http.StatusBadRequest { - t.Errorf("status expected %q but got %q", http.StatusBadRequest, code) - } -} - -func testHybiFrame(t *testing.T, testHeader, testPayload, testMaskedPayload []byte, frameHeader *hybiFrameHeader) { - b := bytes.NewBuffer([]byte{}) - frameWriterFactory := &hybiFrameWriterFactory{bufio.NewWriter(b), false} - w, _ := frameWriterFactory.NewFrameWriter(TextFrame) - w.(*hybiFrameWriter).header = frameHeader - _, err := w.Write(testPayload) - w.Close() - if err != nil { - t.Errorf("Write error %q", err) - } - var expectedFrame []byte - expectedFrame = append(expectedFrame, testHeader...) - expectedFrame = append(expectedFrame, testMaskedPayload...) - if !bytes.Equal(expectedFrame, b.Bytes()) { - t.Errorf("frame expected %q got %q", expectedFrame, b.Bytes()) - } - frameReaderFactory := &hybiFrameReaderFactory{bufio.NewReader(b)} - r, err := frameReaderFactory.NewFrameReader() - if err != nil { - t.Errorf("Read error %q", err) - } - if header := r.HeaderReader(); header == nil { - t.Errorf("no header") - } else { - actualHeader := make([]byte, r.Len()) - n, err := header.Read(actualHeader) - if err != nil { - t.Errorf("Read header error %q", err) - } else { - if n < len(testHeader) { - t.Errorf("header too short %q got %q", testHeader, actualHeader[:n]) - } - if !bytes.Equal(testHeader, actualHeader[:n]) { - t.Errorf("header expected %q got %q", testHeader, actualHeader[:n]) - } - } - } - if trailer := r.TrailerReader(); trailer != nil { - t.Errorf("unexpected trailer %q", trailer) - } - frame := r.(*hybiFrameReader) - if frameHeader.Fin != frame.header.Fin || - frameHeader.OpCode != frame.header.OpCode || - len(testPayload) != int(frame.header.Length) { - t.Errorf("mismatch %v (%d) vs %v", frameHeader, len(testPayload), frame) - } - payload := make([]byte, len(testPayload)) - _, err = r.Read(payload) - if err != nil && err != io.EOF { - t.Errorf("read %v", err) - } - if !bytes.Equal(testPayload, payload) { - t.Errorf("payload %q vs %q", testPayload, payload) - } -} - -func TestHybiShortTextFrame(t *testing.T) { - frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} - payload := []byte("hello") - testHybiFrame(t, []byte{0x81, 0x05}, payload, payload, frameHeader) - - payload = make([]byte, 125) - testHybiFrame(t, []byte{0x81, 125}, payload, payload, frameHeader) -} - -func TestHybiShortMaskedTextFrame(t *testing.T) { - frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame, - MaskingKey: []byte{0xcc, 0x55, 0x80, 0x20}} - payload := []byte("hello") - maskedPayload := []byte{0xa4, 0x30, 0xec, 0x4c, 0xa3} - header := []byte{0x81, 0x85} - header = append(header, frameHeader.MaskingKey...) - testHybiFrame(t, header, payload, maskedPayload, frameHeader) -} - -func TestHybiShortBinaryFrame(t *testing.T) { - frameHeader := &hybiFrameHeader{Fin: true, OpCode: BinaryFrame} - payload := []byte("hello") - testHybiFrame(t, []byte{0x82, 0x05}, payload, payload, frameHeader) - - payload = make([]byte, 125) - testHybiFrame(t, []byte{0x82, 125}, payload, payload, frameHeader) -} - -func TestHybiControlFrame(t *testing.T) { - payload := []byte("hello") - - frameHeader := &hybiFrameHeader{Fin: true, OpCode: PingFrame} - testHybiFrame(t, []byte{0x89, 0x05}, payload, payload, frameHeader) - - frameHeader = &hybiFrameHeader{Fin: true, OpCode: PingFrame} - testHybiFrame(t, []byte{0x89, 0x00}, nil, nil, frameHeader) - - frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} - testHybiFrame(t, []byte{0x8A, 0x05}, payload, payload, frameHeader) - - frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} - testHybiFrame(t, []byte{0x8A, 0x00}, nil, nil, frameHeader) - - frameHeader = &hybiFrameHeader{Fin: true, OpCode: CloseFrame} - payload = []byte{0x03, 0xe8} // 1000 - testHybiFrame(t, []byte{0x88, 0x02}, payload, payload, frameHeader) -} - -func TestHybiLongFrame(t *testing.T) { - frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} - payload := make([]byte, 126) - testHybiFrame(t, []byte{0x81, 126, 0x00, 126}, payload, payload, frameHeader) - - payload = make([]byte, 65535) - testHybiFrame(t, []byte{0x81, 126, 0xff, 0xff}, payload, payload, frameHeader) - - payload = make([]byte, 65536) - testHybiFrame(t, []byte{0x81, 127, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}, payload, payload, frameHeader) -} - -func TestHybiClientRead(t *testing.T) { - wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', - 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping - 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} - br := bufio.NewReader(bytes.NewBuffer(wireData)) - bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) - conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) - - msg := make([]byte, 512) - n, err := conn.Read(msg) - if err != nil { - t.Errorf("read 1st frame, error %q", err) - } - if n != 5 { - t.Errorf("read 1st frame, expect 5, got %d", n) - } - if !bytes.Equal(wireData[2:7], msg[:n]) { - t.Errorf("read 1st frame %v, got %v", wireData[2:7], msg[:n]) - } - n, err = conn.Read(msg) - if err != nil { - t.Errorf("read 2nd frame, error %q", err) - } - if n != 5 { - t.Errorf("read 2nd frame, expect 5, got %d", n) - } - if !bytes.Equal(wireData[16:21], msg[:n]) { - t.Errorf("read 2nd frame %v, got %v", wireData[16:21], msg[:n]) - } - n, err = conn.Read(msg) - if err == nil { - t.Errorf("read not EOF") - } - if n != 0 { - t.Errorf("expect read 0, got %d", n) - } -} - -func TestHybiShortRead(t *testing.T) { - wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', - 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping - 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} - br := bufio.NewReader(bytes.NewBuffer(wireData)) - bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) - conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) - - step := 0 - pos := 0 - expectedPos := []int{2, 5, 16, 19} - expectedLen := []int{3, 2, 3, 2} - for { - msg := make([]byte, 3) - n, err := conn.Read(msg) - if step >= len(expectedPos) { - if err == nil { - t.Errorf("read not EOF") - } - if n != 0 { - t.Errorf("expect read 0, got %d", n) - } - return - } - pos = expectedPos[step] - endPos := pos + expectedLen[step] - if err != nil { - t.Errorf("read from %d, got error %q", pos, err) - return - } - if n != endPos-pos { - t.Errorf("read from %d, expect %d, got %d", pos, endPos-pos, n) - } - if !bytes.Equal(wireData[pos:endPos], msg[:n]) { - t.Errorf("read from %d, frame %v, got %v", pos, wireData[pos:endPos], msg[:n]) - } - step++ - } -} - -func TestHybiServerRead(t *testing.T) { - wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, - 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello - 0x89, 0x85, 0xcc, 0x55, 0x80, 0x20, - 0xa4, 0x30, 0xec, 0x4c, 0xa3, // ping: hello - 0x81, 0x85, 0xed, 0x83, 0xb4, 0x24, - 0x9a, 0xec, 0xc6, 0x48, 0x89, // world - } - br := bufio.NewReader(bytes.NewBuffer(wireData)) - bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) - conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) - - expected := [][]byte{[]byte("hello"), []byte("world")} - - msg := make([]byte, 512) - n, err := conn.Read(msg) - if err != nil { - t.Errorf("read 1st frame, error %q", err) - } - if n != 5 { - t.Errorf("read 1st frame, expect 5, got %d", n) - } - if !bytes.Equal(expected[0], msg[:n]) { - t.Errorf("read 1st frame %q, got %q", expected[0], msg[:n]) - } - - n, err = conn.Read(msg) - if err != nil { - t.Errorf("read 2nd frame, error %q", err) - } - if n != 5 { - t.Errorf("read 2nd frame, expect 5, got %d", n) - } - if !bytes.Equal(expected[1], msg[:n]) { - t.Errorf("read 2nd frame %q, got %q", expected[1], msg[:n]) - } - - n, err = conn.Read(msg) - if err == nil { - t.Errorf("read not EOF") - } - if n != 0 { - t.Errorf("expect read 0, got %d", n) - } -} - -func TestHybiServerReadWithoutMasking(t *testing.T) { - wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o'} - br := bufio.NewReader(bytes.NewBuffer(wireData)) - bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) - conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) - // server MUST close the connection upon receiving a non-masked frame. - msg := make([]byte, 512) - _, err := conn.Read(msg) - if err != io.EOF { - t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) - } -} - -func TestHybiClientReadWithMasking(t *testing.T) { - wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, - 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello - } - br := bufio.NewReader(bytes.NewBuffer(wireData)) - bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) - conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) - - // client MUST close the connection upon receiving a masked frame. - msg := make([]byte, 512) - _, err := conn.Read(msg) - if err != io.EOF { - t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) - } -} - -// Test the hybiServerHandshaker supports firefox implementation and -// checks Connection request header include (but it's not necessary -// equal to) "upgrade" -func TestHybiServerFirefoxHandshake(t *testing.T) { - config := new(Config) - handshaker := &hybiServerHandshaker{Config: config} - br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 -Host: server.example.com -Upgrade: websocket -Connection: keep-alive, upgrade -Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== -Origin: http://example.com -Sec-WebSocket-Protocol: chat, superchat -Sec-WebSocket-Version: 13 - -`)) - req, err := http.ReadRequest(br) - if err != nil { - t.Fatal("request", err) - } - code, err := handshaker.ReadHandshake(br, req) - if err != nil { - t.Errorf("handshake failed: %v", err) - } - if code != http.StatusSwitchingProtocols { - t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) - } - b := bytes.NewBuffer([]byte{}) - bw := bufio.NewWriter(b) - - config.Protocol = []string{"chat"} - - err = handshaker.AcceptHandshake(bw) - if err != nil { - t.Errorf("handshake response failed: %v", err) - } - expectedResponse := strings.Join([]string{ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", - "Sec-WebSocket-Protocol: chat", - "", ""}, "\r\n") - - if b.String() != expectedResponse { - t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/websocket/websocket_test.go b/Godeps/_workspace/src/golang.org/x/net/websocket/websocket_test.go deleted file mode 100644 index 05b7e5356e4..00000000000 --- a/Godeps/_workspace/src/golang.org/x/net/websocket/websocket_test.go +++ /dev/null @@ -1,587 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bytes" - "fmt" - "io" - "log" - "net" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -var serverAddr string -var once sync.Once - -func echoServer(ws *Conn) { - defer ws.Close() - io.Copy(ws, ws) -} - -type Count struct { - S string - N int -} - -func countServer(ws *Conn) { - defer ws.Close() - for { - var count Count - err := JSON.Receive(ws, &count) - if err != nil { - return - } - count.N++ - count.S = strings.Repeat(count.S, count.N) - err = JSON.Send(ws, count) - if err != nil { - return - } - } -} - -type testCtrlAndDataHandler struct { - hybiFrameHandler -} - -func (h *testCtrlAndDataHandler) WritePing(b []byte) (int, error) { - h.hybiFrameHandler.conn.wio.Lock() - defer h.hybiFrameHandler.conn.wio.Unlock() - w, err := h.hybiFrameHandler.conn.frameWriterFactory.NewFrameWriter(PingFrame) - if err != nil { - return 0, err - } - n, err := w.Write(b) - w.Close() - return n, err -} - -func ctrlAndDataServer(ws *Conn) { - defer ws.Close() - h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} - ws.frameHandler = h - - go func() { - for i := 0; ; i++ { - var b []byte - if i%2 != 0 { // with or without payload - b = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-SERVER", i)) - } - if _, err := h.WritePing(b); err != nil { - break - } - if _, err := h.WritePong(b); err != nil { // unsolicited pong - break - } - time.Sleep(10 * time.Millisecond) - } - }() - - b := make([]byte, 128) - for { - n, err := ws.Read(b) - if err != nil { - break - } - if _, err := ws.Write(b[:n]); err != nil { - break - } - } -} - -func subProtocolHandshake(config *Config, req *http.Request) error { - for _, proto := range config.Protocol { - if proto == "chat" { - config.Protocol = []string{proto} - return nil - } - } - return ErrBadWebSocketProtocol -} - -func subProtoServer(ws *Conn) { - for _, proto := range ws.Config().Protocol { - io.WriteString(ws, proto) - } -} - -func startServer() { - http.Handle("/echo", Handler(echoServer)) - http.Handle("/count", Handler(countServer)) - http.Handle("/ctrldata", Handler(ctrlAndDataServer)) - subproto := Server{ - Handshake: subProtocolHandshake, - Handler: Handler(subProtoServer), - } - http.Handle("/subproto", subproto) - server := httptest.NewServer(nil) - serverAddr = server.Listener.Addr().String() - log.Print("Test WebSocket server listening on ", serverAddr) -} - -func newConfig(t *testing.T, path string) *Config { - config, _ := NewConfig(fmt.Sprintf("ws://%s%s", serverAddr, path), "http://localhost") - return config -} - -func TestEcho(t *testing.T) { - once.Do(startServer) - - // websocket.Dial() - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - conn, err := NewClient(newConfig(t, "/echo"), client) - if err != nil { - t.Errorf("WebSocket handshake error: %v", err) - return - } - - msg := []byte("hello, world\n") - if _, err := conn.Write(msg); err != nil { - t.Errorf("Write: %v", err) - } - var actual_msg = make([]byte, 512) - n, err := conn.Read(actual_msg) - if err != nil { - t.Errorf("Read: %v", err) - } - actual_msg = actual_msg[0:n] - if !bytes.Equal(msg, actual_msg) { - t.Errorf("Echo: expected %q got %q", msg, actual_msg) - } - conn.Close() -} - -func TestAddr(t *testing.T) { - once.Do(startServer) - - // websocket.Dial() - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - conn, err := NewClient(newConfig(t, "/echo"), client) - if err != nil { - t.Errorf("WebSocket handshake error: %v", err) - return - } - - ra := conn.RemoteAddr().String() - if !strings.HasPrefix(ra, "ws://") || !strings.HasSuffix(ra, "/echo") { - t.Errorf("Bad remote addr: %v", ra) - } - la := conn.LocalAddr().String() - if !strings.HasPrefix(la, "http://") { - t.Errorf("Bad local addr: %v", la) - } - conn.Close() -} - -func TestCount(t *testing.T) { - once.Do(startServer) - - // websocket.Dial() - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - conn, err := NewClient(newConfig(t, "/count"), client) - if err != nil { - t.Errorf("WebSocket handshake error: %v", err) - return - } - - var count Count - count.S = "hello" - if err := JSON.Send(conn, count); err != nil { - t.Errorf("Write: %v", err) - } - if err := JSON.Receive(conn, &count); err != nil { - t.Errorf("Read: %v", err) - } - if count.N != 1 { - t.Errorf("count: expected %d got %d", 1, count.N) - } - if count.S != "hello" { - t.Errorf("count: expected %q got %q", "hello", count.S) - } - if err := JSON.Send(conn, count); err != nil { - t.Errorf("Write: %v", err) - } - if err := JSON.Receive(conn, &count); err != nil { - t.Errorf("Read: %v", err) - } - if count.N != 2 { - t.Errorf("count: expected %d got %d", 2, count.N) - } - if count.S != "hellohello" { - t.Errorf("count: expected %q got %q", "hellohello", count.S) - } - conn.Close() -} - -func TestWithQuery(t *testing.T) { - once.Do(startServer) - - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - - config := newConfig(t, "/echo") - config.Location, err = url.ParseRequestURI(fmt.Sprintf("ws://%s/echo?q=v", serverAddr)) - if err != nil { - t.Fatal("location url", err) - } - - ws, err := NewClient(config, client) - if err != nil { - t.Errorf("WebSocket handshake: %v", err) - return - } - ws.Close() -} - -func testWithProtocol(t *testing.T, subproto []string) (string, error) { - once.Do(startServer) - - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - - config := newConfig(t, "/subproto") - config.Protocol = subproto - - ws, err := NewClient(config, client) - if err != nil { - return "", err - } - msg := make([]byte, 16) - n, err := ws.Read(msg) - if err != nil { - return "", err - } - ws.Close() - return string(msg[:n]), nil -} - -func TestWithProtocol(t *testing.T) { - proto, err := testWithProtocol(t, []string{"chat"}) - if err != nil { - t.Errorf("SubProto: unexpected error: %v", err) - } - if proto != "chat" { - t.Errorf("SubProto: expected %q, got %q", "chat", proto) - } -} - -func TestWithTwoProtocol(t *testing.T) { - proto, err := testWithProtocol(t, []string{"test", "chat"}) - if err != nil { - t.Errorf("SubProto: unexpected error: %v", err) - } - if proto != "chat" { - t.Errorf("SubProto: expected %q, got %q", "chat", proto) - } -} - -func TestWithBadProtocol(t *testing.T) { - _, err := testWithProtocol(t, []string{"test"}) - if err != ErrBadStatus { - t.Errorf("SubProto: expected %v, got %v", ErrBadStatus, err) - } -} - -func TestHTTP(t *testing.T) { - once.Do(startServer) - - // If the client did not send a handshake that matches the protocol - // specification, the server MUST return an HTTP response with an - // appropriate error code (such as 400 Bad Request) - resp, err := http.Get(fmt.Sprintf("http://%s/echo", serverAddr)) - if err != nil { - t.Errorf("Get: error %#v", err) - return - } - if resp == nil { - t.Error("Get: resp is null") - return - } - if resp.StatusCode != http.StatusBadRequest { - t.Errorf("Get: expected %q got %q", http.StatusBadRequest, resp.StatusCode) - } -} - -func TestTrailingSpaces(t *testing.T) { - // http://code.google.com/p/go/issues/detail?id=955 - // The last runs of this create keys with trailing spaces that should not be - // generated by the client. - once.Do(startServer) - config := newConfig(t, "/echo") - for i := 0; i < 30; i++ { - // body - ws, err := DialConfig(config) - if err != nil { - t.Errorf("Dial #%d failed: %v", i, err) - break - } - ws.Close() - } -} - -func TestDialConfigBadVersion(t *testing.T) { - once.Do(startServer) - config := newConfig(t, "/echo") - config.Version = 1234 - - _, err := DialConfig(config) - - if dialerr, ok := err.(*DialError); ok { - if dialerr.Err != ErrBadProtocolVersion { - t.Errorf("dial expected err %q but got %q", ErrBadProtocolVersion, dialerr.Err) - } - } -} - -func TestSmallBuffer(t *testing.T) { - // http://code.google.com/p/go/issues/detail?id=1145 - // Read should be able to handle reading a fragment of a frame. - once.Do(startServer) - - // websocket.Dial() - client, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - conn, err := NewClient(newConfig(t, "/echo"), client) - if err != nil { - t.Errorf("WebSocket handshake error: %v", err) - return - } - - msg := []byte("hello, world\n") - if _, err := conn.Write(msg); err != nil { - t.Errorf("Write: %v", err) - } - var small_msg = make([]byte, 8) - n, err := conn.Read(small_msg) - if err != nil { - t.Errorf("Read: %v", err) - } - if !bytes.Equal(msg[:len(small_msg)], small_msg) { - t.Errorf("Echo: expected %q got %q", msg[:len(small_msg)], small_msg) - } - var second_msg = make([]byte, len(msg)) - n, err = conn.Read(second_msg) - if err != nil { - t.Errorf("Read: %v", err) - } - second_msg = second_msg[0:n] - if !bytes.Equal(msg[len(small_msg):], second_msg) { - t.Errorf("Echo: expected %q got %q", msg[len(small_msg):], second_msg) - } - conn.Close() -} - -var parseAuthorityTests = []struct { - in *url.URL - out string -}{ - { - &url.URL{ - Scheme: "ws", - Host: "www.google.com", - }, - "www.google.com:80", - }, - { - &url.URL{ - Scheme: "wss", - Host: "www.google.com", - }, - "www.google.com:443", - }, - { - &url.URL{ - Scheme: "ws", - Host: "www.google.com:80", - }, - "www.google.com:80", - }, - { - &url.URL{ - Scheme: "wss", - Host: "www.google.com:443", - }, - "www.google.com:443", - }, - // some invalid ones for parseAuthority. parseAuthority doesn't - // concern itself with the scheme unless it actually knows about it - { - &url.URL{ - Scheme: "http", - Host: "www.google.com", - }, - "www.google.com", - }, - { - &url.URL{ - Scheme: "http", - Host: "www.google.com:80", - }, - "www.google.com:80", - }, - { - &url.URL{ - Scheme: "asdf", - Host: "127.0.0.1", - }, - "127.0.0.1", - }, - { - &url.URL{ - Scheme: "asdf", - Host: "www.google.com", - }, - "www.google.com", - }, -} - -func TestParseAuthority(t *testing.T) { - for _, tt := range parseAuthorityTests { - out := parseAuthority(tt.in) - if out != tt.out { - t.Errorf("got %v; want %v", out, tt.out) - } - } -} - -type closerConn struct { - net.Conn - closed int // count of the number of times Close was called -} - -func (c *closerConn) Close() error { - c.closed++ - return c.Conn.Close() -} - -func TestClose(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/11454") - } - - once.Do(startServer) - - conn, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal("dialing", err) - } - - cc := closerConn{Conn: conn} - - client, err := NewClient(newConfig(t, "/echo"), &cc) - if err != nil { - t.Fatalf("WebSocket handshake: %v", err) - } - - // set the deadline to ten minutes ago, which will have expired by the time - // client.Close sends the close status frame. - conn.SetDeadline(time.Now().Add(-10 * time.Minute)) - - if err := client.Close(); err == nil { - t.Errorf("ws.Close(): expected error, got %v", err) - } - if cc.closed < 1 { - t.Fatalf("ws.Close(): expected underlying ws.rwc.Close to be called > 0 times, got: %v", cc.closed) - } -} - -var originTests = []struct { - req *http.Request - origin *url.URL -}{ - { - req: &http.Request{ - Header: http.Header{ - "Origin": []string{"http://www.example.com"}, - }, - }, - origin: &url.URL{ - Scheme: "http", - Host: "www.example.com", - }, - }, - { - req: &http.Request{}, - }, -} - -func TestOrigin(t *testing.T) { - conf := newConfig(t, "/echo") - conf.Version = ProtocolVersionHybi13 - for i, tt := range originTests { - origin, err := Origin(conf, tt.req) - if err != nil { - t.Error(err) - continue - } - if !reflect.DeepEqual(origin, tt.origin) { - t.Errorf("#%d: got origin %v; want %v", i, origin, tt.origin) - continue - } - } -} - -func TestCtrlAndData(t *testing.T) { - once.Do(startServer) - - c, err := net.Dial("tcp", serverAddr) - if err != nil { - t.Fatal(err) - } - ws, err := NewClient(newConfig(t, "/ctrldata"), c) - if err != nil { - t.Fatal(err) - } - defer ws.Close() - - h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} - ws.frameHandler = h - - b := make([]byte, 128) - for i := 0; i < 2; i++ { - data := []byte(fmt.Sprintf("#%d-DATA-FRAME-FROM-CLIENT", i)) - if _, err := ws.Write(data); err != nil { - t.Fatalf("#%d: %v", i, err) - } - var ctrl []byte - if i%2 != 0 { // with or without payload - ctrl = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-CLIENT", i)) - } - if _, err := h.WritePing(ctrl); err != nil { - t.Fatalf("#%d: %v", i, err) - } - n, err := ws.Read(b) - if err != nil { - t.Fatalf("#%d: %v", i, err) - } - if !bytes.Equal(b[:n], data) { - t.Fatalf("#%d: got %v; want %v", i, b[:n], data) - } - } -} 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 ab319e0828c..00000000000 --- 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 8be27885567..00000000000 --- 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/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/example_test.go deleted file mode 100644 index 17262802a91..00000000000 --- 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 4cc01884b2c..00000000000 --- 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/sdk_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk_test.go deleted file mode 100644 index 79df8896443..00000000000 --- 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 ff5eefbd0a8..00000000000 --- 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 025de886cf7..00000000000 --- 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 014a351e006..00000000000 --- 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 864f6fa07ef..00000000000 --- 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/jwt/example_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/example_test.go deleted file mode 100644 index 6d618836ea3..00000000000 --- 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_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt_test.go deleted file mode 100644 index da922c3d00d..00000000000 --- 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 2f7d731c1b5..00000000000 --- 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 "<nil>", and no - // non-nil expected error ever stringifies as "<nil>", 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 739eeb2a205..00000000000 --- 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 35cb25ed56e..00000000000 --- 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/golang.org/x/tools/go/ast/astutil/enclosing_test.go b/Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/enclosing_test.go deleted file mode 100644 index 107f87c55c5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/enclosing_test.go +++ /dev/null @@ -1,195 +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 astutil_test - -// This file defines tests of PathEnclosingInterval. - -// TODO(adonovan): exhaustive tests that run over the whole input -// tree, not just handcrafted examples. - -import ( - "bytes" - "fmt" - "go/ast" - "go/parser" - "go/token" - "strings" - "testing" - - "golang.org/x/tools/go/ast/astutil" -) - -// pathToString returns a string containing the concrete types of the -// nodes in path. -func pathToString(path []ast.Node) string { - var buf bytes.Buffer - fmt.Fprint(&buf, "[") - for i, n := range path { - if i > 0 { - fmt.Fprint(&buf, " ") - } - fmt.Fprint(&buf, strings.TrimPrefix(fmt.Sprintf("%T", n), "*ast.")) - } - fmt.Fprint(&buf, "]") - return buf.String() -} - -// findInterval parses input and returns the [start, end) positions of -// the first occurrence of substr in input. f==nil indicates failure; -// an error has already been reported in that case. -// -func findInterval(t *testing.T, fset *token.FileSet, input, substr string) (f *ast.File, start, end token.Pos) { - f, err := parser.ParseFile(fset, "<input>", input, 0) - if err != nil { - t.Errorf("parse error: %s", err) - return - } - - i := strings.Index(input, substr) - if i < 0 { - t.Errorf("%q is not a substring of input", substr) - f = nil - return - } - - filePos := fset.File(f.Package) - return f, filePos.Pos(i), filePos.Pos(i + len(substr)) -} - -// Common input for following tests. -const input = ` -// Hello. -package main -import "fmt" -func f() {} -func main() { - z := (x + y) // add them - f() // NB: ExprStmt and its CallExpr have same Pos/End -} -` - -func TestPathEnclosingInterval_Exact(t *testing.T) { - // For the exact tests, we check that a substring is mapped to - // the canonical string for the node it denotes. - tests := []struct { - substr string // first occurrence of this string indicates interval - node string // complete text of expected containing node - }{ - {"package", - input[11 : len(input)-1]}, - {"\npack", - input[11 : len(input)-1]}, - {"main", - "main"}, - {"import", - "import \"fmt\""}, - {"\"fmt\"", - "\"fmt\""}, - {"\nfunc f() {}\n", - "func f() {}"}, - {"x ", - "x"}, - {" y", - "y"}, - {"z", - "z"}, - {" + ", - "x + y"}, - {" :=", - "z := (x + y)"}, - {"x + y", - "x + y"}, - {"(x + y)", - "(x + y)"}, - {" (x + y) ", - "(x + y)"}, - {" (x + y) // add", - "(x + y)"}, - {"func", - "func f() {}"}, - {"func f() {}", - "func f() {}"}, - {"\nfun", - "func f() {}"}, - {" f", - "f"}, - } - for _, test := range tests { - f, start, end := findInterval(t, new(token.FileSet), input, test.substr) - if f == nil { - continue - } - - path, exact := astutil.PathEnclosingInterval(f, start, end) - if !exact { - t.Errorf("PathEnclosingInterval(%q) not exact", test.substr) - continue - } - - if len(path) == 0 { - if test.node != "" { - t.Errorf("PathEnclosingInterval(%q).path: got [], want %q", - test.substr, test.node) - } - continue - } - - if got := input[path[0].Pos():path[0].End()]; got != test.node { - t.Errorf("PathEnclosingInterval(%q): got %q, want %q (path was %s)", - test.substr, got, test.node, pathToString(path)) - continue - } - } -} - -func TestPathEnclosingInterval_Paths(t *testing.T) { - // For these tests, we check only the path of the enclosing - // node, but not its complete text because it's often quite - // large when !exact. - tests := []struct { - substr string // first occurrence of this string indicates interval - path string // the pathToString(),exact of the expected path - }{ - {"// add", - "[BlockStmt FuncDecl File],false"}, - {"(x + y", - "[ParenExpr AssignStmt BlockStmt FuncDecl File],false"}, - {"x +", - "[BinaryExpr ParenExpr AssignStmt BlockStmt FuncDecl File],false"}, - {"z := (x", - "[AssignStmt BlockStmt FuncDecl File],false"}, - {"func f", - "[FuncDecl File],false"}, - {"func f()", - "[FuncDecl File],false"}, - {" f()", - "[FuncDecl File],false"}, - {"() {}", - "[FuncDecl File],false"}, - {"// Hello", - "[File],false"}, - {" f", - "[Ident FuncDecl File],true"}, - {"func ", - "[FuncDecl File],true"}, - {"mai", - "[Ident File],true"}, - {"f() // NB", - "[CallExpr ExprStmt BlockStmt FuncDecl File],true"}, - } - for _, test := range tests { - f, start, end := findInterval(t, new(token.FileSet), input, test.substr) - if f == nil { - continue - } - - path, exact := astutil.PathEnclosingInterval(f, start, end) - if got := fmt.Sprintf("%s,%v", pathToString(path), exact); got != test.path { - t.Errorf("PathEnclosingInterval(%q): got %q, want %q", - test.substr, got, test.path) - continue - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/imports_test.go b/Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/imports_test.go deleted file mode 100644 index 9134b193c4c..00000000000 --- a/Godeps/_workspace/src/golang.org/x/tools/go/ast/astutil/imports_test.go +++ /dev/null @@ -1,946 +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 astutil - -import ( - "bytes" - "go/ast" - "go/format" - "go/parser" - "go/token" - "reflect" - "strconv" - "testing" -) - -var fset = token.NewFileSet() - -func parse(t *testing.T, name, in string) *ast.File { - file, err := parser.ParseFile(fset, name, in, parser.ParseComments) - if err != nil { - t.Fatalf("%s parse: %v", name, err) - } - return file -} - -func print(t *testing.T, name string, f *ast.File) string { - var buf bytes.Buffer - if err := format.Node(&buf, fset, f); err != nil { - t.Fatalf("%s gofmt: %v", name, err) - } - return string(buf.Bytes()) -} - -type test struct { - name string - renamedPkg string - pkg string - in string - out string - broken bool // known broken -} - -var addTests = []test{ - { - name: "leave os alone", - pkg: "os", - in: `package main - -import ( - "os" -) -`, - out: `package main - -import ( - "os" -) -`, - }, - { - name: "import.1", - pkg: "os", - in: `package main -`, - out: `package main - -import "os" -`, - }, - { - name: "import.2", - pkg: "os", - in: `package main - -// Comment -import "C" -`, - out: `package main - -// Comment -import "C" -import "os" -`, - }, - { - name: "import.3", - pkg: "os", - in: `package main - -// Comment -import "C" - -import ( - "io" - "utf8" -) -`, - out: `package main - -// Comment -import "C" - -import ( - "io" - "os" - "utf8" -) -`, - }, - { - name: "import.17", - pkg: "x/y/z", - in: `package main - -// Comment -import "C" - -import ( - "a" - "b" - - "x/w" - - "d/f" -) -`, - out: `package main - -// Comment -import "C" - -import ( - "a" - "b" - - "x/w" - "x/y/z" - - "d/f" -) -`, - }, - { - name: "import into singular group", - pkg: "bytes", - in: `package main - -import "os" - -`, - out: `package main - -import ( - "bytes" - "os" -) -`, - }, - { - name: "import into singular group with comment", - pkg: "bytes", - in: `package main - -import /* why */ /* comment here? */ "os" - -`, - out: `package main - -import /* why */ /* comment here? */ ( - "bytes" - "os" -) -`, - }, - { - name: "import into group with leading comment", - pkg: "strings", - in: `package main - -import ( - // comment before bytes - "bytes" - "os" -) - -`, - out: `package main - -import ( - // comment before bytes - "bytes" - "os" - "strings" -) -`, - }, - { - name: "", - renamedPkg: "fmtpkg", - pkg: "fmt", - in: `package main - -import "os" - -`, - out: `package main - -import ( - fmtpkg "fmt" - "os" -) -`, - }, - { - name: "struct comment", - pkg: "time", - in: `package main - -// This is a comment before a struct. -type T struct { - t time.Time -} -`, - out: `package main - -import "time" - -// This is a comment before a struct. -type T struct { - t time.Time -} -`, - }, - { - name: "issue 8729 import C", - pkg: "time", - in: `package main - -import "C" - -// comment -type T time.Time -`, - out: `package main - -import "C" -import "time" - -// comment -type T time.Time -`, - }, - { - name: "issue 8729 empty import", - pkg: "time", - in: `package main - -import () - -// comment -type T time.Time -`, - out: `package main - -import "time" - -// comment -type T time.Time -`, - }, - { - name: "issue 8729 comment on package line", - pkg: "time", - in: `package main // comment - -type T time.Time -`, - out: `package main // comment -import "time" - -type T time.Time -`, - }, - { - name: "issue 8729 comment after package", - pkg: "time", - in: `package main -// comment - -type T time.Time -`, - out: `package main - -import "time" - -// comment - -type T time.Time -`, - }, - { - name: "issue 8729 comment before and on package line", - pkg: "time", - in: `// comment before -package main // comment on - -type T time.Time -`, - out: `// comment before -package main // comment on -import "time" - -type T time.Time -`, - }, - - // Issue 9961: Match prefixes using path segments rather than bytes - { - name: "issue 9961", - pkg: "regexp", - in: `package main - -import ( - "flag" - "testing" - - "rsc.io/p" -) -`, - out: `package main - -import ( - "flag" - "regexp" - "testing" - - "rsc.io/p" -) -`, - }, -} - -func TestAddImport(t *testing.T) { - for _, test := range addTests { - file := parse(t, test.name, test.in) - var before bytes.Buffer - ast.Fprint(&before, fset, file, nil) - AddNamedImport(fset, file, test.renamedPkg, test.pkg) - if got := print(t, test.name, file); got != test.out { - if test.broken { - t.Logf("%s is known broken:\ngot: %s\nwant: %s", test.name, got, test.out) - } else { - t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out) - } - var after bytes.Buffer - ast.Fprint(&after, fset, file, nil) - - t.Logf("AST before:\n%s\nAST after:\n%s\n", before.String(), after.String()) - } - } -} - -func TestDoubleAddImport(t *testing.T) { - file := parse(t, "doubleimport", "package main\n") - AddImport(fset, file, "os") - AddImport(fset, file, "bytes") - want := `package main - -import ( - "bytes" - "os" -) -` - if got := print(t, "doubleimport", file); got != want { - t.Errorf("got: %s\nwant: %s", got, want) - } -} - -func TestDoubleAddNamedImport(t *testing.T) { - file := parse(t, "doublenamedimport", "package main\n") - AddNamedImport(fset, file, "o", "os") - AddNamedImport(fset, file, "i", "io") - want := `package main - -import ( - i "io" - o "os" -) -` - if got := print(t, "doublenamedimport", file); got != want { - t.Errorf("got: %s\nwant: %s", got, want) - } -} - -// Part of issue 8729. -func TestDoubleAddImportWithDeclComment(t *testing.T) { - file := parse(t, "doubleimport", `package main - -import ( -) - -// comment -type I int -`) - // The AddImport order here matters. - AddImport(fset, file, "golang.org/x/tools/go/ast/astutil") - AddImport(fset, file, "os") - want := `package main - -import ( - "golang.org/x/tools/go/ast/astutil" - "os" -) - -// comment -type I int -` - if got := print(t, "doubleimport_with_decl_comment", file); got != want { - t.Errorf("got: %s\nwant: %s", got, want) - } -} - -var deleteTests = []test{ - { - name: "import.4", - pkg: "os", - in: `package main - -import ( - "os" -) -`, - out: `package main -`, - }, - { - name: "import.5", - pkg: "os", - in: `package main - -// Comment -import "C" -import "os" -`, - out: `package main - -// Comment -import "C" -`, - }, - { - name: "import.6", - pkg: "os", - in: `package main - -// Comment -import "C" - -import ( - "io" - "os" - "utf8" -) -`, - out: `package main - -// Comment -import "C" - -import ( - "io" - "utf8" -) -`, - }, - { - name: "import.7", - pkg: "io", - in: `package main - -import ( - "io" // a - "os" // b - "utf8" // c -) -`, - out: `package main - -import ( - // a - "os" // b - "utf8" // c -) -`, - }, - { - name: "import.8", - pkg: "os", - in: `package main - -import ( - "io" // a - "os" // b - "utf8" // c -) -`, - out: `package main - -import ( - "io" // a - // b - "utf8" // c -) -`, - }, - { - name: "import.9", - pkg: "utf8", - in: `package main - -import ( - "io" // a - "os" // b - "utf8" // c -) -`, - out: `package main - -import ( - "io" // a - "os" // b - // c -) -`, - }, - { - name: "import.10", - pkg: "io", - in: `package main - -import ( - "io" - "os" - "utf8" -) -`, - out: `package main - -import ( - "os" - "utf8" -) -`, - }, - { - name: "import.11", - pkg: "os", - in: `package main - -import ( - "io" - "os" - "utf8" -) -`, - out: `package main - -import ( - "io" - "utf8" -) -`, - }, - { - name: "import.12", - pkg: "utf8", - in: `package main - -import ( - "io" - "os" - "utf8" -) -`, - out: `package main - -import ( - "io" - "os" -) -`, - }, - { - name: "handle.raw.quote.imports", - pkg: "os", - in: "package main\n\nimport `os`", - out: `package main -`, - }, - { - name: "import.13", - pkg: "io", - in: `package main - -import ( - "fmt" - - "io" - "os" - "utf8" - - "go/format" -) -`, - out: `package main - -import ( - "fmt" - - "os" - "utf8" - - "go/format" -) -`, - }, - { - name: "import.14", - pkg: "io", - in: `package main - -import ( - "fmt" // a - - "io" // b - "os" // c - "utf8" // d - - "go/format" // e -) -`, - out: `package main - -import ( - "fmt" // a - - // b - "os" // c - "utf8" // d - - "go/format" // e -) -`, - }, - { - name: "import.15", - pkg: "double", - in: `package main - -import ( - "double" - "double" -) -`, - out: `package main -`, - }, - { - name: "import.16", - pkg: "bubble", - in: `package main - -import ( - "toil" - "bubble" - "bubble" - "trouble" -) -`, - out: `package main - -import ( - "toil" - "trouble" -) -`, - }, - { - name: "import.17", - pkg: "quad", - in: `package main - -import ( - "quad" - "quad" -) - -import ( - "quad" - "quad" -) -`, - out: `package main -`, - }, -} - -func TestDeleteImport(t *testing.T) { - for _, test := range deleteTests { - file := parse(t, test.name, test.in) - DeleteImport(fset, file, test.pkg) - if got := print(t, test.name, file); got != test.out { - t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out) - } - } -} - -type rewriteTest struct { - name string - srcPkg string - dstPkg string - in string - out string -} - -var rewriteTests = []rewriteTest{ - { - name: "import.13", - srcPkg: "utf8", - dstPkg: "encoding/utf8", - in: `package main - -import ( - "io" - "os" - "utf8" // thanks ken -) -`, - out: `package main - -import ( - "encoding/utf8" // thanks ken - "io" - "os" -) -`, - }, - { - name: "import.14", - srcPkg: "asn1", - dstPkg: "encoding/asn1", - in: `package main - -import ( - "asn1" - "crypto" - "crypto/rsa" - _ "crypto/sha1" - "crypto/x509" - "crypto/x509/pkix" - "time" -) - -var x = 1 -`, - out: `package main - -import ( - "crypto" - "crypto/rsa" - _ "crypto/sha1" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "time" -) - -var x = 1 -`, - }, - { - name: "import.15", - srcPkg: "url", - dstPkg: "net/url", - in: `package main - -import ( - "bufio" - "net" - "path" - "url" -) - -var x = 1 // comment on x, not on url -`, - out: `package main - -import ( - "bufio" - "net" - "net/url" - "path" -) - -var x = 1 // comment on x, not on url -`, - }, - { - name: "import.16", - srcPkg: "http", - dstPkg: "net/http", - in: `package main - -import ( - "flag" - "http" - "log" - "text/template" -) - -var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 -`, - out: `package main - -import ( - "flag" - "log" - "net/http" - "text/template" -) - -var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 -`, - }, -} - -func TestRewriteImport(t *testing.T) { - for _, test := range rewriteTests { - file := parse(t, test.name, test.in) - RewriteImport(fset, file, test.srcPkg, test.dstPkg) - if got := print(t, test.name, file); got != test.out { - t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out) - } - } -} - -var importsTests = []struct { - name string - in string - want [][]string -}{ - { - name: "no packages", - in: `package foo -`, - want: nil, - }, - { - name: "one group", - in: `package foo - -import ( - "fmt" - "testing" -) -`, - want: [][]string{{"fmt", "testing"}}, - }, - { - name: "four groups", - in: `package foo - -import "C" -import ( - "fmt" - "testing" - - "appengine" - - "myproject/mylib1" - "myproject/mylib2" -) -`, - want: [][]string{ - {"C"}, - {"fmt", "testing"}, - {"appengine"}, - {"myproject/mylib1", "myproject/mylib2"}, - }, - }, - { - name: "multiple factored groups", - in: `package foo - -import ( - "fmt" - "testing" - - "appengine" -) -import ( - "reflect" - - "bytes" -) -`, - want: [][]string{ - {"fmt", "testing"}, - {"appengine"}, - {"reflect"}, - {"bytes"}, - }, - }, -} - -func unquote(s string) string { - res, err := strconv.Unquote(s) - if err != nil { - return "could_not_unquote" - } - return res -} - -func TestImports(t *testing.T) { - fset := token.NewFileSet() - for _, test := range importsTests { - f, err := parser.ParseFile(fset, "test.go", test.in, 0) - if err != nil { - t.Errorf("%s: %v", test.name, err) - continue - } - var got [][]string - for _, group := range Imports(fset, f) { - var b []string - for _, spec := range group { - b = append(b, unquote(spec.Path.Value)) - } - got = append(got, b) - } - if !reflect.DeepEqual(got, test.want) { - t.Errorf("Imports(%s)=%v, want %v", test.name, got, test.want) - } - } -} diff --git a/Godeps/_workspace/src/golang.org/x/tools/imports/fix_test.go b/Godeps/_workspace/src/golang.org/x/tools/imports/fix_test.go deleted file mode 100644 index f087bc70bf5..00000000000 --- a/Godeps/_workspace/src/golang.org/x/tools/imports/fix_test.go +++ /dev/null @@ -1,862 +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 imports - -import ( - "flag" - "go/build" - "io/ioutil" - "os" - "path/filepath" - "sync" - "testing" -) - -var only = flag.String("only", "", "If non-empty, the fix test to run") - -var tests = []struct { - name string - in, out string -}{ - // Adding an import to an existing parenthesized import - { - name: "factored_imports_add", - in: `package foo -import ( - "fmt" -) -func bar() { -var b bytes.Buffer -fmt.Println(b.String()) -} -`, - out: `package foo - -import ( - "bytes" - "fmt" -) - -func bar() { - var b bytes.Buffer - fmt.Println(b.String()) -} -`, - }, - - // Adding an import to an existing parenthesized import, - // verifying it goes into the first section. - { - name: "factored_imports_add_first_sec", - in: `package foo -import ( - "fmt" - - "appengine" -) -func bar() { -var b bytes.Buffer -_ = appengine.IsDevServer -fmt.Println(b.String()) -} -`, - out: `package foo - -import ( - "bytes" - "fmt" - - "appengine" -) - -func bar() { - var b bytes.Buffer - _ = appengine.IsDevServer - fmt.Println(b.String()) -} -`, - }, - - // Adding an import to an existing parenthesized import, - // verifying it goes into the first section. (test 2) - { - name: "factored_imports_add_first_sec_2", - in: `package foo -import ( - "fmt" - - "appengine" -) -func bar() { -_ = math.NaN -_ = fmt.Sprintf -_ = appengine.IsDevServer -} -`, - out: `package foo - -import ( - "fmt" - "math" - - "appengine" -) - -func bar() { - _ = math.NaN - _ = fmt.Sprintf - _ = appengine.IsDevServer -} -`, - }, - - // Adding a new import line, without parens - { - name: "add_import_section", - in: `package foo -func bar() { -var b bytes.Buffer -} -`, - out: `package foo - -import "bytes" - -func bar() { - var b bytes.Buffer -} -`, - }, - - // Adding two new imports, which should make a parenthesized import decl. - { - name: "add_import_paren_section", - in: `package foo -func bar() { -_, _ := bytes.Buffer, zip.NewReader -} -`, - out: `package foo - -import ( - "archive/zip" - "bytes" -) - -func bar() { - _, _ := bytes.Buffer, zip.NewReader -} -`, - }, - - // Make sure we don't add things twice - { - name: "no_double_add", - in: `package foo -func bar() { -_, _ := bytes.Buffer, bytes.NewReader -} -`, - out: `package foo - -import "bytes" - -func bar() { - _, _ := bytes.Buffer, bytes.NewReader -} -`, - }, - - // Remove unused imports, 1 of a factored block - { - name: "remove_unused_1_of_2", - in: `package foo -import ( -"bytes" -"fmt" -) - -func bar() { -_, _ := bytes.Buffer, bytes.NewReader -} -`, - out: `package foo - -import "bytes" - -func bar() { - _, _ := bytes.Buffer, bytes.NewReader -} -`, - }, - - // Remove unused imports, 2 of 2 - { - name: "remove_unused_2_of_2", - in: `package foo -import ( -"bytes" -"fmt" -) - -func bar() { -} -`, - out: `package foo - -func bar() { -} -`, - }, - - // Remove unused imports, 1 of 1 - { - name: "remove_unused_1_of_1", - in: `package foo - -import "fmt" - -func bar() { -} -`, - out: `package foo - -func bar() { -} -`, - }, - - // Don't remove empty imports. - { - name: "dont_remove_empty_imports", - in: `package foo -import ( -_ "image/png" -_ "image/jpeg" -) -`, - out: `package foo - -import ( - _ "image/jpeg" - _ "image/png" -) -`, - }, - - // Don't remove dot imports. - { - name: "dont_remove_dot_imports", - in: `package foo -import ( -. "foo" -. "bar" -) -`, - out: `package foo - -import ( - . "bar" - . "foo" -) -`, - }, - - // Skip refs the parser can resolve. - { - name: "skip_resolved_refs", - in: `package foo - -func f() { - type t struct{ Println func(string) } - fmt := t{Println: func(string) {}} - fmt.Println("foo") -} -`, - out: `package foo - -func f() { - type t struct{ Println func(string) } - fmt := t{Println: func(string) {}} - fmt.Println("foo") -} -`, - }, - - // Do not add a package we already have a resolution for. - { - name: "skip_template", - in: `package foo - -import "html/template" - -func f() { t = template.New("sometemplate") } -`, - out: `package foo - -import "html/template" - -func f() { t = template.New("sometemplate") } -`, - }, - - // Don't touch cgo - { - name: "cgo", - in: `package foo - -/* -#include <foo.h> -*/ -import "C" -`, - out: `package foo - -/* -#include <foo.h> -*/ -import "C" -`, - }, - - // Put some things in their own section - { - name: "make_sections", - in: `package foo - -import ( -"os" -) - -func foo () { -_, _ = os.Args, fmt.Println -_, _ = appengine.FooSomething, user.Current -} -`, - out: `package foo - -import ( - "fmt" - "os" - - "appengine" - "appengine/user" -) - -func foo() { - _, _ = os.Args, fmt.Println - _, _ = appengine.FooSomething, user.Current -} -`, - }, - - // Delete existing empty import block - { - name: "delete_empty_import_block", - in: `package foo - -import () -`, - out: `package foo -`, - }, - - // Use existing empty import block - { - name: "use_empty_import_block", - in: `package foo - -import () - -func f() { - _ = fmt.Println -} -`, - out: `package foo - -import "fmt" - -func f() { - _ = fmt.Println -} -`, - }, - - // Blank line before adding new section. - { - name: "blank_line_before_new_group", - in: `package foo - -import ( - "fmt" - "net" -) - -func f() { - _ = net.Dial - _ = fmt.Printf - _ = snappy.Foo -} -`, - out: `package foo - -import ( - "fmt" - "net" - - "code.google.com/p/snappy-go/snappy" -) - -func f() { - _ = net.Dial - _ = fmt.Printf - _ = snappy.Foo -} -`, - }, - - // Blank line between standard library and third-party stuff. - { - name: "blank_line_separating_std_and_third_party", - in: `package foo - -import ( - "code.google.com/p/snappy-go/snappy" - "fmt" - "net" -) - -func f() { - _ = net.Dial - _ = fmt.Printf - _ = snappy.Foo -} -`, - out: `package foo - -import ( - "fmt" - "net" - - "code.google.com/p/snappy-go/snappy" -) - -func f() { - _ = net.Dial - _ = fmt.Printf - _ = snappy.Foo -} -`, - }, - - // golang.org/issue/6884 - { - name: "issue 6884", - in: `package main - -// A comment -func main() { - fmt.Println("Hello, world") -} -`, - out: `package main - -import "fmt" - -// A comment -func main() { - fmt.Println("Hello, world") -} -`, - }, - - // golang.org/issue/7132 - { - name: "issue 7132", - in: `package main - -import ( -"fmt" - -"gu" -"github.com/foo/bar" -) - -var ( -a = bar.a -b = gu.a -c = fmt.Printf -) -`, - out: `package main - -import ( - "fmt" - - "gu" - - "github.com/foo/bar" -) - -var ( - a = bar.a - b = gu.a - c = fmt.Printf -) -`, - }, - - { - name: "renamed package", - in: `package main - -var _ = str.HasPrefix -`, - out: `package main - -import str "strings" - -var _ = str.HasPrefix -`, - }, - - { - name: "fragment with main", - in: `func main(){fmt.Println("Hello, world")}`, - out: `package main - -import "fmt" - -func main() { fmt.Println("Hello, world") } -`, - }, - - { - name: "fragment without main", - in: `func notmain(){fmt.Println("Hello, world")}`, - out: `import "fmt" - -func notmain() { fmt.Println("Hello, world") }`, - }, - - // Remove first import within in a 2nd/3rd/4th/etc. section. - // golang.org/issue/7679 - { - name: "issue 7679", - in: `package main - -import ( - "fmt" - - "github.com/foo/bar" - "github.com/foo/qux" -) - -func main() { - var _ = fmt.Println - //var _ = bar.A - var _ = qux.B -} -`, - out: `package main - -import ( - "fmt" - - "github.com/foo/qux" -) - -func main() { - var _ = fmt.Println - //var _ = bar.A - var _ = qux.B -} -`, - }, - - // Blank line can be added before all types of import declarations. - // golang.org/issue/7866 - { - name: "issue 7866", - in: `package main - -import ( - "fmt" - renamed_bar "github.com/foo/bar" - - . "github.com/foo/baz" - "io" - - _ "github.com/foo/qux" - "strings" -) - -func main() { - _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_bar.A, B -} -`, - out: `package main - -import ( - "fmt" - - renamed_bar "github.com/foo/bar" - - "io" - - . "github.com/foo/baz" - - "strings" - - _ "github.com/foo/qux" -) - -func main() { - _, _, _, _, _ = fmt.Errorf, io.Copy, strings.Contains, renamed_bar.A, B -} -`, - }, - - // Non-idempotent comment formatting - // golang.org/issue/8035 - { - name: "issue 8035", - in: `package main - -import ( - "fmt" // A - "go/ast" // B - _ "launchpad.net/gocheck" // C -) - -func main() { _, _ = fmt.Print, ast.Walk } -`, - out: `package main - -import ( - "fmt" // A - "go/ast" // B - - _ "launchpad.net/gocheck" // C -) - -func main() { _, _ = fmt.Print, ast.Walk } -`, - }, - - // Failure to delete all duplicate imports - // golang.org/issue/8459 - { - name: "issue 8459", - in: `package main - -import ( - "fmt" - "log" - "log" - "math" -) - -func main() { fmt.Println("pi:", math.Pi) } -`, - out: `package main - -import ( - "fmt" - "math" -) - -func main() { fmt.Println("pi:", math.Pi) } -`, - }, - - // Too aggressive prefix matching - // golang.org/issue/9961 - { - name: "issue 9961", - in: `package p - -import ( - "zip" - - "rsc.io/p" -) - -var ( - _ = fmt.Print - _ = zip.Store - _ p.P - _ = regexp.Compile -) -`, - out: `package p - -import ( - "fmt" - "regexp" - "zip" - - "rsc.io/p" -) - -var ( - _ = fmt.Print - _ = zip.Store - _ p.P - _ = regexp.Compile -) -`, - }, - - // Unused named import is mistaken for unnamed import - // golang.org/issue/8149 - { - name: "issue 8149", - in: `package main - -import foo "fmt" - -func main() { fmt.Println() } -`, - out: `package main - -import "fmt" - -func main() { fmt.Println() } -`, - }, -} - -func TestFixImports(t *testing.T) { - simplePkgs := map[string]string{ - "appengine": "appengine", - "bytes": "bytes", - "fmt": "fmt", - "math": "math", - "os": "os", - "p": "rsc.io/p", - "regexp": "regexp", - "snappy": "code.google.com/p/snappy-go/snappy", - "str": "strings", - "user": "appengine/user", - "zip": "archive/zip", - } - findImport = func(pkgName string, symbols map[string]bool) (string, bool, error) { - return simplePkgs[pkgName], pkgName == "str", nil - } - - options := &Options{ - TabWidth: 8, - TabIndent: true, - Comments: true, - Fragment: true, - } - - for _, tt := range tests { - if *only != "" && tt.name != *only { - continue - } - buf, err := Process(tt.name+".go", []byte(tt.in), options) - if err != nil { - t.Errorf("error on %q: %v", tt.name, err) - continue - } - if got := string(buf); got != tt.out { - t.Errorf("results diff on %q\nGOT:\n%s\nWANT:\n%s\n", tt.name, got, tt.out) - } - } -} - -func TestFindImportGoPath(t *testing.T) { - goroot, err := ioutil.TempDir("", "goimports-") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(goroot) - - pkgIndexOnce = sync.Once{} - - origStdlib := stdlib - defer func() { - stdlib = origStdlib - }() - stdlib = nil - - // Test against imaginary bits/bytes package in std lib - bytesDir := filepath.Join(goroot, "src", "pkg", "bits", "bytes") - for _, tag := range build.Default.ReleaseTags { - // Go 1.4 rearranged the GOROOT tree to remove the "pkg" path component. - if tag == "go1.4" { - bytesDir = filepath.Join(goroot, "src", "bits", "bytes") - } - } - if err := os.MkdirAll(bytesDir, 0755); err != nil { - t.Fatal(err) - } - bytesSrcPath := filepath.Join(bytesDir, "bytes.go") - bytesPkgPath := "bits/bytes" - bytesSrc := []byte(`package bytes - -type Buffer2 struct {} -`) - if err := ioutil.WriteFile(bytesSrcPath, bytesSrc, 0775); err != nil { - t.Fatal(err) - } - oldGOROOT := build.Default.GOROOT - oldGOPATH := build.Default.GOPATH - build.Default.GOROOT = goroot - build.Default.GOPATH = "" - defer func() { - build.Default.GOROOT = oldGOROOT - build.Default.GOPATH = oldGOPATH - }() - - got, rename, err := findImportGoPath("bytes", map[string]bool{"Buffer2": true}) - if err != nil { - t.Fatal(err) - } - if got != bytesPkgPath || rename { - t.Errorf(`findImportGoPath("bytes", Buffer2 ...)=%q, %t, want "%s", false`, got, rename, bytesPkgPath) - } - - got, rename, err = findImportGoPath("bytes", map[string]bool{"Missing": true}) - if err != nil { - t.Fatal(err) - } - if got != "" || rename { - t.Errorf(`findImportGoPath("bytes", Missing ...)=%q, %t, want "", false`, got, rename) - } -} - -func TestFindImportStdlib(t *testing.T) { - tests := []struct { - pkg string - symbols []string - want string - }{ - {"http", []string{"Get"}, "net/http"}, - {"http", []string{"Get", "Post"}, "net/http"}, - {"http", []string{"Get", "Foo"}, ""}, - {"bytes", []string{"Buffer"}, "bytes"}, - {"ioutil", []string{"Discard"}, "io/ioutil"}, - } - for _, tt := range tests { - got, rename, ok := findImportStdlib(tt.pkg, strSet(tt.symbols)) - if (got != "") != ok { - t.Error("findImportStdlib return value inconsistent") - } - if got != tt.want || rename { - t.Errorf("findImportStdlib(%q, %q) = %q, %t; want %q, false", tt.pkg, tt.symbols, got, rename, tt.want) - } - } -} - -func strSet(ss []string) map[string]bool { - m := make(map[string]bool) - for _, s := range ss { - m[s] = true - } - return m -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go deleted file mode 100644 index c4989f70a5b..00000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi_test.go +++ /dev/null @@ -1,598 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package googleapi - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "testing" - "time" - - "golang.org/x/net/context" -) - -type SetOpaqueTest struct { - in *url.URL - wantRequestURI string -} - -var setOpaqueTests = []SetOpaqueTest{ - // no path - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - }, - "http://www.golang.org", - }, - // path - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - }, - "http://www.golang.org/", - }, - // file with hex escaping - { - &url.URL{ - Scheme: "https", - Host: "www.golang.org", - Path: "/file%20one&two", - }, - "https://www.golang.org/file%20one&two", - }, - // query - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - RawQuery: "q=go+language", - }, - "http://www.golang.org/?q=go+language", - }, - // file with hex escaping in path plus query - { - &url.URL{ - Scheme: "https", - Host: "www.golang.org", - Path: "/file%20one&two", - RawQuery: "q=go+language", - }, - "https://www.golang.org/file%20one&two?q=go+language", - }, - // query with hex escaping - { - &url.URL{ - Scheme: "http", - Host: "www.golang.org", - Path: "/", - RawQuery: "q=go%20language", - }, - "http://www.golang.org/?q=go%20language", - }, -} - -// prefixTmpl is a template for the expected prefix of the output of writing -// an HTTP request. -const prefixTmpl = "GET %v HTTP/1.1\r\nHost: %v\r\n" - -func TestSetOpaque(t *testing.T) { - for _, test := range setOpaqueTests { - u := *test.in - SetOpaque(&u) - - w := &bytes.Buffer{} - r := &http.Request{URL: &u} - if err := r.Write(w); err != nil { - t.Errorf("write request: %v", err) - continue - } - - prefix := fmt.Sprintf(prefixTmpl, test.wantRequestURI, test.in.Host) - if got := string(w.Bytes()); !strings.HasPrefix(got, prefix) { - t.Errorf("got %q expected prefix %q", got, prefix) - } - } -} - -type ExpandTest struct { - in string - expansions map[string]string - want string -} - -var expandTests = []ExpandTest{ - // no expansions - { - "http://www.golang.org/", - map[string]string{}, - "http://www.golang.org/", - }, - // one expansion, no escaping - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red", - }, - "http://www.golang.org/red/delete", - }, - // one expansion, with hex escapes - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red/blue", - }, - "http://www.golang.org/red%2Fblue/delete", - }, - // one expansion, with space - { - "http://www.golang.org/{bucket}/delete", - map[string]string{ - "bucket": "red or blue", - }, - "http://www.golang.org/red%20or%20blue/delete", - }, - // expansion not found - { - "http://www.golang.org/{object}/delete", - map[string]string{ - "bucket": "red or blue", - }, - "http://www.golang.org//delete", - }, - // multiple expansions - { - "http://www.golang.org/{one}/{two}/{three}/get", - map[string]string{ - "one": "ONE", - "two": "TWO", - "three": "THREE", - }, - "http://www.golang.org/ONE/TWO/THREE/get", - }, - // utf-8 characters - { - "http://www.golang.org/{bucket}/get", - map[string]string{ - "bucket": "£100", - }, - "http://www.golang.org/%C2%A3100/get", - }, - // punctuations - { - "http://www.golang.org/{bucket}/get", - map[string]string{ - "bucket": `/\@:,.`, - }, - "http://www.golang.org/%2F%5C%40%3A%2C./get", - }, - // mis-matched brackets - { - "http://www.golang.org/{bucket/get", - map[string]string{ - "bucket": "red", - }, - "http://www.golang.org/{bucket/get", - }, - // "+" prefix for suppressing escape - // See also: http://tools.ietf.org/html/rfc6570#section-3.2.3 - { - "http://www.golang.org/{+topic}", - map[string]string{ - "topic": "/topics/myproject/mytopic", - }, - // The double slashes here look weird, but it's intentional - "http://www.golang.org//topics/myproject/mytopic", - }, -} - -func TestExpand(t *testing.T) { - for i, test := range expandTests { - u := url.URL{ - Path: test.in, - } - Expand(&u, test.expansions) - got := u.Path - if got != test.want { - t.Errorf("got %q expected %q in test %d", got, test.want, i+1) - } - } -} - -type CheckResponseTest struct { - in *http.Response - bodyText string - want error - errText string -} - -var checkResponseTests = []CheckResponseTest{ - { - &http.Response{ - StatusCode: http.StatusOK, - }, - "", - nil, - "", - }, - { - &http.Response{ - StatusCode: http.StatusInternalServerError, - }, - `{"error":{}}`, - &Error{ - Code: http.StatusInternalServerError, - Body: `{"error":{}}`, - }, - `googleapi: got HTTP response code 500 with body: {"error":{}}`, - }, - { - &http.Response{ - StatusCode: http.StatusNotFound, - }, - `{"error":{"message":"Error message for StatusNotFound."}}`, - &Error{ - Code: http.StatusNotFound, - Message: "Error message for StatusNotFound.", - Body: `{"error":{"message":"Error message for StatusNotFound."}}`, - }, - "googleapi: Error 404: Error message for StatusNotFound.", - }, - { - &http.Response{ - StatusCode: http.StatusBadRequest, - }, - `{"error":"invalid_token","error_description":"Invalid Value"}`, - &Error{ - Code: http.StatusBadRequest, - Body: `{"error":"invalid_token","error_description":"Invalid Value"}`, - }, - `googleapi: got HTTP response code 400 with body: {"error":"invalid_token","error_description":"Invalid Value"}`, - }, - { - &http.Response{ - StatusCode: http.StatusBadRequest, - }, - `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`, - &Error{ - Code: http.StatusBadRequest, - Errors: []ErrorItem{ - { - Reason: "keyInvalid", - Message: "Bad Request", - }, - }, - Body: `{"error":{"errors":[{"domain":"usageLimits","reason":"keyInvalid","message":"Bad Request"}],"code":400,"message":"Bad Request"}}`, - Message: "Bad Request", - }, - "googleapi: Error 400: Bad Request, keyInvalid", - }, -} - -func TestCheckResponse(t *testing.T) { - for _, test := range checkResponseTests { - res := test.in - if test.bodyText != "" { - res.Body = ioutil.NopCloser(strings.NewReader(test.bodyText)) - } - g := CheckResponse(res) - if !reflect.DeepEqual(g, test.want) { - t.Errorf("CheckResponse: got %v, want %v", g, test.want) - gotJson, err := json.Marshal(g) - if err != nil { - t.Error(err) - } - wantJson, err := json.Marshal(test.want) - if err != nil { - t.Error(err) - } - t.Errorf("json(got): %q\njson(want): %q", string(gotJson), string(wantJson)) - } - if g != nil && g.Error() != test.errText { - t.Errorf("CheckResponse: unexpected error message.\nGot: %q\nwant: %q", g, test.errText) - } - } -} - -type VariantPoint struct { - Type string - Coordinates []float64 -} - -type VariantTest struct { - in map[string]interface{} - result bool - want VariantPoint -} - -var coords = []interface{}{1.0, 2.0} - -var variantTests = []VariantTest{ - { - in: map[string]interface{}{ - "type": "Point", - "coordinates": coords, - }, - result: true, - want: VariantPoint{ - Type: "Point", - Coordinates: []float64{1.0, 2.0}, - }, - }, - { - in: map[string]interface{}{ - "type": "Point", - "bogus": coords, - }, - result: true, - want: VariantPoint{ - Type: "Point", - }, - }, -} - -func TestVariantType(t *testing.T) { - for _, test := range variantTests { - if g := VariantType(test.in); g != test.want.Type { - t.Errorf("VariantType(%v): got %v, want %v", test.in, g, test.want.Type) - } - } -} - -func TestConvertVariant(t *testing.T) { - for _, test := range variantTests { - g := VariantPoint{} - r := ConvertVariant(test.in, &g) - if r != test.result { - t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, r, test.result) - } - if !reflect.DeepEqual(g, test.want) { - t.Errorf("ConvertVariant(%v): got %v, want %v", test.in, g, test.want) - } - } -} - -type unexpectedReader struct{} - -func (unexpectedReader) Read([]byte) (int, error) { - return 0, fmt.Errorf("unexpected read in test.") -} - -var contentRangeRE = regexp.MustCompile(`^bytes (\d+)\-(\d+)/(\d+)$`) - -func (t *testTransport) RoundTrip(req *http.Request) (*http.Response, error) { - t.req = req - if rng := req.Header.Get("Content-Range"); rng != "" && !strings.HasPrefix(rng, "bytes */") { // Read the data - m := contentRangeRE.FindStringSubmatch(rng) - if len(m) != 4 { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - start, err := strconv.ParseInt(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - end, err := strconv.ParseInt(m[2], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - totalSize, err := strconv.ParseInt(m[3], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - partialSize := end - start + 1 - t.buf, err = ioutil.ReadAll(req.Body) - if err != nil || int64(len(t.buf)) != partialSize { - return nil, fmt.Errorf("unable to read %v bytes from request data, n=%v: %v", partialSize, len(t.buf), err) - } - if totalSize == end+1 { - t.statusCode = 200 // signify completion of transfer - } - } - f := ioutil.NopCloser(unexpectedReader{}) - res := &http.Response{ - Body: f, - StatusCode: t.statusCode, - Header: http.Header{}, - } - if t.rangeVal != "" { - res.Header.Set("Range", t.rangeVal) - } - return res, nil -} - -type testTransport struct { - req *http.Request - statusCode int - rangeVal string - want int64 - buf []byte -} - -var statusTests = []*testTransport{ - &testTransport{statusCode: 308, want: 0}, - &testTransport{statusCode: 308, rangeVal: "bytes=0-0", want: 1}, - &testTransport{statusCode: 308, rangeVal: "bytes=0-42", want: 43}, -} - -func TestTransferStatus(t *testing.T) { - for _, tr := range statusTests { - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - } - g, _, err := rx.transferStatus() - if err != nil { - t.Error(err) - } - if g != tr.want { - t.Errorf("transferStatus got %v, want %v", g, tr.want) - } - } -} - -func (t *interruptedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - t.req = req - if rng := req.Header.Get("Content-Range"); rng != "" && !strings.HasPrefix(rng, "bytes */") { - t.interruptCount += 1 - if t.interruptCount%7 == 0 { // Respond with a "service unavailable" error - res := &http.Response{ - StatusCode: http.StatusServiceUnavailable, - Header: http.Header{}, - } - t.rangeVal = fmt.Sprintf("bytes=0-%v", len(t.buf)-1) // Set the response for next time - return res, nil - } - m := contentRangeRE.FindStringSubmatch(rng) - if len(m) != 4 { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - start, err := strconv.ParseInt(m[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - end, err := strconv.ParseInt(m[2], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - totalSize, err := strconv.ParseInt(m[3], 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse content range: %v", rng) - } - partialSize := end - start + 1 - buf, err := ioutil.ReadAll(req.Body) - if err != nil || int64(len(buf)) != partialSize { - return nil, fmt.Errorf("unable to read %v bytes from request data, n=%v: %v", partialSize, len(buf), err) - } - t.buf = append(t.buf, buf...) - if totalSize == end+1 { - t.statusCode = 200 // signify completion of transfer - } - } - f := ioutil.NopCloser(unexpectedReader{}) - res := &http.Response{ - Body: f, - StatusCode: t.statusCode, - Header: http.Header{}, - } - if t.rangeVal != "" { - res.Header.Set("Range", t.rangeVal) - } - return res, nil -} - -type interruptedTransport struct { - req *http.Request - statusCode int - rangeVal string - interruptCount int - buf []byte - progressBuf string -} - -func (tr *interruptedTransport) ProgressUpdate(current, total int64) { - tr.progressBuf += fmt.Sprintf("%v, %v\n", current, total) -} - -func TestInterruptedTransferChunks(t *testing.T) { - f, err := os.Open("googleapi.go") - if err != nil { - t.Fatalf("unable to open googleapi.go: %v", err) - } - defer f.Close() - slurp, err := ioutil.ReadAll(f) - if err != nil { - t.Fatalf("unable to slurp file: %v", err) - } - st, err := f.Stat() - if err != nil { - t.Fatalf("unable to stat googleapi.go: %v", err) - } - tr := &interruptedTransport{ - statusCode: 308, - buf: make([]byte, 0, st.Size()), - } - oldChunkSize := chunkSize - defer func() { chunkSize = oldChunkSize }() - chunkSize = 100 // override to process small chunks for test. - - sleep = func(time.Duration) {} // override time.Sleep - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - Media: f, - MediaType: "text/plain", - ContentLength: st.Size(), - Callback: tr.ProgressUpdate, - } - res, err := rx.Upload(context.Background()) - if err != nil || res == nil || res.StatusCode != http.StatusOK { - if res == nil { - t.Errorf("transferChunks not successful, res=nil: %v", err) - } else { - t.Errorf("transferChunks not successful, statusCode=%v: %v", res.StatusCode, err) - } - } - if len(tr.buf) != len(slurp) || bytes.Compare(tr.buf, slurp) != 0 { - t.Errorf("transfered file corrupted:\ngot %s\nwant %s", tr.buf, slurp) - } - w := "" - for i := chunkSize; i <= st.Size(); i += chunkSize { - w += fmt.Sprintf("%v, %v\n", i, st.Size()) - } - if st.Size()%chunkSize != 0 { - w += fmt.Sprintf("%v, %v\n", st.Size(), st.Size()) - } - if tr.progressBuf != w { - t.Errorf("progress update error, got %v, want %v", tr.progressBuf, w) - } -} - -func TestCancelUpload(t *testing.T) { - f, err := os.Open("googleapi.go") - if err != nil { - t.Fatalf("unable to open googleapi.go: %v", err) - } - defer f.Close() - st, err := f.Stat() - if err != nil { - t.Fatalf("unable to stat googleapi.go: %v", err) - } - tr := &interruptedTransport{ - statusCode: 308, - buf: make([]byte, 0, st.Size()), - } - oldChunkSize := chunkSize - defer func() { chunkSize = oldChunkSize }() - chunkSize = 100 // override to process small chunks for test. - - sleep = func(time.Duration) {} // override time.Sleep - rx := &ResumableUpload{ - Client: &http.Client{Transport: tr}, - Media: f, - MediaType: "text/plain", - ContentLength: st.Size(), - Callback: tr.ProgressUpdate, - } - ctx, cancelFunc := context.WithCancel(context.Background()) - cancelFunc() // stop the upload that hasn't started yet - res, err := rx.Upload(ctx) - if err == nil || res == nil || res.StatusCode != http.StatusRequestTimeout { - if res == nil { - t.Errorf("transferChunks not successful, got res=nil, err=%v, want StatusRequestTimeout", err) - } else { - t.Errorf("transferChunks not successful, got statusCode=%v, err=%v, want StatusRequestTimeout", res.StatusCode, err) - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go deleted file mode 100644 index a6b2045156e..00000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/types_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package googleapi - -import ( - "encoding/json" - "reflect" - "testing" -) - -func TestTypes(t *testing.T) { - type T struct { - I32 Int32s - I64 Int64s - U32 Uint32s - U64 Uint64s - F64 Float64s - } - v := &T{ - I32: Int32s{-1, 2, 3}, - I64: Int64s{-1, 2, 1 << 33}, - U32: Uint32s{1, 2}, - U64: Uint64s{1, 2, 1 << 33}, - F64: Float64s{1.5, 3.33}, - } - got, err := json.Marshal(v) - if err != nil { - t.Fatal(err) - } - want := `{"I32":["-1","2","3"],"I64":["-1","2","8589934592"],"U32":["1","2"],"U64":["1","2","8589934592"],"F64":["1.5","3.33"]}` - if string(got) != want { - t.Fatalf("Marshal mismatch.\n got: %s\nwant: %s\n", got, want) - } - - v2 := new(T) - if err := json.Unmarshal(got, v2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(v, v2) { - t.Fatalf("Unmarshal didn't produce same results.\n got: %#v\nwant: %#v\n", v, v2) - } -} diff --git a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/example_test.go b/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/example_test.go deleted file mode 100644 index bf689fd9dd0..00000000000 --- a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/example_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package lumberjack_test - -import ( - "log" - - "gopkg.in/natefinch/lumberjack.v2" -) - -// To use lumberjack with the standard library's log package, just pass it into -// the SetOutput function when your application starts. -func Example() { - log.SetOutput(&lumberjack.Logger{ - Filename: "/var/log/myapp/foo.log", - MaxSize: 500, // megabytes - MaxBackups: 3, - MaxAge: 28, // days - }) -} diff --git a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/linux_test.go b/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/linux_test.go deleted file mode 100644 index 40f3446685c..00000000000 --- a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/linux_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// +build linux - -package lumberjack - -import ( - "os" - "syscall" - "testing" -) - -func TestMaintainMode(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestMaintainMode", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - mode := os.FileMode(0770) - f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, mode) - isNil(err, t) - f.Close() - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - filename2 := backupFile(dir) - info, err := os.Stat(filename) - isNil(err, t) - info2, err := os.Stat(filename2) - isNil(err, t) - equals(mode, info.Mode(), t) - equals(mode, info2.Mode(), t) -} - -func TestMaintainOwner(t *testing.T) { - fakeC := fakeChown{} - os_Chown = fakeC.Set - os_Stat = fakeStat - defer func() { - os_Chown = os.Chown - os_Stat = os.Stat - }() - currentTime = fakeTime - dir := makeTempDir("TestMaintainOwner", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - equals(555, fakeC.uid, t) - equals(666, fakeC.gid, t) -} - -type fakeChown struct { - name string - uid int - gid int -} - -func (f *fakeChown) Set(name string, uid, gid int) error { - f.name = name - f.uid = uid - f.gid = gid - return nil -} - -func fakeStat(name string) (os.FileInfo, error) { - info, err := os.Stat(name) - if err != nil { - return info, err - } - stat := info.Sys().(*syscall.Stat_t) - stat.Uid = 555 - stat.Gid = 666 - return info, nil -} diff --git a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/lumberjack_test.go b/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/lumberjack_test.go deleted file mode 100644 index c11dc1872ff..00000000000 --- a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/lumberjack_test.go +++ /dev/null @@ -1,690 +0,0 @@ -package lumberjack - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "testing" - "time" - - "github.com/BurntSushi/toml" - "gopkg.in/yaml.v1" -) - -// !!!NOTE!!! -// -// Running these tests in parallel will almost certainly cause sporadic (or even -// regular) failures, because they're all messing with the same global variable -// that controls the logic's mocked time.Now. So... don't do that. - -// Since all the tests uses the time to determine filenames etc, we need to -// control the wall clock as much as possible, which means having a wall clock -// that doesn't change unless we want it to. -var fakeCurrentTime = time.Now() - -func fakeTime() time.Time { - return fakeCurrentTime -} - -func TestNewFile(t *testing.T) { - currentTime = fakeTime - - dir := makeTempDir("TestNewFile", t) - defer os.RemoveAll(dir) - l := &Logger{ - Filename: logFile(dir), - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - existsWithLen(logFile(dir), n, t) - fileCount(dir, 1, t) -} - -func TestOpenExisting(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestOpenExisting", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - data := []byte("foo!") - err := ioutil.WriteFile(filename, data, 0644) - isNil(err, t) - existsWithLen(filename, len(data), t) - - l := &Logger{ - Filename: filename, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - // make sure the file got appended - existsWithLen(filename, len(data)+n, t) - - // make sure no other files were created - fileCount(dir, 1, t) -} - -func TestWriteTooLong(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestWriteTooLong", t) - defer os.RemoveAll(dir) - l := &Logger{ - Filename: logFile(dir), - MaxSize: 5, - } - defer l.Close() - b := []byte("booooooooooooooo!") - n, err := l.Write(b) - notNil(err, t) - equals(0, n, t) - equals(err.Error(), - fmt.Sprintf("write length %d exceeds maximum file size %d", len(b), l.MaxSize), t) - _, err = os.Stat(logFile(dir)) - assert(os.IsNotExist(err), t, "File exists, but should not have been created") -} - -func TestMakeLogDir(t *testing.T) { - currentTime = fakeTime - dir := time.Now().Format("TestMakeLogDir" + backupTimeFormat) - dir = filepath.Join(os.TempDir(), dir) - defer os.RemoveAll(dir) - filename := logFile(dir) - l := &Logger{ - Filename: filename, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - existsWithLen(logFile(dir), n, t) - fileCount(dir, 1, t) -} - -func TestDefaultFilename(t *testing.T) { - currentTime = fakeTime - dir := os.TempDir() - filename := filepath.Join(dir, filepath.Base(os.Args[0])+"-lumberjack.log") - defer os.Remove(filename) - l := &Logger{} - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - - isNil(err, t) - equals(len(b), n, t) - existsWithLen(filename, n, t) -} - -func TestAutoRotate(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestAutoRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // the old logfile should be moved aside and the main logfile should have - // only the last write in it. - existsWithLen(filename, n, t) - - // the backup file will use the current fake time and have the old contents. - existsWithLen(backupFile(dir), len(b), t) - - fileCount(dir, 2, t) -} - -func TestFirstWriteRotate(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestFirstWriteRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - } - defer l.Close() - - start := []byte("boooooo!") - err := ioutil.WriteFile(filename, start, 0600) - isNil(err, t) - - newFakeTime() - - // this would make us rotate - b := []byte("fooo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - existsWithLen(backupFile(dir), len(start), t) - - fileCount(dir, 2, t) -} - -func TestMaxBackups(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - dir := makeTempDir("TestMaxBackups", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - MaxBackups: 1, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - // this will put us over the max - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - secondFilename := backupFile(dir) - existsWithLen(secondFilename, len(b), t) - - // make sure the old file still exists with the same size. - existsWithLen(filename, n, t) - - fileCount(dir, 2, t) - - newFakeTime() - - // this will make us rotate again - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - thirdFilename := backupFile(dir) - existsWithLen(thirdFilename, len(b2), t) - - existsWithLen(filename, n, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(time.Millisecond * 10) - - // should only have two files in the dir still - fileCount(dir, 2, t) - - // second file name should still exist - existsWithLen(thirdFilename, len(b2), t) - - // should have deleted the first backup - notExist(secondFilename, t) - - // now test that we don't delete directories or non-logfile files - - newFakeTime() - - // create a file that is close to but different from the logfile name. - // It shouldn't get caught by our deletion filters. - notlogfile := logFile(dir) + ".foo" - err = ioutil.WriteFile(notlogfile, []byte("data"), 0644) - isNil(err, t) - - // Make a directory that exactly matches our log file filters... it still - // shouldn't get caught by the deletion filter since it's a directory. - notlogfiledir := backupFile(dir) - err = os.Mkdir(notlogfiledir, 0700) - isNil(err, t) - - newFakeTime() - - // this will make us rotate again - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - fourthFilename := backupFile(dir) - existsWithLen(fourthFilename, len(b2), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(time.Millisecond * 10) - - // We should have four things in the directory now - the 2 log files, the - // not log file, and the directory - fileCount(dir, 4, t) - - // third file name should still exist - existsWithLen(filename, n, t) - - existsWithLen(fourthFilename, len(b2), t) - - // should have deleted the first filename - notExist(thirdFilename, t) - - // the not-a-logfile should still exist - exists(notlogfile, t) - - // the directory - exists(notlogfiledir, t) -} - -func TestCleanupExistingBackups(t *testing.T) { - // test that if we start with more backup files than we're supposed to have - // in total, that extra ones get cleaned up when we rotate. - - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestCleanupExistingBackups", t) - defer os.RemoveAll(dir) - - // make 3 backup files - - data := []byte("data") - backup := backupFile(dir) - err := ioutil.WriteFile(backup, data, 0644) - isNil(err, t) - - newFakeTime() - - backup = backupFile(dir) - err = ioutil.WriteFile(backup, data, 0644) - isNil(err, t) - - newFakeTime() - - backup = backupFile(dir) - err = ioutil.WriteFile(backup, data, 0644) - isNil(err, t) - - // now create a primary log file with some data - filename := logFile(dir) - err = ioutil.WriteFile(filename, data, 0644) - isNil(err, t) - - l := &Logger{ - Filename: filename, - MaxSize: 10, - MaxBackups: 1, - } - defer l.Close() - - newFakeTime() - - b2 := []byte("foooooo!") - n, err := l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(time.Millisecond * 10) - - // now we should only have 2 files left - the primary and one backup - fileCount(dir, 2, t) -} - -func TestMaxAge(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestMaxAge", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - l := &Logger{ - Filename: filename, - MaxSize: 10, - MaxAge: 1, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - // two days later - newFakeTime() - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - existsWithLen(backupFile(dir), len(b), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - // We should still have 2 log files, since the most recent backup was just - // created. - fileCount(dir, 2, t) - - existsWithLen(filename, len(b2), t) - - // we should have deleted the old file due to being too old - existsWithLen(backupFile(dir), len(b), t) - - // two days later - newFakeTime() - - b3 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b3), n, t) - existsWithLen(backupFile(dir), len(b2), t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - // We should have 2 log files - the main log file, and the most recent - // backup. The earlier backup is past the cutoff and should be gone. - fileCount(dir, 2, t) - - existsWithLen(filename, len(b3), t) - - // we should have deleted the old file due to being too old - existsWithLen(backupFile(dir), len(b2), t) - -} - -func TestOldLogFiles(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestOldLogFiles", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - data := []byte("data") - err := ioutil.WriteFile(filename, data, 07) - isNil(err, t) - - // This gives us a time with the same precision as the time we get from the - // timestamp in the name. - t1, err := time.Parse(backupTimeFormat, fakeTime().UTC().Format(backupTimeFormat)) - isNil(err, t) - - backup := backupFile(dir) - err = ioutil.WriteFile(backup, data, 07) - isNil(err, t) - - newFakeTime() - - t2, err := time.Parse(backupTimeFormat, fakeTime().UTC().Format(backupTimeFormat)) - isNil(err, t) - - backup2 := backupFile(dir) - err = ioutil.WriteFile(backup2, data, 07) - isNil(err, t) - - l := &Logger{Filename: filename} - files, err := l.oldLogFiles() - isNil(err, t) - equals(2, len(files), t) - - // should be sorted by newest file first, which would be t2 - equals(t2, files[0].timestamp, t) - equals(t1, files[1].timestamp, t) -} - -func TestTimeFromName(t *testing.T) { - l := &Logger{Filename: "/var/log/myfoo/foo.log"} - prefix, ext := l.prefixAndExt() - val := l.timeFromName("foo-2014-05-04T14-44-33.555.log", prefix, ext) - equals("2014-05-04T14-44-33.555", val, t) - - val = l.timeFromName("foo-2014-05-04T14-44-33.555", prefix, ext) - equals("", val, t) - - val = l.timeFromName("2014-05-04T14-44-33.555.log", prefix, ext) - equals("", val, t) - - val = l.timeFromName("foo.log", prefix, ext) - equals("", val, t) -} - -func TestLocalTime(t *testing.T) { - currentTime = fakeTime - megabyte = 1 - - dir := makeTempDir("TestLocalTime", t) - defer os.RemoveAll(dir) - - l := &Logger{ - Filename: logFile(dir), - MaxSize: 10, - LocalTime: true, - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - b2 := []byte("fooooooo!") - n2, err := l.Write(b2) - isNil(err, t) - equals(len(b2), n2, t) - - existsWithLen(logFile(dir), n2, t) - existsWithLen(backupFileLocal(dir), n, t) -} - -func TestRotate(t *testing.T) { - currentTime = fakeTime - dir := makeTempDir("TestRotate", t) - defer os.RemoveAll(dir) - - filename := logFile(dir) - - l := &Logger{ - Filename: filename, - MaxBackups: 1, - MaxSize: 100, // megabytes - } - defer l.Close() - b := []byte("boo!") - n, err := l.Write(b) - isNil(err, t) - equals(len(b), n, t) - - existsWithLen(filename, n, t) - fileCount(dir, 1, t) - - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - filename2 := backupFile(dir) - existsWithLen(filename2, n, t) - existsWithLen(filename, 0, t) - fileCount(dir, 2, t) - newFakeTime() - - err = l.Rotate() - isNil(err, t) - - // we need to wait a little bit since the files get deleted on a different - // goroutine. - <-time.After(10 * time.Millisecond) - - filename3 := backupFile(dir) - existsWithLen(filename3, 0, t) - existsWithLen(filename, 0, t) - fileCount(dir, 2, t) - - b2 := []byte("foooooo!") - n, err = l.Write(b2) - isNil(err, t) - equals(len(b2), n, t) - - // this will use the new fake time - existsWithLen(filename, n, t) -} - -func TestJson(t *testing.T) { - data := []byte(` -{ - "filename": "foo", - "maxsize": 5, - "maxage": 10, - "maxbackups": 3, - "localtime": true -}`[1:]) - - l := Logger{} - err := json.Unmarshal(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) -} - -func TestYaml(t *testing.T) { - data := []byte(` -filename: foo -maxsize: 5 -maxage: 10 -maxbackups: 3 -localtime: true`[1:]) - - l := Logger{} - err := yaml.Unmarshal(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) -} - -func TestToml(t *testing.T) { - data := ` -filename = "foo" -maxsize = 5 -maxage = 10 -maxbackups = 3 -localtime = true`[1:] - - l := Logger{} - md, err := toml.Decode(data, &l) - isNil(err, t) - equals("foo", l.Filename, t) - equals(5, l.MaxSize, t) - equals(10, l.MaxAge, t) - equals(3, l.MaxBackups, t) - equals(true, l.LocalTime, t) - equals(0, len(md.Undecoded()), t) -} - -// makeTempDir creates a file with a semi-unique name in the OS temp directory. -// It should be based on the name of the test, to keep parallel tests from -// colliding, and must be cleaned up after the test is finished. -func makeTempDir(name string, t testing.TB) string { - dir := time.Now().Format(name + backupTimeFormat) - dir = filepath.Join(os.TempDir(), dir) - isNilUp(os.Mkdir(dir, 0777), t, 1) - return dir -} - -// existsWithLen checks that the given file exists and has the correct length. -func existsWithLen(path string, length int, t testing.TB) { - info, err := os.Stat(path) - isNilUp(err, t, 1) - equalsUp(int64(length), info.Size(), t, 1) -} - -// logFile returns the log file name in the given directory for the current fake -// time. -func logFile(dir string) string { - return filepath.Join(dir, "foobar.log") -} - -func backupFile(dir string) string { - return filepath.Join(dir, "foobar-"+fakeTime().UTC().Format(backupTimeFormat)+".log") -} - -func backupFileLocal(dir string) string { - return filepath.Join(dir, "foobar-"+fakeTime().Format(backupTimeFormat)+".log") -} - -// logFileLocal returns the log file name in the given directory for the current -// fake time using the local timezone. -func logFileLocal(dir string) string { - return filepath.Join(dir, fakeTime().Format(backupTimeFormat)) -} - -// fileCount checks that the number of files in the directory is exp. -func fileCount(dir string, exp int, t testing.TB) { - files, err := ioutil.ReadDir(dir) - isNilUp(err, t, 1) - // Make sure no other files were created. - equalsUp(exp, len(files), t, 1) -} - -// newFakeTime sets the fake "current time" to two days later. -func newFakeTime() { - fakeCurrentTime = fakeCurrentTime.Add(time.Hour * 24 * 2) -} - -func notExist(path string, t testing.TB) { - _, err := os.Stat(path) - assertUp(os.IsNotExist(err), t, 1, "expected to get os.IsNotExist, but instead got %v", err) -} - -func exists(path string, t testing.TB) { - _, err := os.Stat(path) - assertUp(err == nil, t, 1, "expected file to exist, but got error from os.Stat: %v", err) -} diff --git a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/rotate_test.go b/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/rotate_test.go deleted file mode 100644 index 0561464ac0d..00000000000 --- a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/rotate_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build linux - -package lumberjack_test - -import ( - "log" - "os" - "os/signal" - "syscall" - - "github.com/natefinch/lumberjack" -) - -// Example of how to rotate in response to SIGHUP. -func ExampleLogger_Rotate() { - l := &lumberjack.Logger{} - log.SetOutput(l) - c := make(chan os.Signal, 1) - signal.Notify(c, syscall.SIGHUP) - - go func() { - for { - <-c - l.Rotate() - } - }() -} diff --git a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/testing_test.go b/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/testing_test.go deleted file mode 100644 index 8e89c083198..00000000000 --- a/Godeps/_workspace/src/gopkg.in/natefinch/lumberjack.v2/testing_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package lumberjack - -import ( - "fmt" - "path/filepath" - "reflect" - "runtime" - "testing" -) - -// assert will log the given message if condition is false. -func assert(condition bool, t testing.TB, msg string, v ...interface{}) { - assertUp(condition, t, 1, msg, v...) -} - -// assertUp is like assert, but used inside helper functions, to ensure that -// the file and line number reported by failures corresponds to one or more -// levels up the stack. -func assertUp(condition bool, t testing.TB, caller int, msg string, v ...interface{}) { - if !condition { - _, file, line, _ := runtime.Caller(caller + 1) - v = append([]interface{}{filepath.Base(file), line}, v...) - fmt.Printf("%s:%d: "+msg+"\n", v...) - t.FailNow() - } -} - -// equals tests that the two values are equal according to reflect.DeepEqual. -func equals(exp, act interface{}, t testing.TB) { - equalsUp(exp, act, t, 1) -} - -// equalsUp is like equals, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func equalsUp(exp, act interface{}, t testing.TB, caller int) { - if !reflect.DeepEqual(exp, act) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: exp: %v (%T), got: %v (%T)\n", - filepath.Base(file), line, exp, exp, act, act) - t.FailNow() - } -} - -// isNil reports a failure if the given value is not nil. Note that values -// which cannot be nil will always fail this check. -func isNil(obtained interface{}, t testing.TB) { - isNilUp(obtained, t, 1) -} - -// isNilUp is like isNil, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func isNilUp(obtained interface{}, t testing.TB, caller int) { - if !_isNil(obtained) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: expected nil, got: %v\n", filepath.Base(file), line, obtained) - t.FailNow() - } -} - -// notNil reports a failure if the given value is nil. -func notNil(obtained interface{}, t testing.TB) { - notNilUp(obtained, t, 1) -} - -// notNilUp is like notNil, but used inside helper functions, to ensure that the -// file and line number reported by failures corresponds to one or more levels -// up the stack. -func notNilUp(obtained interface{}, t testing.TB, caller int) { - if _isNil(obtained) { - _, file, line, _ := runtime.Caller(caller + 1) - fmt.Printf("%s:%d: expected non-nil, got: %v\n", filepath.Base(file), line, obtained) - t.FailNow() - } -} - -// _isNil is a helper function for isNil and notNil, and should not be used -// directly. -func _isNil(obtained interface{}) bool { - if obtained == nil { - return true - } - - switch v := reflect.ValueOf(obtained); v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - - return false -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go deleted file mode 100644 index 90ffcc01749..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/decode_test.go +++ /dev/null @@ -1,902 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: <foo>", - map[string]string{"a": "<foo>"}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for _, item := range unmarshalTests { - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go deleted file mode 100644 index cdbf64a9d6a..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/encode_test.go +++ /dev/null @@ -1,434 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X int } "a,omitempty" - B int "b,omitempty" - }{nil, 0}, - "{}\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": "<foo>"}, - "a: <foo>\n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, -} - -func (s *S) TestMarshal(c *C) { - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go b/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go deleted file mode 100644 index c5cf1ed4f6e..00000000000 --- a/Godeps/_workspace/src/gopkg.in/yaml.v2/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/benchmark_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/benchmark_test.go deleted file mode 100644 index 27071da0e8a..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/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/speter.net/go/exp/math/dec/inf/dec_go1_2_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_go1_2_test.go deleted file mode 100644 index 5df0f7b5537..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/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/speter.net/go/exp/math/dec/inf/dec_internal_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_internal_test.go deleted file mode 100644 index d4fbe3e5bcd..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/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/speter.net/go/exp/math/dec/inf/dec_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_test.go deleted file mode 100644 index 01ac7710cba..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/dec_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package inf_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "math/big" - "strings" - "testing" - - "speter.net/go/exp/math/dec/inf" -) - -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/speter.net/go/exp/math/dec/inf/example_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/example_test.go deleted file mode 100644 index 52029e08dcd..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/example_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package inf_test - -import ( - "fmt" - "log" -) - -import "speter.net/go/exp/math/dec/inf" - -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: <nil> -} diff --git a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_example_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_example_test.go deleted file mode 100644 index 5c5e4df9755..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_example_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package inf_test - -import ( - "fmt" - "os" - "text/tabwriter" - - "speter.net/go/exp/math/dec/inf" -) - -// 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 <nil> - // -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 <nil> - // -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 <nil> - // -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 <nil> - // -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 <nil> - // -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 <nil> - // 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 <nil> - // 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 <nil> - // 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 <nil> - // 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 <nil> - // 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 <nil> - // 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 <nil> - -} diff --git a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_test.go b/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_test.go deleted file mode 100644 index 757ab9756bc..00000000000 --- a/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf/rounder_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package inf_test - -import ( - "math/big" - "testing" - - "speter.net/go/exp/math/dec/inf" -) - -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]) - } - } - } -} diff --git a/hack/verify-godeps.sh b/hack/verify-godeps.sh index 0787e49bf3b..b98897c3d36 100755 --- a/hack/verify-godeps.sh +++ b/hack/verify-godeps.sh @@ -80,7 +80,7 @@ pushd "${_kubetmp}" > /dev/null git init > /dev/null 2>&1 # recreate the Godeps using the nice clean set we just downloaded - "${GODEP}" save -t ./... + "${GODEP}" save ./... popd > /dev/null if ! _out="$(diff -Naupr --ignore-matching-lines='^\s*\"GoVersion\":' --ignore-matching-lines='^\s*\"Comment\":' ${KUBE_ROOT}/Godeps/Godeps.json ${_kubetmp}/Godeps/Godeps.json)"; then