From 28a05123e57f9b7d98b9f99632b79f674dde37d1 Mon Sep 17 00:00:00 2001 From: hello2mao Date: Fri, 28 Dec 2018 11:32:23 +0800 Subject: [PATCH] rm file and modify ip --- docs/controllers/service/README.md | 10 +- .../examples/http-with-loadBalancerIP.yml | 2 +- ...-cloud-controller-manager-systemd-manifest | 2 +- .../cce-kube-apiserver-systemd-manifest | 10 +- ...e-kube-controller-manager-systemd-manifest | 6 +- .../cce-kubelet-systemd-manifest | 8 +- docs/tutorial.md | 4 +- pkg/sdk/bcc/cds_test.go | 116 -- pkg/sdk/bcc/client_test.go | 116 -- pkg/sdk/bcc/instance_test.go | 59 - pkg/sdk/bce/aksk.json | 5 - pkg/sdk/bce/core_test.go | 761 -------- pkg/sdk/bce/error_test.go | 78 - pkg/sdk/bce/request_test.go | 227 --- pkg/sdk/bce/response_test.go | 52 - pkg/sdk/blb/backendserver_test.go | 84 - pkg/sdk/blb/client_test.go | 382 ---- pkg/sdk/blb/listener_test.go | 130 -- pkg/sdk/blb/loadbalancer_test.go | 75 - pkg/sdk/bos/bucket_test.go | 295 --- pkg/sdk/bos/client_test.go | 1705 ----------------- pkg/sdk/cce/client_test.go | 157 -- pkg/sdk/cce/cluster_test.go | 85 - pkg/sdk/clientset/clientset_test.go | 47 - pkg/sdk/eip/client_test.go | 165 -- pkg/sdk/eip/eip_test.go | 93 - pkg/sdk/util/mime_types_test.go | 51 - pkg/sdk/util/util_test.go | 752 -------- 28 files changed, 21 insertions(+), 5456 deletions(-) delete mode 100644 pkg/sdk/bcc/cds_test.go delete mode 100644 pkg/sdk/bcc/client_test.go delete mode 100644 pkg/sdk/bcc/instance_test.go delete mode 100644 pkg/sdk/bce/aksk.json delete mode 100644 pkg/sdk/bce/core_test.go delete mode 100644 pkg/sdk/bce/error_test.go delete mode 100644 pkg/sdk/bce/request_test.go delete mode 100644 pkg/sdk/bce/response_test.go delete mode 100644 pkg/sdk/blb/backendserver_test.go delete mode 100644 pkg/sdk/blb/client_test.go delete mode 100644 pkg/sdk/blb/listener_test.go delete mode 100644 pkg/sdk/blb/loadbalancer_test.go delete mode 100644 pkg/sdk/bos/bucket_test.go delete mode 100644 pkg/sdk/bos/client_test.go delete mode 100644 pkg/sdk/cce/client_test.go delete mode 100644 pkg/sdk/cce/cluster_test.go delete mode 100644 pkg/sdk/clientset/clientset_test.go delete mode 100644 pkg/sdk/eip/client_test.go delete mode 100644 pkg/sdk/eip/eip_test.go delete mode 100644 pkg/sdk/util/mime_types_test.go delete mode 100644 pkg/sdk/util/util_test.go diff --git a/docs/controllers/service/README.md b/docs/controllers/service/README.md index 1f4d54a..bd8d337 100644 --- a/docs/controllers/service/README.md +++ b/docs/controllers/service/README.md @@ -13,9 +13,9 @@ Get more info about Service: ``` kubectl get svc nginx-service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE -nginx-service LoadBalancer 172.18.127.136 180.76.177.103 80:30601/TCP 1m +nginx-service LoadBalancer 1.1.1.1 8.8.8.8 80:30601/TCP 1m ``` -So, the EIP is `180.76.177.103` +So, the EIP is `8.8.8.8` ## HTTP loadbalancer with loadBalancerIP If loadBalancerIP is specified, the load-balancer will be created with the user-specified loadBalancerIP: @@ -28,7 +28,7 @@ Get more info about Service: ``` kubectl get svc nginx-service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE -nginx-service LoadBalancer 172.18.127.136 178.11.24.19 80:30601/TCP 1m +nginx-service LoadBalancer 1.1.1.1 8.8.8.8 80:30601/TCP 1m ``` As you can see, the EXTERNAL-IP is the user-specified loadBalancerIP. @@ -44,6 +44,6 @@ Get more info about Service: ``` kubectl get svc nginx-service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE -nginx-service LoadBalancer 172.18.127.136 192.168.9.222 80:30601/TCP 1m +nginx-service LoadBalancer 1.1.1.1 2.2.2.2 80:30601/TCP 1m ``` -As you can see, the EXTERNAL-IP `192.168.9.222` can only be accessed inside the VPC. +As you can see, the EXTERNAL-IP `2.2.2.2` can only be accessed inside the VPC. diff --git a/docs/controllers/service/examples/http-with-loadBalancerIP.yml b/docs/controllers/service/examples/http-with-loadBalancerIP.yml index 6eb2b17..8b3cbc7 100644 --- a/docs/controllers/service/examples/http-with-loadBalancerIP.yml +++ b/docs/controllers/service/examples/http-with-loadBalancerIP.yml @@ -25,7 +25,7 @@ spec: app: nginx type: LoadBalancer # here set your own EIP - loadBalancerIP: 178.11.24.19 + loadBalancerIP: 8.8.8.8 ports: - name: http port: 80 diff --git a/docs/example-manifests/cce-cloud-controller-manager-systemd-manifest b/docs/example-manifests/cce-cloud-controller-manager-systemd-manifest index 5cd7a39..9684fbe 100644 --- a/docs/example-manifests/cce-cloud-controller-manager-systemd-manifest +++ b/docs/example-manifests/cce-cloud-controller-manager-systemd-manifest @@ -7,7 +7,7 @@ ExecStart=/opt/kube/bin/kube-cloud-controller-manager \ --allocate-node-cidrs=true \ --cloud-config=/etc/kubernetes/cloud.config \ --cloud-provider=cce \ ---cluster-cidr=172.29.0.0/16 \ +--cluster-cidr=172.0.0.1/16 \ --cluster-name=kubernetes \ --kubeconfig=/root/.kube/config \ --leader-elect=true \ diff --git a/docs/example-manifests/cce-kube-apiserver-systemd-manifest b/docs/example-manifests/cce-kube-apiserver-systemd-manifest index 519e0b7..16988d6 100644 --- a/docs/example-manifests/cce-kube-apiserver-systemd-manifest +++ b/docs/example-manifests/cce-kube-apiserver-systemd-manifest @@ -6,27 +6,27 @@ After=etcd.service [Service] ExecStart=/opt/kube/bin/kube-apiserver \ --admission-control=NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota,DefaultTolerationSeconds,PodPreset,Initializers \ ---advertise-address=100.0.0.59 \ +--advertise-address=127.0.0.1 \ --allow-privileged=true \ --apiserver-count=3 \ --authorization-mode=RBAC,Node \ ---bind-address=100.0.0.59 \ +--bind-address=127.0.0.1 \ --client-ca-file=/etc/kubernetes/pki/ca.pem \ --cloud-config=/etc/kubernetes/cloud.config \ --enable-swagger-ui=true \ --etcd-cafile=/etc/etcd/ssl/ca.pem \ --etcd-certfile=/etc/etcd/ssl/etcd.pem \ --etcd-keyfile=/etc/etcd/ssl/etcd-key.pem \ ---etcd-servers=https://100.0.0.58:2379,https://100.0.0.60:2379,https://100.0.0.59:2379 \ +--etcd-servers=https://127.0.0.1:2379,https://127.0.0.1:2379,https://127.0.0.1:2379 \ --enable-bootstrap-token-auth=true \ ---external-hostname=100.0.0.59 \ +--external-hostname=127.0.0.1 \ --feature-gates=DevicePlugins=true,RotateKubeletServerCertificate=true,MountPropagation=true,CSIPersistentVolume=true \ --insecure-port=0 \ --logtostderr=true \ --runtime-config=settings.k8s.io/v1alpha1=true,admissionregistration.k8s.io/v1alpha1=true,storage.k8s.io/v1alpha1=true \ --secure-port=6443 \ --service-account-key-file=/etc/kubernetes/pki/ca-key.pem \ ---service-cluster-ip-range=172.16.0.0/16 \ +--service-cluster-ip-range=127.0.0.1/16 \ --storage-backend=etcd3 \ --tls-cert-file=/etc/kubernetes/pki/apiserver.pem \ --tls-private-key-file=/etc/kubernetes/pki/apiserver-key.pem \ diff --git a/docs/example-manifests/cce-kube-controller-manager-systemd-manifest b/docs/example-manifests/cce-kube-controller-manager-systemd-manifest index 046d344..bca9137 100644 --- a/docs/example-manifests/cce-kube-controller-manager-systemd-manifest +++ b/docs/example-manifests/cce-kube-controller-manager-systemd-manifest @@ -7,7 +7,7 @@ After=kube-apiserver.service ExecStart=/opt/kube/bin/kube-controller-manager \ --allocate-node-cidrs=true \ --cloud-config=/etc/kubernetes/cloud.config \ ---cluster-cidr=172.29.0.0/16 \ +--cluster-cidr=172.1.0.1/16 \ --cluster-name=kubernetes \ --cluster-signing-cert-file=/etc/kubernetes/pki/ca.pem \ --cluster-signing-key-file=/etc/kubernetes/pki/ca-key.pem \ @@ -17,11 +17,11 @@ ExecStart=/opt/kube/bin/kube-controller-manager \ --kubeconfig=/etc/kubernetes/controller-manager.conf \ --leader-elect=true \ --logtostderr=true \ ---master=https://100.0.0.59:6443 \ +--master=https://127.0.0.1:6443 \ --root-ca-file=/etc/kubernetes/pki/ca.pem \ --route-reconciliation-period=50s \ --service-account-private-key-file=/etc/kubernetes/pki/ca-key.pem \ ---service-cluster-ip-range=172.16.0.0/16 \ +--service-cluster-ip-range=172.0.0.1/16 \ --use-service-account-credentials=true \ --v=4 Restart=always diff --git a/docs/example-manifests/cce-kubelet-systemd-manifest b/docs/example-manifests/cce-kubelet-systemd-manifest index 234d5e3..29f9101 100644 --- a/docs/example-manifests/cce-kubelet-systemd-manifest +++ b/docs/example-manifests/cce-kubelet-systemd-manifest @@ -5,21 +5,21 @@ Requires=docker.service [Service] ExecStart=/opt/kube/bin/kubelet \ ---address=192.168.3.16 \ +--address=127.0.0.1 \ --allow-privileged=true \ --client-ca-file=/etc/kubernetes/pki/ca.pem \ --cloud-config=/etc/kubernetes/cloud.config \ --cloud-provider=external \ ---cluster-dns=172.16.0.10 \ +--cluster-dns=127.0.0.1 \ --cluster-domain=cluster.local \ --docker-root=/var/lib/docker \ --fail-swap-on=false \ --feature-gates=DevicePlugins=true,RotateKubeletServerCertificate=true,MountPropagation=true,CSIPersistentVolume=true \ ---hostname-override=192.168.3.16 \ +--hostname-override=127.0.0.1 \ --kubeconfig=/etc/kubernetes/kubelet.conf \ --logtostderr=true \ --network-plugin=kubenet \ ---non-masquerade-cidr=172.29.0.0/16 \ +--non-masquerade-cidr=127.0.0.1/16 \ --pod-infra-container-image=hub-readonly.baidubce.com/public/pause:2.0 \ --pod-manifest-path=/etc/kubernetes/manifests \ --anonymous-auth=false \ diff --git a/docs/tutorial.md b/docs/tutorial.md index 97a7c18..4627915 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -55,11 +55,11 @@ IP which you can use to connect to your service. ```bash $ kubectl get svc --watch NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE -nginx-service 10.96.97.137 129.213.12.174 80:30274/TCP 5m +nginx-service 1.1.1.1 8.8.8.8 80:30274/TCP 5m ``` You can now access your service via the provisioned load balancer ```bash -$ curl -i http://129.213.12.174 +$ curl -i http://8.8.8.8 ``` \ No newline at end of file diff --git a/pkg/sdk/bcc/cds_test.go b/pkg/sdk/bcc/cds_test.go deleted file mode 100644 index a5555df..0000000 --- a/pkg/sdk/bcc/cds_test.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bcc - -import ( - "fmt" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestDeleteVolume(t *testing.T) { - // ts := httptest.NewServer(InstancesHandler()) - // defer ts.Close() - // bccClient.SetDebug(true) - // bccClient.Endpoint = ts.URL - err := bccClient.DeleteVolume("v-MK288vVC") - if err != nil { - t.Error(util.FormatTest("DeleteVolume", err.Error(), "nil")) - } -} - -var expectBill = &bce.Billing{ - PaymentTiming: "Postpaid", - BillingMethod: "ByTraffic", -} -var expectCreateVolumeArgs = &CreateVolumeArgs{ - PurchaseCount: 1, - Billing: expectBill, - StorageType: STORAGE_TYPE_STD1, - CdsSizeInGB: 10, -} - -func TestCreateVolumes(t *testing.T) { - // ts := httptest.NewServer(EipHandler()) - // defer ts.Close() - // eipClient.Endpoint = ts.URL - _, err := bccClient.CreateVolumes(expectCreateVolumeArgs) - if err != nil { - t.Error(err) - } -} - -func TestGetVolumeList(t *testing.T) { - // ts := httptest.NewServer(EipHandler()) - // defer ts.Close() - // eipClient.Endpoint = ts.URL - list, err := bccClient.GetVolumeList(nil) - if err != nil { - t.Error(err) - } - for _, v := range list { - fmt.Println(v.Id) - } -} - -func TestDescribeVolume(t *testing.T) { - // ts := httptest.NewServer(InstancesHandler()) - // defer ts.Close() - // bccClient.Endpoint = ts.URL - ins, err := bccClient.DescribeVolume("v-31wjHWIU") - if err != nil { - t.Error(util.FormatTest("TestDescribeVolume", err.Error(), "nil")) - } - fmt.Println(ins.Id) -} - -var expectAttach = &AttachCDSVolumeArgs{ - VolumeId: "v-JCvK3cpI", - InstanceId: "i-NN0KeMyw", -} - -func TestAttachCDSVolume(t *testing.T) { - // ts := httptest.NewServer(EipHandler()) - // defer ts.Close() - // eipClient.Endpoint = ts.URL - bccClient.SetDebug(true) - att, err := bccClient.AttachCDSVolume(expectAttach) - if err != nil { - t.Error(err) - } else { - fmt.Println(att.Device) - } - -} - -func TestDetachCDSVolume(t *testing.T) { - bccClient.SetDebug(true) - err := bccClient.DetachCDSVolume(expectAttach) - if err != nil { - t.Error(err) - } -} - -func TestDeleteCDSVolume(t *testing.T) { - bccClient.SetDebug(true) - err := bccClient.DeleteCDS("v-JCvK3cpI") - if err != nil { - t.Error(err) - } -} diff --git a/pkg/sdk/bcc/client_test.go b/pkg/sdk/bcc/client_test.go deleted file mode 100644 index 4207975..0000000 --- a/pkg/sdk/bcc/client_test.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bcc - -import ( - "fmt" - "net/http" - "os" - "path" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" -) - -var credentials, _ = bce.NewCredentialsFromFile("../aksk-test.json") - -//var bceConfig = bce.NewConfig(credentials) -var bceConfig = &bce.Config{ - Credentials: credentials, - Checksum: true, - Region: os.Getenv("BOS_REGION"), -} -var bccConfig = NewConfig(bceConfig) -var bccClient = NewClient(bccConfig) - -func InstancesHandler() http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("/v2/instance", func(w http.ResponseWriter, r *http.Request) { - handleInstanceList(w, r) - }) - mux.HandleFunc("/v2/instance/", func(w http.ResponseWriter, r *http.Request) { - handleDescribeInstance(w, r) - }) - return mux -} - -func handleInstanceList(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case http.MethodGet: - w.Header().Set("Content-Type", "application/json") - response := `{ - "nextMarker": "i-xktdeMSf", - "marker": "i-IyWRtII7", - "maxKeys": 1, - "isTruncated": true, - "instances": [ - { - "id": "i-IyWRtII7", - "createTime": "2015-08-06T13:23:13Z", - "name": "instance-j93wzbn1", - "status": "Running", - "desc": "console", - "paymentTiming":"Postpaid", - "expireTime": null, - "internalIp": "192.168.6.15", - "publicIp": "-", - "cpuCount": 1, - "memoryCapacityInGB": 1, - "localDiskSizeInGB": 0, - "networkCapacityInMbps": 1, - "imageId": "m-3zfBY1Ku", - "placementPolicy": "default", - "zoneName": "cn-bj-a" - } - ] -}` - fmt.Fprint(w, response) - } -} - -func handleDescribeInstance(w http.ResponseWriter, r *http.Request) { - _, id := path.Split(r.URL.Path) - if id != "i-YufwpQAe" { - return - } - switch r.Method { - case http.MethodGet: - w.Header().Set("Content-Type", "application/json") - response := `{ - "instance": { - "id": "i-YufwpQAe", - "createTime": "2015-07-09T10:27:15Z", - "name": "instance-luz2ef4l-1", - "status": "Stopped", - "desc": "console", - "paymentTiming":"Postpaid", - "expireTime": null, - "internalIp": "192.168.0.25", - "publicIp": "-", - "cpuCount": 1, - "memoryCapacityInGB": 1, - "localDiskSizeInGB": 0, - "networkCapacityInMbps": 5, - "imageId": "m-nky7qeom", - "placementPolicy": "default", - "zoneName": "cn-bj-a", - "subnetId": "sbn-oioiadda", - "vpcId": "vpc-i80sab3o" - } -}` - fmt.Fprint(w, response) - } -} diff --git a/pkg/sdk/bcc/instance_test.go b/pkg/sdk/bcc/instance_test.go deleted file mode 100644 index 122f02d..0000000 --- a/pkg/sdk/bcc/instance_test.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bcc - -import ( - "testing" - - "fmt" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestDescribeInstance(t *testing.T) { - // ts := httptest.NewServer(InstancesHandler()) - // defer ts.Close() - bccClient.SetDebug(true) - // bccClient.Endpoint = ts.URL - // ins, err := bccClient.DescribeInstance("i-YufwpQAe", nil) - ins, err := bccClient.DescribeInstance("i-7VUJvwqR", nil) - if err != nil { - t.Error(util.FormatTest("ListInstances", err.Error(), "nil")) - } - if ins.InstanceName != "instance-luz2ef4l-1" { - t.Error("name error!") - } -} - -func TestListInstances(t *testing.T) { - // ts := httptest.NewServer(InstancesHandler()) - // defer ts.Close() - // bccClient.Endpoint = ts.URL - // bccClient.Endpoint = "bcc.bce-api.baidu.com" - bccClient.SetDebug(true) - list, err := bccClient.ListInstances(nil) - - if err != nil { - t.Error(util.FormatTest("ListInstances", err.Error(), "nil")) - } - for _, ins := range list { - fmt.Println(ins.VpcId) - if ins.InstanceId != "i-IyWRtII7" { - // t.Error("instanceId error") - } - } -} diff --git a/pkg/sdk/bce/aksk.json b/pkg/sdk/bce/aksk.json deleted file mode 100644 index 73f1ec3..0000000 --- a/pkg/sdk/bce/aksk.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "AccessKeyID":"aaa", - "SecretAccessKey":"bbb", - "region":"ccc" -} \ No newline at end of file diff --git a/pkg/sdk/bce/core_test.go b/pkg/sdk/bce/core_test.go deleted file mode 100644 index 3fc9138..0000000 --- a/pkg/sdk/bce/core_test.go +++ /dev/null @@ -1,761 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bce - -import ( - "errors" - "net/http" - "os" - "strconv" - "testing" - "time" - - "fmt" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func getConfig() *Config { - return &Config{ - Credentials: NewCredentials(os.Getenv("BAIDU_BCE_AK"), os.Getenv("BAIDU_BCE_SK")), - Checksum: true, - Region: os.Getenv("BOS_REGION"), - } -} - -var bceClient = NewClient(getConfig()) - -func TestNewConfig(t *testing.T) { - credentials := Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - } - config := NewConfig(&credentials) - - if config == nil { - t.Error(util.FormatTest("NewConfig", "nil", "not nil")) - } -} - -func TestGetRegion(t *testing.T) { - expected := os.Getenv("BOS_REGION") - - if expected == "" { - expected = "bj" - } - - config := &Config{Region: os.Getenv("BOS_REGION")} - region := config.GetRegion() - - if region != expected { - t.Error(util.FormatTest("GetRegion", region, expected)) - } - - expected = "bj" - config = &Config{} - region = config.GetRegion() - - if region != expected { - t.Error(util.FormatTest("GetRegion", region, expected)) - } -} - -func TestGetUserAgent(t *testing.T) { - expected := DefaultUserAgent - config := &Config{} - userAgent := config.GetUserAgent() - - if userAgent != expected { - t.Error(util.FormatTest("GetUserAgent", userAgent, expected)) - } - - expected = "baidubce-sdk-go" - config = &Config{UserAgent: "baidubce-sdk-go"} - userAgent = config.GetUserAgent() - - if userAgent != expected { - t.Error(util.FormatTest("GetUserAgent", userAgent, expected)) - } -} - -func TestGetMaxErrorRetry(t *testing.T) { - expected := 3 - retryPolicy := NewDefaultRetryPolicy(expected, 20*time.Second) - - if retryPolicy.MaxErrorRetry != expected { - t.Error(util.FormatTest("GetMaxErrorRetry", strconv.Itoa(retryPolicy.MaxErrorRetry), strconv.Itoa(expected))) - } -} - -func TestGetMaxDelay(t *testing.T) { - expected := 20 * time.Second - retryPolicy := NewDefaultRetryPolicy(3, expected) - - if retryPolicy.MaxDelay != expected { - t.Error(util.FormatTest("GetMaxDelay", retryPolicy.MaxDelay.String(), expected.String())) - } -} - -func TestGetDelayBeforeNextRetry(t *testing.T) { - maxErrorRetry := 3 - maxDelay := 20 * time.Second - retryPolicy := NewDefaultRetryPolicy(maxErrorRetry, maxDelay) - delay := retryPolicy.GetDelayBeforeNextRetry(errors.New("Unknown Error"), 5) - - if delay != -1 { - t.Error(util.FormatTest("GetDelayBeforeNextRetry", delay.String(), strconv.Itoa(-1))) - } - - delay = retryPolicy.GetDelayBeforeNextRetry(errors.New("Unknown Error"), 1) - - if delay != -1 { - t.Error(util.FormatTest("GetDelayBeforeNextRetry", delay.String(), strconv.Itoa(-1))) - } - delay = retryPolicy.GetDelayBeforeNextRetry(&Error{StatusCode: http.StatusInternalServerError}, 1) - expected := (1 << 1) * 300 * time.Millisecond - - if delay != expected { - t.Error(util.FormatTest("GetDelayBeforeNextRetry", delay.String(), expected.String())) - } - - delay = retryPolicy.GetDelayBeforeNextRetry(&Error{StatusCode: http.StatusServiceUnavailable}, 2) - expected = (1 << 2) * 300 * time.Millisecond - - if delay != expected { - t.Error(util.FormatTest("GetDelayBeforeNextRetry", delay.String(), expected.String())) - } - - maxDelay = 1 * time.Second - retryPolicy = NewDefaultRetryPolicy(maxErrorRetry, maxDelay) - delay = retryPolicy.GetDelayBeforeNextRetry(&Error{StatusCode: http.StatusServiceUnavailable}, 2) - expected = retryPolicy.GetMaxDelay() - - if delay != expected { - t.Error(util.FormatTest("GetDelayBeforeNextRetry", delay.String(), expected.String())) - } -} - -func TestShouldRetry(t *testing.T) { - maxErrorRetry := 3 - maxDelay := 20 * time.Second - retryPolicy := NewDefaultRetryPolicy(maxErrorRetry, maxDelay) - expected := false - unknownError := errors.New("Unknown Error") - shouldRetry := retryPolicy.shouldRetry(unknownError, maxErrorRetry+1) - - if shouldRetry != expected { - t.Error(util.FormatTest("shouldRetry", strconv.FormatBool(shouldRetry), strconv.FormatBool(expected))) - } - - shouldRetry = retryPolicy.shouldRetry(unknownError, maxErrorRetry-1) - - if shouldRetry != expected { - t.Error(util.FormatTest("shouldRetry", strconv.FormatBool(shouldRetry), strconv.FormatBool(expected))) - } - - bceError := &Error{} - shouldRetry = retryPolicy.shouldRetry(bceError, maxErrorRetry-1) - - if shouldRetry != expected { - t.Error(util.FormatTest("shouldRetry", strconv.FormatBool(shouldRetry), strconv.FormatBool(expected))) - } - - expected = true - bceError.StatusCode = http.StatusInternalServerError - shouldRetry = retryPolicy.shouldRetry(bceError, maxErrorRetry-1) - - if shouldRetry != expected { - t.Error(util.FormatTest("shouldRetry", strconv.FormatBool(shouldRetry), strconv.FormatBool(expected))) - } - - bceError.StatusCode = http.StatusServiceUnavailable - shouldRetry = retryPolicy.shouldRetry(bceError, maxErrorRetry-1) - - if shouldRetry != expected { - t.Error(util.FormatTest("shouldRetry", strconv.FormatBool(shouldRetry), strconv.FormatBool(expected))) - } -} - -func TestCheckSignOption(t *testing.T) { - signOption := CheckSignOption(nil) - - if signOption == nil { - t.Error(util.FormatTest("CheckSignOption", "nil", "not nil")) - } - - originSignOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - getHeaders(), - nil, - ) - signOption = CheckSignOption(originSignOption) - - if signOption != originSignOption { - t.Error(util.FormatTest("CheckSignOption", "new signOption", "originSignOption")) - } -} - -func TestAddHeadersToSign(t *testing.T) { - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - nil, - ) - signOption.AddHeadersToSign("content-type", "content-length") - - if len(signOption.HeadersToSign) != 2 { - t.Error(util.FormatTest("AddHeadersToSign", strconv.Itoa(len(signOption.HeadersToSign)), strconv.Itoa(2))) - } - - if signOption.HeadersToSign[0] != "content-type" { - t.Error(util.FormatTest("AddHeadersToSign", signOption.HeadersToSign[0], "content-type")) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - []string{"content-type"}, - ) - signOption.AddHeadersToSign("content-type", "content-length") - - if len(signOption.HeadersToSign) != 2 { - t.Error(util.FormatTest("AddHeadersToSign", strconv.Itoa(len(signOption.HeadersToSign)), strconv.Itoa(2))) - } -} - -func TestAddHeader(t *testing.T) { - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - nil, - ) - signOption.AddHeader("content-type", "text/plain") - signOption.AddHeader("content-length", "1024") - - if len(signOption.Headers) != 2 { - t.Error(util.FormatTest("AddHeader", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(2))) - } - - if signOption.Headers["content-type"] != "text/plain" { - t.Error(util.FormatTest("AddHeader", signOption.Headers["content-type"], "text/plain")) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - map[string]string{"content-type": "text/plain"}, - nil, - ) - originHeaders := signOption.Headers - signOption.AddHeader("content-type", "text/plain") - signOption.AddHeader("content-length", "1024") - - if len(signOption.Headers) != 2 { - t.Error(util.FormatTest("AddHeader", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(2))) - } - - if len(originHeaders) != len(signOption.Headers) { - t.Error(util.FormatTest("AddHeader", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(len(originHeaders)))) - } -} - -func TestAddHeaders(t *testing.T) { - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - nil, - ) - - var headers map[string]string - signOption.AddHeaders(headers) - - if len(signOption.Headers) != len(headers) { - t.Error(util.FormatTest("AddHeaders", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(len(headers)))) - } - - headers = map[string]string{ - "content-type": "text/plain", - "content-length": "1024", - } - signOption.AddHeaders(headers) - - if len(signOption.Headers) != len(headers) { - t.Error(util.FormatTest("AddHeaders", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(len(headers)))) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - map[string]string{"content-type": "text/plain"}, - nil, - ) - signOption.AddHeaders(headers) - - if len(signOption.Headers) != len(headers) { - t.Error(util.FormatTest("AddHeaders", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(len(headers)))) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - map[string]string{"content-encoding": "gzip"}, - nil, - ) - signOption.AddHeaders(headers) - - if len(signOption.Headers) != len(headers)+1 { - t.Error(util.FormatTest("AddHeaders", strconv.Itoa(len(signOption.Headers)), strconv.Itoa(len(headers)+1))) - } -} - -func TestInit(t *testing.T) { - signOption := &SignOption{} - - signOption.init() - - if signOption.initialized != true { - t.Error(util.FormatTest("init", strconv.FormatBool(signOption.initialized), strconv.FormatBool(true))) - } - - timestamp := signOption.Timestamp - - if timestamp == "" { - t.Error(util.FormatTest("init", timestamp, "timestamp string")) - } - - if signOption.ExpirationPeriodInSeconds != ExpirationPeriodInSeconds { - t.Error(util.FormatTest("init", strconv.Itoa(signOption.ExpirationPeriodInSeconds), strconv.Itoa(ExpirationPeriodInSeconds))) - } - - signOption.init() - - if signOption.Timestamp != timestamp { - t.Error(util.FormatTest("init", signOption.Timestamp, timestamp)) - } - - signOption = &SignOption{ - Headers: map[string]string{"content-type": "text/plain"}, - HeadersToSign: []string{"content-type", "date"}, - } - signOption.init() - - if !util.Contains(signOption.HeadersToSign, "host", true) { - t.Error(util.FormatTest("init", "", "host should be specified")) - } - - if !util.MapContains(signOption.Headers, func(key, value string) bool { - return key == "date" - }) { - t.Error(util.FormatTest("init", "", "date should be specified")) - } - - if util.MapContains(signOption.Headers, func(key, value string) bool { - return key == "x-bce-date" - }) { - t.Error(util.FormatTest("init", "x-bce-date", "x-bce-date should be specified")) - } - - signOption = &SignOption{ - Headers: map[string]string{"content-type": "text/plain", "date": "2015-11-16T07:33:15Z"}, - HeadersToSign: []string{"content-type", "date"}, - } - expectedDate := util.TimeStringToRFC1123(signOption.Headers["date"]) - signOption.init() - - if signOption.Headers["date"] != expectedDate { - t.Error(util.FormatTest("init", signOption.Headers["date"], expectedDate)) - } - - signOption = &SignOption{ - Headers: map[string]string{"content-type": "text/plain"}, - HeadersToSign: []string{"content-type"}, - } - signOption.init() - - if util.MapContains(signOption.Headers, func(key, value string) bool { - return key == "date" - }) { - t.Error(util.FormatTest("init", "date", "date should not be specified")) - } - - if !util.MapContains(signOption.Headers, func(key, value string) bool { - return key == "x-bce-date" - }) { - t.Error(util.FormatTest("init", "", "x-bce-date should not be specified")) - } -} - -func TestSignedHeadersToString(t *testing.T) { - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - []string{"date", "content-type", "server", "content-length"}, - ) - result := signOption.signedHeadersToString() - expected := "content-length;content-type;date;server" - - if result != expected { - t.Error(util.FormatTest("signedHeadersToString", result, expected)) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - map[string]string{"content-type": "text/plain", "server": "nginx"}, - []string{"date", "content-type", "server", "content-length"}, - ) - result = signOption.signedHeadersToString() - expected = "content-length;content-type;date;server" - - if result != expected { - t.Error(util.FormatTest("signedHeadersToString", result, expected)) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - map[string]string{"content-type": "text/plain", "server": "nginx", "content-length": "1024"}, - nil, - ) - result = signOption.signedHeadersToString() - expected = "content-length;content-type" - - if result != expected { - t.Error(util.FormatTest("signedHeadersToString", result, expected)) - } -} - -func TestGetSigningKey(t *testing.T) { - const expected = "d9f35aaba8a5f3efa654851917114b6f22cd831116fd7d8431e08af22dcff24c" - credentials := Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - } - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - getHeaders(), - nil, - ) - signingKey := getSigningKey(credentials, signOption) - - if signingKey != expected { - t.Error(util.FormatTest("getSigningKey", signingKey, expected)) - } -} - -func TestSign(t *testing.T) { - expected := "a19e6386e990691aca1114a20357c83713f1cb4be3d74942bb4ed37469ecdacf" - credentials := Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - } - req := getRequest() - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - getHeaders(), - nil, - ) - signature := sign(credentials, *req, signOption) - - if signature != expected { - t.Error(util.FormatTest("sign", signature, expected)) - } -} - -func TestGenerateAuthorization(t *testing.T) { - expected := "bce-auth-v1/0b0f67dfb88244b289b72b142befad0c/2015-04-27T08:23:49Z/1800/content-length;content-md5;" + - "content-type;host;x-bce-date/a19e6386e990691aca1114a20357c83713f1cb4be3d74942bb4ed37469ecdacf" - credentials := Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - } - req := getRequest() - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - getHeaders(), - nil, - ) - authorization := GenerateAuthorization(credentials, *req, signOption) - - if authorization != expected { - t.Error(util.FormatTest("GenerateAuthorization", authorization, expected)) - } - - req = getRequest() - GenerateAuthorization(credentials, *req, nil) -} - -func TestNewHttpClient(t *testing.T) { - credentials := Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - } - config := &Config{ - Credentials: &credentials, - ProxyHost: "guoyao.me", - ProxyPort: 8000, - MaxConnections: 10, - } - - httpClient := newHttpClient(config) - - if httpClient == nil { - t.Error(util.FormatTest("newHttpClient", "nil", "valid http client")) - } -} - -func TestSetDebug(t *testing.T) { - config := getConfig() - client := NewClient(config) - expected := false - - if client.debug != expected { - t.Error(util.FormatTest("SetDebug", strconv.FormatBool(client.debug), strconv.FormatBool(expected))) - } - - expected = true - client.SetDebug(true) - - if client.debug != expected { - t.Error(util.FormatTest("SetDebug", strconv.FormatBool(client.debug), strconv.FormatBool(expected))) - } -} - -func TestGetURL(t *testing.T) { - client := NewClient(&Config{}) - host := "guoyao.me" - uriPath := "articals" - params := map[string]string{"pageNo": "2", "pageSize": "10"} - url := client.GetURL(host, uriPath, params) - expected := "http://guoyao.me/articals?pageNo=2&pageSize=10" - - if url != expected { - t.Error(util.FormatTest("GetURL", url, expected)) - } - - uriPath = "/articals" - url = client.GetURL(host, uriPath, params) - - if url != expected { - t.Error(util.FormatTest("GetURL", url, expected)) - } - - client = NewClient(&Config{APIVersion: "v1"}) - url = client.GetURL(host, uriPath, params) - expected = "http://guoyao.me/v1/articals?pageNo=2&pageSize=10" - - if url != expected { - t.Error(util.FormatTest("GetURL", url, expected)) - } -} - -func TestGetSessionToken(t *testing.T) { - method := "GetSessionToken" - config := getConfig() - - req := SessionTokenRequest{ - DurationSeconds: 600, - Id: "ef5a4b19192f4931adcf0e12f82795e2", - AccessControlList: []AccessControlListItem{ - AccessControlListItem{ - Service: "bce:bos", - Region: config.GetRegion(), - Effect: "Allow", - Resource: []string{"baidubce-sdk-go/*"}, - Permission: []string{"READ"}, - }, - }, - } - - sessionTokenResponse, err := bceClient.GetSessionToken(req, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if sessionTokenResponse.SessionToken == "" { - t.Error(util.FormatTest(method, "sessionToken is empty", "non empty sessionToken")) - } -} - -func TestSendRequest(t *testing.T) { - config := getConfig() - client := NewClient(config) - client.SetDebug(true) - url := "http://www.baidu.com" - request, _ := NewRequest("GET", url, nil) - resp, err := client.SendRequest(request, &SignOption{ - Credentials: &Credentials{ - AccessKeyID: "0b0f67dfb88244b289b72b142befad0c", - SecretAccessKey: "bad522c2126a4618a8125f4b6cf6356f", - }, - }) - - if err != nil { - t.Error(util.FormatTest("SendRequest", err.Error(), "nil")) - } - - url = "http://guoyao.me.no-such-host" - request, _ = NewRequest("GET", url, nil) - resp, err = client.SendRequest(request, nil) - - if _, ok := err.(*Error); ok { - t.Error(util.FormatTest("SendRequest", "bceError", "error")) - } - - url = "http://guoyao.me/no-exist-path" - request, _ = NewRequest("GET", url, nil) - resp, err = client.SendRequest(request, nil) - - if err == nil && resp.StatusCode != http.StatusNotFound { - t.Error(util.FormatTest("SendRequest", strconv.Itoa(resp.StatusCode), strconv.Itoa(http.StatusNotFound))) - } - - duration := client.RetryPolicy.GetDelayBeforeNextRetry(err, 1) - - if duration != -1 { - t.Error(util.FormatTest("SendRequest", duration.String(), strconv.Itoa(-1))) - } - - resp, err = client.SendRequest(getRequest(), nil) - - if err == nil { - t.Error(util.FormatTest("SendRequest", "nil", "error")) - } - - duration = client.RetryPolicy.GetDelayBeforeNextRetry(err, 1) - - if duration != -1 { - t.Error(util.FormatTest("SendRequest", duration.String(), strconv.Itoa(-1))) - } - - if bceError, ok := err.(*Error); ok { - bceError.StatusCode = http.StatusInternalServerError - retriesAttempted := 1 - duration = client.RetryPolicy.GetDelayBeforeNextRetry(err, retriesAttempted) - expected := (1 << uint(retriesAttempted)) * 300 * time.Millisecond - - if duration != expected { - t.Error(util.FormatTest("SendRequest", duration.String(), expected.String())) - } - - retriesAttempted = 2 - duration = client.RetryPolicy.GetDelayBeforeNextRetry(err, retriesAttempted) - expected = (1 << uint(retriesAttempted)) * 300 * time.Millisecond - - if duration != expected { - t.Error(util.FormatTest("SendRequest", duration.String(), expected.String())) - } - - retriesAttempted = 3 - duration = client.RetryPolicy.GetDelayBeforeNextRetry(err, retriesAttempted) - expected = (1 << uint(retriesAttempted)) * 300 * time.Millisecond - - if duration != expected { - t.Error(util.FormatTest("SendRequest", duration.String(), expected.String())) - } - - retriesAttempted = client.RetryPolicy.GetMaxErrorRetry() + 1 - duration = client.RetryPolicy.GetDelayBeforeNextRetry(err, retriesAttempted) - expected = -1 - - if duration != expected { - t.Error(util.FormatTest("SendRequest", duration.String(), expected.String())) - } - } - - client.SetDebug(false) -} - -func getRequest() *Request { - params := map[string]string{ - "partNumber": "9", - "uploadId": "VXBsb2FkIElpZS5tMnRzIHVwbG9hZA", - } - - url := util.GetURL("http", "bj.bcebos.com", "/v1/test/myfolder/readme.txt", params) - - request, _ := NewRequest("PUT", url, nil) - - return request -} - -func getHeaders() map[string]string { - headers := map[string]string{ - "Host": "bj.bcebos.com", - "Date": "Mon, 27 Apr 2015 16:23:49 +0800", - "Content-Type": "text/plain", - "Content-Length": "8", - "Content-Md5": "0a52730597fb4ffa01fc117d9e71e3a9", - "x-bce-date": "2015-04-27T08:23:49Z", - } - - return headers -} - -func TestBCCSendRequest(t *testing.T) { - config := getConfig() - client := NewClient(config) - client.SetDebug(true) - url := "https://bcc.bj.baidubce.com/v2/instance" - request, _ := NewRequest("GET", url, nil) - resp, err := client.SendRequest(request, &SignOption{ - Credentials: &Credentials{ - AccessKeyID: "0b565874be53440ba579d8a70cac8f98", - SecretAccessKey: "d8ad18e630c64bf4b4661ce9b49164c8", - }, - }) - bodyContent, err := resp.GetBodyContent() - - if err != nil { - t.Error("resp error") - } - - fmt.Printf("resp is : %s \n", bodyContent) - if err != nil { - t.Error(util.FormatTest("SendRequest", err.Error(), "nil")) - } - - client.SetDebug(false) -} - -func TestNewCredentialsFromFile(t *testing.T) { - c, err := NewCredentialsFromFile("aksk.json") - if err != nil { - t.Error("newcredentialsfromfile error") - } else { - if c.AccessKeyID != "aaa" { - t.Error("error ak") - } - } -} - -func TestNewConfigFromFile(t *testing.T) { - c, err := NewConfigFromFile("aksk.json") - if err != nil { - t.Error(err) - } else { - fmt.Printf("%+v", c) - } -} diff --git a/pkg/sdk/bce/error_test.go b/pkg/sdk/bce/error_test.go deleted file mode 100644 index 71abcdb..0000000 --- a/pkg/sdk/bce/error_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bce - -import ( - "encoding/json" - "net/http" - "strconv" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestError(t *testing.T) { - bceError := &Error{ - StatusCode: 500, - Code: "StatusInternalServerError", - Message: "failed", - RequestID: "123", - } - - result := bceError.Error() - expected := "Error Message: \"failed\", Error Code: \"StatusInternalServerError\", Status Code: 500, Request Id: \"123\"" - - if result != expected { - t.Error(util.FormatTest("Error", result, expected)) - } -} - -func TestBuildError(t *testing.T) { - resp := &Response{BodyContent: []byte{}} - err := buildError(resp) - - if _, ok := err.(*Error); ok { - t.Error(util.FormatTest("buildError", "bceError", "error")) - } - - bceError := &Error{ - StatusCode: 500, - Code: strconv.Itoa(http.StatusInternalServerError), - Message: "failed", - RequestID: "123", - } - byteArray, err := json.Marshal(bceError) - - if err != nil { - t.Error(util.FormatTest("buildError", err.Error(), "nil")) - } - - httpResponse := &http.Response{StatusCode: http.StatusInternalServerError} - resp = &Response{BodyContent: byteArray, Response: httpResponse} - err = buildError(resp) - - if _, ok := err.(*Error); !ok { - t.Error(util.FormatTest("buildError", "error", "bceError")) - } - - resp = &Response{BodyContent: []byte("Unknown Error"), Response: httpResponse} - err = buildError(resp) - - if _, ok := err.(*Error); ok { - t.Error(util.FormatTest("buildError", "bceError", "error")) - } -} diff --git a/pkg/sdk/bce/request_test.go b/pkg/sdk/bce/request_test.go deleted file mode 100644 index ee17284..0000000 --- a/pkg/sdk/bce/request_test.go +++ /dev/null @@ -1,227 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bce - -import ( - "strconv" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestAddHeadersForRequest(t *testing.T) { - headers := map[string]string{"Host": "guoyao.me", "Content-Type": "text/plain"} - req, err := NewRequest("GET", "guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("AddHeaders", err.Error(), "nil")) - } - - req.AddHeaders(headers) - - if len(req.Header) != len(headers) { - t.Error(util.FormatTest("AddHeaders", strconv.Itoa(len(req.Header)), strconv.Itoa(len(headers)))) - } -} - -func TestAddHeaderForRequest(t *testing.T) { - req, err := NewRequest("GET", "guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("addHeader", err.Error(), "nil")) - } - - req.addHeader("Host", "guoyao.me") - - if len(req.Header) != 1 { - t.Error(util.FormatTest("addHeader", strconv.Itoa(len(req.Header)), strconv.Itoa(1))) - } -} - -func TestSetHeaders(t *testing.T) { - headers := map[string]string{"Host": "guoyao.me", "Content-Type": "text/plain"} - req, err := NewRequest("GET", "guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("SetHeaders", err.Error(), "nil")) - } - - req.Header = map[string][]string{ - "Host": {"tocloud.org"}, - "Accept-Encoding": {"gzip, deflate"}, - } - req.SetHeaders(headers) - - if len(req.Header) != 3 { - t.Error(util.FormatTest("SetHeaders", strconv.Itoa(len(req.Header)), strconv.Itoa(3))) - } - - if len(req.Header["Host"]) != 1 { - t.Error(util.FormatTest("SetHeaders", strconv.Itoa(len(req.Header["Host"])), strconv.Itoa(1))) - } -} - -func TestSetHeader(t *testing.T) { - req, err := NewRequest("GET", "guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("setHeader", err.Error(), "nil")) - } - - req.Header = map[string][]string{ - "Host": {"tocloud.org"}, - "Accept-Encoding": {"gzip, deflate"}, - } - req.setHeader("Host", "guoyao.me") - - if len(req.Header) != 2 { - t.Error(util.FormatTest("setHeader", strconv.Itoa(len(req.Header)), strconv.Itoa(2))) - } - - if len(req.Header["Host"]) != 1 { - t.Error(util.FormatTest("setHeaders", strconv.Itoa(len(req.Header["Host"])), strconv.Itoa(1))) - } -} - -func TestClearHeaders(t *testing.T) { - req, err := NewRequest("GET", "guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("clearHeaders", err.Error(), "nil")) - } - - req.Header = map[string][]string{ - "Host": {"tocloud.org"}, - "Accept-Encoding": {"gzip, deflate"}, - } - req.clearHeaders() - - if len(req.Header) != 0 { - t.Error(util.FormatTest("clearHeaders", strconv.Itoa(len(req.Header)), strconv.Itoa(0))) - } -} - -func TestPrepareHeaders(t *testing.T) { - req, err := NewRequest("GET", "http://guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("clearHeaders", err.Error(), "nil")) - } - - signOption := &SignOption{ - Headers: map[string]string{"Content-Type": "text/plain"}, - } - req.prepareHeaders(signOption) - - if !util.MapContains(signOption.Headers, func(key, value string) bool { - return key == "host" && value == "guoyao.me" - }) { - t.Error(util.FormatTest("prepareHeaders", "no host", "host")) - } - - req, err = NewRequest("GET", "http://guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("clearHeaders", err.Error(), "nil")) - } - - req.Header = map[string][]string{ - "Host": {"tocloud.org"}, - "Accept-Encoding": {"gzip, deflate"}, - } - signOption = &SignOption{ - Headers: map[string]string{"Host": "tocloud.org", "Content-Type": "text/plain"}, - } - req.prepareHeaders(signOption) - - if req.Header.Get("Host") != "guoyao.me" { - t.Error(util.FormatTest("prepareHeaders", req.Header.Get("Host"), "guoyao.me")) - } -} - -func TestToCanonicalHeaderString(t *testing.T) { - req, err := NewRequest("GET", "http://guoyao.me", nil) - - if err != nil { - t.Error(util.FormatTest("toCanonicalHeaderString", err.Error(), "nil")) - } - - req.Header = map[string][]string{ - "Host": {"tocloud.org"}, - "Accept-Encoding": {"gzip, deflate"}, - } - - signOption := NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - nil, - ) - - canonicalString := req.toCanonicalHeaderString(signOption) - expected := "host:tocloud.org" - - if canonicalString != expected { - t.Error(util.FormatTest("toCanonicalHeaderString", canonicalString, expected)) - } - - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - []string{"Accept-Encoding"}, - ) - canonicalString = req.toCanonicalHeaderString(signOption) - expected = "accept-encoding:gzip%2C%20deflate" - - if canonicalString != expected { - t.Error(util.FormatTest("toCanonicalHeaderString", canonicalString, expected)) - } - - req.Header = map[string][]string{ - "Last-Modified": {"2015-04-27T08:23:49Z"}, - "Accept-Encoding": {"gzip, deflate"}, - } - signOption = NewSignOption( - "2015-04-27T08:23:49Z", - ExpirationPeriodInSeconds, - nil, - nil, - ) - canonicalString = req.toCanonicalHeaderString(signOption) - expected = "" - - if canonicalString != expected { - t.Error(util.FormatTest("toCanonicalHeaderString", canonicalString, expected)) - } -} - -func TestIsCanonicalHeader(t *testing.T) { - expected := true - result := isCanonicalHeader("content-type") - - if result != expected { - t.Error(util.FormatTest("isCanonicalHeader", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = false - result = isCanonicalHeader("Accept-Encoding") - - if result != expected { - t.Error(util.FormatTest("isCanonicalHeader", strconv.FormatBool(result), strconv.FormatBool(expected))) - } -} diff --git a/pkg/sdk/bce/response_test.go b/pkg/sdk/bce/response_test.go deleted file mode 100644 index fa946dc..0000000 --- a/pkg/sdk/bce/response_test.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bce - -import ( - "net/http" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestGetBodyContent(t *testing.T) { - request, err := http.NewRequest("GET", "http://www.baidu.com", nil) - - if err != nil { - t.Error(util.FormatTest("GetBodyContent", err.Error(), "nil")) - } - - client := &http.Client{} - resp, err := client.Do(request) - - if err != nil { - t.Error(util.FormatTest("GetBodyContent", err.Error(), "nil")) - } - - bceResponse := NewResponse(resp) - bodyContent, err := bceResponse.GetBodyContent() - - if err != nil { - t.Error(util.FormatTest("GetBodyContent", err.Error(), "nil")) - } - - if bodyContent == nil { - t.Error(util.FormatTest("GetBodyContent", "nil", "not nil")) - } else if string(bodyContent) == "" { - t.Error(util.FormatTest("GetBodyContent", "empty string", "none empty string")) - } -} diff --git a/pkg/sdk/blb/backendserver_test.go b/pkg/sdk/blb/backendserver_test.go deleted file mode 100644 index a6f0b5a..0000000 --- a/pkg/sdk/blb/backendserver_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 blb - -import ( - "fmt" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestAddBackendServers(t *testing.T) { - args := &AddBackendServersArgs{ - LoadBalancerId: "lb-e5b33752", - BackendServerList: []BackendServer{ - BackendServer{ - InstanceId: "i-YWIy3FQx", - Weight: 50, - }, - BackendServer{ - InstanceId: "i-vfBlsqNG", - Weight: 50, - }, - }, - } - err := blbClient.AddBackendServers(args) - if err != nil { - t.Error(err) - } -} - -func TestDescribeBackendServers(t *testing.T) { - args := &DescribeBackendServersArgs{ - LoadBalancerId: "lb-e5b33752", - } - list, err := blbClient.DescribeBackendServers(args) - if err != nil { - fmt.Println(err) - t.Error(util.FormatTest("DescribeBackendServers", err.Error(), "nil")) - } - for _, blb := range list { - fmt.Println(blb) - } -} - -func TestUpdateBackendServers(t *testing.T) { - args := &UpdateBackendServersArgs{ - LoadBalancerId: "lb-e5b33752", - BackendServerList: []BackendServer{BackendServer{ - InstanceId: "i-vfBlsqNG", - Weight: 99, - }}, - } - err := blbClient.UpdateBackendServers(args) - if err != nil { - t.Error(err) - } -} - -func TestRemoveBackendServers(t *testing.T) { - args := &RemoveBackendServersArgs{ - LoadBalancerId: "lb-e5b33752", - BackendServerList: []string{"i-vfBlsqNG", "i-vfBlsqNG"}, - } - - err := blbClient.RemoveBackendServers(args) - if err != nil { - t.Error(err) - } -} diff --git a/pkg/sdk/blb/client_test.go b/pkg/sdk/blb/client_test.go deleted file mode 100644 index f166ec3..0000000 --- a/pkg/sdk/blb/client_test.go +++ /dev/null @@ -1,382 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 blb - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "os" - - "github.com/gorilla/mux" - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" -) - -var ( - testHTTPServer *httptest.Server - blbClient *Client -) - -func init() { - var credentials, _ = bce.NewCredentialsFromFile("../aksk-test.json") - - //var bceConfig = bce.NewConfig(credentials) - var bceConfig = &bce.Config{ - Credentials: credentials, - Checksum: true, - Region: os.Getenv("BOS_REGION"), - } - var bccConfig = NewConfig(bceConfig) - blbClient = NewBLBClient(bccConfig) - r := mux.NewRouter() - // loadbalancer - r.HandleFunc("/v1/blb", handleGetBLB).Methods("GET") - r.HandleFunc("/v1/blb/{blbid}", handleDeleteBLB).Methods("DELETE") - r.HandleFunc("/v1/blb/{blbid}", handleUpdateBLB).Methods("PUT") - r.HandleFunc("/v1/blb", handleCreateBLB).Methods("POST") - - // backendserver - r.HandleFunc("/v1/blb/{blbid}/backendserver", handleCreateBackendServers).Methods("POST") - r.HandleFunc("/v1/blb/{blbid}/backendserver", handleDescribeBackendServers).Methods("GET") - r.HandleFunc("/v1/blb/{blbid}/backendserver", handleDescribeBackendServers).Methods("PUT") - r.HandleFunc("/v1/blb/{blbid}/backendserver", handleDescribeBackendServers).Methods("DELETE") - - // listener - r.HandleFunc("/v1/blb/{blbid}/TCPlistener", handleCreateTCPlistener).Methods("POST") - r.HandleFunc("/v1/blb/{blbid}/UDPlistener", handleCreateUDPlistener).Methods("POST") - r.HandleFunc("/v1/blb/{blbid}/HTTPlistener", handleCreateHTTPListener).Methods("POST") - r.HandleFunc("/v1/blb/{blbid}/TCPlistener", handleDescribeTCPListeners).Methods("GET") - r.HandleFunc("/v1/blb/{blbid}/UDPlistener", handleDescribeUDPListeners).Methods("GET") - - r.HandleFunc("/v1/blb/{blbid}/UDPlistener", handleUpdateUDPListener).Methods("PUT") - r.HandleFunc("/v1/blb/{blbid}/TCPlistener", handleUpdateTCPListener).Methods("PUT") - r.HandleFunc("/v1/blb/{blbid}/listener", handleDeleteListeners).Methods("PUT") - // start - testHTTPServer = httptest.NewServer(r) - blbClient.Endpoint = testHTTPServer.URL -} - -func handleGetBLB(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - response := `{ - "blbList":[ - { - "blbId":"lb-a7e5zPPk", - "status":"available", - "name":"test-blb", - "desc":"用于生产环境", - "vpcId":"vpc-fy6vdykpwkqb", - "address":"10.32.249.113" - }, - { - "blbId": "lb-gj5gVpeq", - "status":"available", - "name": "nametest", - "desc": "用于测试环境", - "vpcId":"vpc-a8n5p6kybbx4", - "address": "10.32.251.4" - } - ], - "marker": "blb-0A20F971", - "nextMarker": "blb-0A20FB09", - "isTruncated": true, - "maxKeys": 2 -}` - fmt.Fprint(w, response) -} - -func handleCreateBLB(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &CreateLoadBalancerArgs{} - json.Unmarshal(body, args) - if args.Name != expectCreateBLB.Name { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "blbId": "lb-BLuOPSLZ", - "name": "blb-for-test", - "desc": "", - "address": "10.32.251.93" -}` - fmt.Fprint(w, response) -} - -func handleUpdateBLB(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-e5b33752" { - w.WriteHeader(200) - return - } - w.WriteHeader(400) -} - -func handleDeleteBLB(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-426fad2b" { - w.WriteHeader(200) - } else { - w.WriteHeader(400) - } - -} - -func handleCreateBackendServers(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &AddBackendServersArgs{} - json.Unmarshal(body, args) - fmt.Println(args.LoadBalancerId) - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-e5b33752" { - w.WriteHeader(http.StatusBadRequest) - return - } -} - -func handleDescribeBackendServers(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-e5b33752" { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "backendServerList": [ - { - "instanceId": "i-YfAibl4A", - "weight": 50 - } - ], - "marker": "rs-0A6BE9BB", - "nextMarker": null, - "isTruncated": false, - "maxKeys": 1000 -}` - fmt.Fprint(w, response) -} - -func handleUpdateBackendServers(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-e5b33752" { - w.WriteHeader(200) - return - } - w.WriteHeader(400) -} - -func handleDeleteBackendServers(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-e5b33752" { - w.WriteHeader(200) - } else { - w.WriteHeader(400) - } - -} - -func handleCreateTCPlistener(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &CreateTCPListenerArgs{} - json.Unmarshal(body, args) - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-e5b33752" { - w.WriteHeader(http.StatusBadRequest) - return - } - if args.ListenerPort != 8088 { - w.WriteHeader(http.StatusBadRequest) - return - } -} - -func handleCreateUDPlistener(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &CreateUDPListenerArgs{} - json.Unmarshal(body, args) - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-f5d263e5" { - w.WriteHeader(http.StatusBadRequest) - return - } - if args.ListenerPort != 8888 { - w.WriteHeader(http.StatusBadRequest) - return - } -} - -func handleCreateHTTPListener(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &CreateUDPListenerArgs{} - json.Unmarshal(body, args) - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-f5d263e5" { - w.WriteHeader(http.StatusBadRequest) - return - } - if args.ListenerPort != 8899 { - w.WriteHeader(http.StatusBadRequest) - return - } -} - -func handleDescribeTCPListeners(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-e5b33752" { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "listenerList": [ - { - "listenerPort": 80, - "backendPort": 80, - "scheduler": "RoundRobin", - "healthCheckTimeoutInSecond": 3, - "healthCheckInterval": 3, - "unhealthyThreshold": 3, - "healthyThreshold": 3 - }, - { - "listenerPort": 88, - "backendPort": 88, - "scheduler": "RoundRobin", - "healthCheckTimeoutInSecond": 2, - "healthCheckInterval": 4, - "unhealthyThreshold": 3, - "healthyThreshold": 3 - } - ], - "marker": "listener-0050", - "nextMarker": null, - "isTruncated": false, - "maxKeys": 2 -}` - fmt.Fprint(w, response) -} - -func handleDescribeUDPListeners(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid != "lb-07ab7a1d" { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "listenerList": [ - { - "listenerPort": 80, - "backendPort": 80, - "scheduler": "RoundRobin", - "healthCheckTimeoutInSecond": 3, - "healthCheckInterval": 3, - "unhealthyThreshold": 3, - "healthyThreshold": 3 - }, - { - "listenerPort": 88, - "backendPort": 88, - "scheduler": "RoundRobin", - "healthCheckTimeoutInSecond": 2, - "healthCheckInterval": 4, - "unhealthyThreshold": 3, - "healthyThreshold": 3 - } - ], - "marker": "listener-0050", - "nextMarker": null, - "isTruncated": false, - "maxKeys": 2 -}` - fmt.Fprint(w, response) -} - -func handleUpdateUDPListener(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-f5d263e5" { - w.WriteHeader(200) - return - } - w.WriteHeader(400) -} - -func handleUpdateTCPListener(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-e5b33752" { - w.WriteHeader(200) - return - } - w.WriteHeader(400) -} - -func handleDeleteListeners(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - blbid := vars["blbid"] - if blbid == "lb-e5b33752" { - w.WriteHeader(200) - } else { - w.WriteHeader(400) - } - -} diff --git a/pkg/sdk/blb/listener_test.go b/pkg/sdk/blb/listener_test.go deleted file mode 100644 index d1333f7..0000000 --- a/pkg/sdk/blb/listener_test.go +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 blb - -import ( - "fmt" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestCreateTCPListener(t *testing.T) { - args := &CreateTCPListenerArgs{ - LoadBalancerId: "lb-e5b33752", - ListenerPort: 8088, - BackendPort: 8080, - Scheduler: "LeastConnection", - } - err := blbClient.CreateTCPListener(args) - if err != nil { - t.Error(err) - } -} - -func TestCreateUDPListener(t *testing.T) { - args := &CreateUDPListenerArgs{ - LoadBalancerId: "lb-f5d263e5", - ListenerPort: 8888, - BackendPort: 8888, - Scheduler: "LeastConnection", - HealthCheckString: "hello", - } - err := blbClient.CreateUDPListener(args) - if err != nil { - t.Error(err) - } -} - -func TestCreateHTTPListener(t *testing.T) { - args := &CreateHTTPListenerArgs{ - LoadBalancerId: "lb-f5d263e5", - ListenerPort: 8899, - BackendPort: 8899, - Scheduler: "LeastConnection", - } - err := blbClient.CreateHTTPListener(args) - if err != nil { - t.Error(err) - } -} - -func TestDescribeTCPListener(t *testing.T) { - args := &DescribeTCPListenerArgs{ - LoadBalancerId: "lb-e5b33752", - ListenerPort: 8088, - } - list, err := blbClient.DescribeTCPListener(args) - - if err != nil { - t.Error(util.FormatTest("ListInstances", err.Error(), "nil")) - } - for _, blb := range list { - fmt.Println(blb.ListenerPort) - } -} - -func TestDescribeUDPListener(t *testing.T) { - args := &DescribeUDPListenerArgs{ - LoadBalancerId: "lb-07ab7a1d", - // ListenerPort: 80, - } - list, err := blbClient.DescribeUDPListener(args) - - if err != nil { - t.Error(util.FormatTest("DescribeUDPListener", err.Error(), "nil")) - } - for _, blb := range list { - fmt.Println(blb.ListenerPort) - } -} -func TestUpdateTCPListener(t *testing.T) { - args := &UpdateTCPListenerArgs{ - LoadBalancerId: "lb-e5b33752", - ListenerPort: 8088, - BackendPort: 999, - } - err := blbClient.UpdateTCPListener(args) - if err != nil { - t.Error(err) - } -} - -func TestUpdateUDPListener(t *testing.T) { - args := &UpdateUDPListenerArgs{ - LoadBalancerId: "lb-f5d263e5", - ListenerPort: 8888, - BackendPort: 8019, - Scheduler: "RoundRobin", - HealthCheckString: "A", - } - err := blbClient.UpdateUDPListener(args) - if err != nil { - t.Error(err) - } -} - -func TestDeleteListeners(t *testing.T) { - args := &DeleteListenersArgs{ - LoadBalancerId: "lb-e5b33752", - PortList: []int{8088}, - } - err := blbClient.DeleteListeners(args) - if err != nil { - t.Error(err) - } -} diff --git a/pkg/sdk/blb/loadbalancer_test.go b/pkg/sdk/blb/loadbalancer_test.go deleted file mode 100644 index 4d067c2..0000000 --- a/pkg/sdk/blb/loadbalancer_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 blb - -import ( - "fmt" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -var expectCreateBLB = &CreateLoadBalancerArgs{ - Name: "blb-for-test", -} - -func TestCreateLoadBalance(t *testing.T) { - blb, err := blbClient.CreateLoadBalancer(expectCreateBLB) - if err != nil { - t.Error(util.FormatTest("TestCreateLoadBalance", err.Error(), "nil")) - } else { - if blb.Name != expectCreateBLB.Name { - t.Error("blb name error") - } - } -} - -func TestDescribeLoadBalancers(t *testing.T) { - args := &DescribeLoadBalancersArgs{ - LoadBalancerName: "test", - } - list, err := blbClient.DescribeLoadBalancers(args) - - if err != nil { - fmt.Println(err) - t.Error(util.FormatTest("TestDescribeLoadBalancers", err.Error(), "nil")) - } - if len(list) != 2 { - t.Error("blb length error") - } -} - -func TestUpdateLoadBalancer(t *testing.T) { - args := &UpdateLoadBalancerArgs{ - LoadBalancerId: "lb-e5b33752", - Name: "golang-123", - } - err := blbClient.UpdateLoadBalancer(args) - if err != nil { - t.Error(err) - } -} - -func TestDeleteLoadBalancer(t *testing.T) { - args := &DeleteLoadBalancerArgs{ - LoadBalancerId: "lb-426fad2b", - } - err := blbClient.DeleteLoadBalancer(args) - if err != nil { - t.Error(err) - } -} diff --git a/pkg/sdk/bos/bucket_test.go b/pkg/sdk/bos/bucket_test.go deleted file mode 100644 index a6a034a..0000000 --- a/pkg/sdk/bos/bucket_test.go +++ /dev/null @@ -1,295 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bos - -import ( - "net/http" - "strconv" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestNewObjectMetadataFromHeader(t *testing.T) { - header := http.Header{ - "cache-control": []string{"no-cache", "no-store"}, - "Content-Disposition": []string{"inline"}, - "Content-Length": []string{"1024"}, - "Content-Range": []string{"bytes=0-1024"}, - "Content-Type": []string{"text/plain"}, - "Expires": []string{"Tue, 03 Jan 2017 05:30:19 GMT"}, - "Etag": []string{"abc123"}, - "x-bce-meta-name": []string{"hello"}, - } - metadata := NewObjectMetadataFromHeader(header) - - if metadata.CacheControl != "no-cache" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.CacheControl, "no-cache")) - } - - if metadata.ContentDisposition != "inline" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.ContentDisposition, "inline")) - } - - if metadata.ContentLength != 1024 { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", strconv.FormatInt(metadata.ContentLength, 10), strconv.Itoa(1024))) - } - - if metadata.ContentRange != "bytes=0-1024" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.ContentRange, "bytes=0-1024")) - } - - if metadata.ContentType != "text/plain" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.ContentType, "text/plain")) - } - - if metadata.Expires != "Tue, 03 Jan 2017 05:30:19 GMT" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.Expires, "Tue, 03 Jan 2017 05:30:19 GMT")) - } - - if metadata.ETag != "abc123" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.ETag, "abc123")) - } - - if metadata.UserMetadata["x-bce-meta-name"] != "hello" { - t.Error(util.FormatTest("NewObjectMetadataFromHeader", metadata.UserMetadata["x-bce-meta-name"], "hello")) - } -} - -func TestAddUserMetadata(t *testing.T) { - metadata := &ObjectMetadata{} - metadata.AddUserMetadata("x-bce-meta-name", "hello") - - if metadata.UserMetadata["x-bce-meta-name"] != "hello" { - t.Error(util.FormatTest("AddUserMetadata", metadata.UserMetadata["x-bce-meta-name"], "hello")) - } -} - -func TestMergeToSignOption(t *testing.T) { - option := &bce.SignOption{} - header := http.Header{ - "cache-control": []string{"no-cache", "no-store"}, - "Content-Disposition": []string{"inline"}, - "Content-Length": []string{"1024"}, - "Content-Range": []string{"bytes=0-1024"}, - "Content-Type": []string{"text/plain"}, - "Expires": []string{"Tue, 03 Jan 2017 05:30:19 GMT"}, - "Etag": []string{"abc123"}, - "x-bce-meta-name": []string{"hello"}, - } - metadata := NewObjectMetadataFromHeader(header) - metadata.ContentMD5 = "md5-value" - metadata.ContentSha256 = "sha256-value" - metadata.AddUserMetadata("server", "nginx") - metadata.mergeToSignOption(option) - - if option.Headers["Cache-Control"] != "no-cache" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["Cache-Control"], "no-cache")) - } - - if option.Headers["Content-Disposition"] != "inline" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["Content-Disposition"], "inline")) - } - - if option.Headers["x-bce-meta-name"] != "hello" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["x-bce-meta-name"], "hello")) - } - - if option.Headers["x-bce-meta-server"] != "nginx" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["x-bce-meta-server"], "nginx")) - } - - if option.Headers["Content-MD5"] != "md5-value" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["Content-MD5"], "md5-value")) - } - - if option.Headers["x-bce-content-sha256"] != "sha256-value" { - t.Error(util.FormatTest("mergeToSignOption", option.Headers["x-bce-content-sha256"], "sha256-value")) - } -} - -func TestGetETag(t *testing.T) { - header := http.Header{"Etag": []string{"\"12345\""}} - response := NewPutObjectResponse(header) - etag := response.GetETag() - - if etag != "12345" { - t.Error(util.FormatTest("GetETag", etag, "12345")) - } -} - -func TestGetCommonPrefixes(t *testing.T) { - response := &ListObjectsResponse{ - CommonPrefixes: []map[string]string{ - map[string]string{"prefix": "prefix-0"}, - map[string]string{"prefix": "prefix-1"}, - map[string]string{"prefix": "prefix-2"}, - }, - } - - prefixes := response.GetCommonPrefixes() - - if len(prefixes) != len(response.CommonPrefixes) { - t.Error(util.FormatTest("GetCommonPrefixes", strconv.Itoa(len(prefixes)), strconv.Itoa(len(response.CommonPrefixes)))) - } - - if prefixes[1] != response.CommonPrefixes[1]["prefix"] { - t.Error(util.FormatTest("GetCommonPrefixes", prefixes[1], response.CommonPrefixes[1]["prefix"])) - } -} - -func TestMergeToSignOptionForCopyObjectRequest(t *testing.T) { - option := &bce.SignOption{} - request := CopyObjectRequest{ - SrcBucketName: "source-bucket", - SrcKey: "source-bucket-key", - DestBucketName: "dest-bucket", - DestKey: "dest-bucket-key", - ObjectMetadata: &ObjectMetadata{ - CacheControl: "no-cache", - ContentType: "text/plain", - UserMetadata: map[string]string{"request-id": "12345"}, - }, - SourceMatch: "xxx", - SourceNoneMatch: "xxx", - SourceModifiedSince: "xxx", - SourceUnmodifiedSince: "xxx", - } - - request.mergeToSignOption(option) - - if len(option.Headers) != 8 { - t.Error(util.FormatTest("CopyObjectRequest: MergeToSignOption", strconv.Itoa(len(option.Headers)), strconv.Itoa(8))) - } - - if option.Headers["x-bce-metadata-directive"] != "replace" { - t.Error(util.FormatTest("CopyObjectRequest: MergeToSignOption", option.Headers["x-bce-metadata-directive"], "replace")) - } -} - -func TestMergeToSignOptionForGetObjectRequest(t *testing.T) { - lengthRange := "0-1024" - expected := "bytes=" + lengthRange - - option := &bce.SignOption{} - request := &GetObjectRequest{ - BucketName: "test-bucket-name", - ObjectKey: "test-object-key", - Range: lengthRange, - } - - request.MergeToSignOption(option) - - if option.Headers["Range"] != expected { - t.Error(util.FormatTest("GetObjectRequest: MergeToSignOption", option.Headers["Range"], expected)) - } -} - -func TestErrorForDeleteMultipleObjectsError(t *testing.T) { - deleteMultipleObjectsError := DeleteMultipleObjectsError{ - Key: "error-key", - Code: "error-code", - Message: "error-message", - } - - result := deleteMultipleObjectsError.Error() - expected := "error-message" - - if result != expected { - t.Error(util.FormatTest("DeleteMultipleObjectsError: Error", result, expected)) - } - - deleteMultipleObjectsError = DeleteMultipleObjectsError{ - Key: "error-key", - Code: "error-code", - } - - result = deleteMultipleObjectsError.Error() - expected = "error-code" - - if result != expected { - t.Error(util.FormatTest("DeleteMultipleObjectsError: Error", result, expected)) - } -} - -func TestSort(t *testing.T) { - request := CompleteMultipartUploadRequest{ - BucketName: "test-bucket", - ObjectKey: "test-object-key", - UploadId: "test-upload-id", - Parts: []PartSummary{ - PartSummary{PartNumber: 2}, - PartSummary{PartNumber: 3}, - PartSummary{PartNumber: 1}, - }, - } - - result := request.Parts[0].PartNumber - expected := 2 - - if result != expected { - t.Error(util.FormatTest("CompleteMultipartUploadRequest: Sort", strconv.Itoa(result), strconv.Itoa(expected))) - } - - request.sort() - - result = request.Parts[0].PartNumber - expected = 1 - - if result != expected { - t.Error(util.FormatTest("CompleteMultipartUploadRequest: Sort", strconv.Itoa(result), strconv.Itoa(expected))) - } -} - -func TestIsUserDefinedMetadata(t *testing.T) { - expected := true - result := IsUserDefinedMetadata("x-bce-meta-name") - - if result != expected { - t.Error(util.FormatTest("IsUserDefinedMetadata", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = false - result = IsUserDefinedMetadata("content-type") - - if result != expected { - t.Error(util.FormatTest("IsUserDefinedMetadata", strconv.FormatBool(result), strconv.FormatBool(expected))) - } -} - -func TestToUserDefinedMetadata(t *testing.T) { - expected := "x-bce-meta-name" - result := ToUserDefinedMetadata("x-bce-meta-name") - - if result != expected { - t.Error(util.FormatTest("ToUserDefinedMetadata", result, expected)) - } - - result = ToUserDefinedMetadata("name") - - if result != expected { - t.Error(util.FormatTest("ToUserDefinedMetadata", result, expected)) - } - - expected = "x-bce-meta-content-type" - result = ToUserDefinedMetadata("content-type") - - if result != expected { - t.Error(util.FormatTest("ToUserDefinedMetadata", result, expected)) - } -} diff --git a/pkg/sdk/bos/client_test.go b/pkg/sdk/bos/client_test.go deleted file mode 100644 index 696cf63..0000000 --- a/pkg/sdk/bos/client_test.go +++ /dev/null @@ -1,1705 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 bos - -import ( - "fmt" - "io" - "io/ioutil" - "math" - "net/http" - "os" - "strconv" - "strings" - "sync" - "testing" - "time" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -var credentials = bce.NewCredentials(os.Getenv("BAIDU_BCE_AK"), os.Getenv("BAIDU_BCE_SK")) - -//var bceConfig = bce.NewConfig(credentials) -var bceConfig = &bce.Config{ - Credentials: credentials, - Checksum: true, - Region: os.Getenv("BOS_REGION"), -} -var bosConfig = NewConfig(bceConfig) -var bosClient = NewClient(bosConfig) - -func TestCheckBucketName(t *testing.T) { - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - t.Error(util.FormatTest("checkBucketName", "panic", "no panic")) - } - }() - - checkBucketName("bucket-0") - } - }() - - checkBucketName("/bucket-0") - t.Error(util.FormatTest("checkBucketName", "no panic", "panic")) - } - }() - - checkBucketName("") - t.Error(util.FormatTest("checkBucketName", "no panic", "panic")) -} - -func TestCheckObjectKey(t *testing.T) { - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - - defer func() { - if err := recover(); err != nil { - fmt.Println(err) - t.Error(util.FormatTest("checkObjectKey", "panic", "no panic")) - } - }() - - checkObjectKey("object-0") - } - }() - - checkObjectKey("/object-0") - t.Error(util.FormatTest("checkObjectKey", "no panic", "panic")) - } - }() - - checkObjectKey("") - t.Error(util.FormatTest("checkObjectKey", "no panic", "panic")) -} - -func TestGetURL(t *testing.T) { - expected := fmt.Sprintf("http://bucket-0.%s.bcebos.com/object-0", bosClient.GetRegion()) - url := bosClient.GetURL("bucket-0", "object-0", nil) - - if url != expected { - t.Error(util.FormatTest("GetURL", url, expected)) - } - - expected = fmt.Sprintf("http://%s.bcebos.com/object-0", bosClient.GetRegion()) - url = bosClient.GetURL("", "object-0", nil) - - if url != expected { - t.Error(util.FormatTest("GetURL", url, expected)) - } -} - -func TestGetBucketLocation(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-bucket-location-" - method := "GetBucketLocation" - - bucketName := bucketNamePrefix + strconv.Itoa(int(time.Now().UnixNano())) - _, err := bosClient.GetBucketLocation(bucketName, nil) - - if err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - expected := bosClient.GetRegion() - location, _ := bosClient.GetBucketLocation(bucketName, nil) - - if location.LocationConstraint != expected { - t.Error(util.FormatTest(method, location.LocationConstraint, expected)) - } - }) -} - -func TestListBuckets(t *testing.T) { - _, err := bosClient.ListBuckets(nil) - - if err != nil { - t.Error(util.FormatTest("ListBuckets", err.Error(), "nil")) - } -} - -func TestCreateBucket(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-create-bucket-" - method := "CreateBucket" - - around(t, method, bucketNamePrefix, "", nil) -} - -func TestDoesBucketExist(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-does-bucket-exist-" - method := "DoesBucketExist" - - expected := false - exists, _ := bosClient.DoesBucketExist(bucketNamePrefix, nil) - - if exists != expected { - t.Error(util.FormatTest(method, strconv.FormatBool(exists), strconv.FormatBool(expected))) - } - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - expected := true - exists, err := bosClient.DoesBucketExist(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if exists != expected { - t.Error(util.FormatTest(method, strconv.FormatBool(exists), strconv.FormatBool(expected))) - } - }) - -} - -func TestDeleteBucket(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-bucket-" - method := "DeleteBucket" - - around(t, method, bucketNamePrefix, "", nil) -} - -func TestSetBucketPrivate(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-private-" - method := "SetBucketPrivate" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - err := bosClient.SetBucketPrivate(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestSetBucketPublicRead(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-public-read-" - method := "SetBucketPublicRead" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - err := bosClient.SetBucketPublicRead(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestSetBucketPublicReadWrite(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-public-rw-" - method := "SetBucketPublicReadWrite" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - err := bosClient.SetBucketPublicReadWrite(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestGetBucketAcl(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-bucket-acl-" - method := "GetBucketAcl" - - _, err := bosClient.GetBucketAcl(bucketNamePrefix, nil) - if err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - _, err := bosClient.GetBucketAcl(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestSetBucketAcl(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-acl-" - method := "SetBucketAcl" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketAcl := BucketAcl{ - AccessControlList: []Grant{ - Grant{ - Grantee: []BucketGrantee{ - BucketGrantee{Id: "ef5a4b19192f4931adcf0e12f82795e2"}, - }, - Permission: []string{"FULL_CONTROL"}, - }, - }, - } - if err := bosClient.SetBucketAcl(bucketName, bucketAcl, nil); err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestPutObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-put-object-" - method := "PutObject" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - metadata := &ObjectMetadata{ - CacheControl: "no-cache", - ContentDisposition: "attachment", - ContentType: "text/plain", - } - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, metadata, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) - - byteArray := []byte(str) - objectKey = "put-object-from-bytes.txt" - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, byteArray, metadata, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) - - reader := strings.NewReader(str) - objectKey = "put-object-from-reader.txt" - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, reader, metadata, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) - - defer func() { - if err := recover(); err == nil { - t.Error(util.FormatTest(method, "panic", "nil")) - } - }() - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, 1, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestDeleteObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-object-" - method := "DeleteObject" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestDeleteMultipleObjects(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-multiple-objects-" - method := "DeleteMultipleObjects" - str := "Hello World 你好" - - objects := []string{ - "examples/delete-multiple-objects/put-object-from-string.txt", - "examples/delete-multiple-objects/put-object-from-string-2.txt", - "examples/delete-multiple-objects/put-object-from-string-3.txt", - } - - around(t, method, bucketNamePrefix, objects, func(bucketName string) { - for _, objectKey := range objects { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }) - - around(t, method, bucketNamePrefix, []string{}, nil) - - bucketName := bucketNamePrefix + strconv.Itoa(int(time.Now().UnixNano())) - if len(bucketName) > 63 { - bucketName = bucketName[:63] - } - - err := bosClient.CreateBucket(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at creating bucket", err.Error(), "nil")) - } else { - defer func() { - deleteMultipleObjectsResponse, err := bosClient.DeleteMultipleObjects(bucketName, objects, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if len(deleteMultipleObjectsResponse.Errors) != 1 { - t.Error(util.FormatTest(method, strconv.Itoa(len(deleteMultipleObjectsResponse.Errors)), strconv.Itoa(1))) - } - - err = bosClient.DeleteBucket(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at deleting bucket", err.Error(), "nil")) - } - - }() - - for index, objectKey := range objects { - if index < len(objects)-1 { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - } - } -} - -func TestListObjects(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-list-objects-" - method := "ListObjects" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - listObjectsResponse, err := bosClient.ListObjects(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 1 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "1")) - } - } - }) -} - -func TestListObjectsFromRequest(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-list-objects-from-request-" - method := "ListObjectsFromRequest" - str := "Hello World 你好" - - objects := []string{ - "hello.txt", - "examples/list-objects-from-request/put-object-from-string.txt", - "examples/list-objects-from-request/put-object-from-string-2.txt", - "examples2/list-objects-from-request/put-object-from-string-3.txt", - "examples2/list-objects-from-request/put-object-from-string.txt", - "examples3/list-objects-from-request/put-object-from-string-2.txt", - "examples3/list-objects-from-request/put-object-from-string-3.txt", - } - objectsLength := len(objects) - - around(t, method, bucketNamePrefix, objects, func(bucketName string) { - for _, objectKey := range objects { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - } - - listObjectsRequest := ListObjectsRequest{ - BucketName: bucketName, - } - listObjectsResponse, err := bosClient.ListObjectsFromRequest(listObjectsRequest, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != objectsLength { - t.Error(util.FormatTest(method, strconv.Itoa(length), strconv.Itoa(objectsLength))) - } - - listObjectsRequest = ListObjectsRequest{ - BucketName: bucketName, - Delimiter: "/", - } - listObjectsResponse, err = bosClient.ListObjectsFromRequest(listObjectsRequest, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - if length := len(listObjectsResponse.Contents); length != 1 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "1")) - } - - if length := len(listObjectsResponse.CommonPrefixes); length != 3 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "3")) - } - } - - listObjectsRequest = ListObjectsRequest{ - BucketName: bucketName, - Prefix: "examples2", - } - listObjectsResponse, err = bosClient.ListObjectsFromRequest(listObjectsRequest, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 2 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "2")) - } - - listObjectsRequest = ListObjectsRequest{ - BucketName: bucketName, - MaxKeys: 2, - } - listObjectsResponse, err = bosClient.ListObjectsFromRequest(listObjectsRequest, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 2 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "2")) - } - - listObjectsRequest = ListObjectsRequest{ - BucketName: bucketName, - Marker: "examples2", - } - listObjectsResponse, err = bosClient.ListObjectsFromRequest(listObjectsRequest, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 5 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "5")) - } - }) -} - -func TestCopyObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-copy-object-" - method := "CopyObject" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - destKey := "put-object-from-string-copy.txt" - _, err := bosClient.CopyObject(bucketName, objectKey, bucketName, destKey, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - listObjectsResponse, err := bosClient.ListObjects(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 2 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "2")) - } else { - err = bosClient.DeleteObject(bucketName, destKey, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at deleting object", err.Error(), "nil")) - } - } - } - } - }) -} - -func TestCopyObjectFromRequest(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-copy-object-from-request-" - method := "CopyObjectFromRequest" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - destKey := "put-object-from-string-copy.txt" - - copyObjectRequest := CopyObjectRequest{ - SrcBucketName: bucketName, - SrcKey: objectKey, - DestBucketName: bucketName, - DestKey: destKey, - ObjectMetadata: &ObjectMetadata{ - CacheControl: "no-cache", - UserMetadata: map[string]string{ - "test-user-metadata": "test user metadata", - "x-bce-meta-name": "x-bce-meta-name", - }, - }, - } - - _, err := bosClient.CopyObjectFromRequest(copyObjectRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - listObjectsResponse, err := bosClient.ListObjects(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if length := len(listObjectsResponse.Contents); length != 2 { - t.Error(util.FormatTest(method, strconv.Itoa(length), "2")) - } else { - err = bosClient.DeleteObject(bucketName, destKey, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at deleting object", err.Error(), "nil")) - } - } - } - } - }) -} - -func TestGetObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-object-" - method := "GetObject" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - object, err := bosClient.GetObject(bucketName, objectKey, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if object.ObjectMetadata.ETag == "" { - t.Error(util.FormatTest(method, "etag is empty", "non empty etag")) - } else { - byteArray, err := ioutil.ReadAll(object.ObjectContent) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if len(byteArray) == 0 { - t.Error(util.FormatTest(method, "body is empty", "non empty body")) - } - } - } - }) -} - -func TestGetObjectFromRequest(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-object-from-request-" - method := "GetObjectFromRequest" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - getObjectRequest := GetObjectRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - } - getObjectRequest.SetRange(0, 1000) - object, err := bosClient.GetObjectFromRequest(getObjectRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if object.ObjectMetadata.ETag == "" { - t.Error(util.FormatTest(method, "etag is empty", "non empty etag")) - } else { - byteArray, err := ioutil.ReadAll(object.ObjectContent) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if len(byteArray) == 0 { - t.Error(util.FormatTest(method, "body is empty", "non empty body")) - } - } - } - }) -} - -func TestGetObjectToFile(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-object-to-file-" - method := "GetObjectToFile" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - getObjectRequest := &GetObjectRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - } - getObjectRequest.SetRange(0, 1000) - - file, err := os.OpenFile(objectKey, os.O_WRONLY|os.O_CREATE, 0666) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - objectMetadata, err := bosClient.GetObjectToFile(getObjectRequest, file, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if objectMetadata.ETag == "" { - t.Error(util.FormatTest(method, "etag is empty", "non empty etag")) - } else if !util.CheckFileExists(objectKey) { - t.Error(util.FormatTest(method, "file is not saved to local", "file saved to local")) - } else { - err := os.Remove(objectKey) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - } - } - }) -} - -func TestGetObjectMetadata(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-object-metadata-" - method := "GetObjectMetadata" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - objectMetadata, err := bosClient.GetObjectMetadata(bucketName, objectKey, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if objectMetadata.ETag == "" { - t.Error(util.FormatTest(method, "etag is empty", "non empty etag")) - } - } - }) -} - -func TestGeneratePresignedUrl(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-generate-presigned-url-" - method := "GeneratePresignedUrl" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - url, err := bosClient.GeneratePresignedUrl(bucketName, objectKey, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - req, err := http.NewRequest("GET", url, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - httpClient := http.Client{} - res, err := httpClient.Do(req) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if res.StatusCode != 200 { - t.Error(util.FormatTest(method, fmt.Sprintf("status code: %v", res.StatusCode), "status code: 200")) - } - } - } - } - }) -} - -func TestAppendObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-append-object-" - method := "AppendObject" - objectKey := "append-object-from-string.txt" - str := "Hello World 你好" - contentLength := len(str) - offset := 0 - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - appendObjectResponse, err := bosClient.AppendObject(bucketName, objectKey, offset, str, nil, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if appendObjectResponse.GetETag() == "" || appendObjectResponse.GetNextAppendOffset() == "" { - t.Error(util.FormatTest(method, "etag and next append offset are not exists", "etag and next append offset")) - } else { - length, err := strconv.Atoi(appendObjectResponse.GetNextAppendOffset()) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - md5 := appendObjectResponse.GetMD5() - if md5 == "" { - t.Error(util.FormatTest(method, md5, "md5 value of object")) - } else { - offset = length - appendObjectResponse, err := bosClient.AppendObject(bucketName, objectKey, offset, []byte(str), nil, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if appendObjectResponse.GetETag() == "" || appendObjectResponse.GetNextAppendOffset() == "" { - t.Error(util.FormatTest(method, "etag and next append offset are not exists", "etag and next append offset")) - } else { - offset = length * 2 - appendObjectResponse, err := bosClient.AppendObject( - bucketName, - objectKey, - offset, - strings.NewReader(str), - &ObjectMetadata{CacheControl: "no-cache"}, - nil, - ) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if appendObjectResponse.GetETag() == "" || appendObjectResponse.GetNextAppendOffset() == "" { - t.Error(util.FormatTest(method, "etag and next append offset are not exists", "etag and next append offset")) - } else { - offset, err := strconv.Atoi(appendObjectResponse.GetNextAppendOffset()) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if offset != contentLength*3 { - t.Error(util.FormatTest(method, strconv.Itoa(offset), strconv.Itoa(contentLength*3))) - } else { - file, err := os.OpenFile(objectKey, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - defer func() { - file.Close() - os.Remove(file.Name()) - }() - - _, err = bosClient.AppendObject(bucketName, objectKey, offset, file, nil, nil) - if err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } else { - defer func() { - if err := recover(); err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } - }() - - _, err = bosClient.AppendObject(bucketName, objectKey, offset, 12, nil, nil) - } - } - } - } - } - } - } - } - }) -} - -func TestMultipartUploadFromFile(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-multipart-upload-from-file-" - method := "MultipartUploadFromFile" - objectKey := "test-multipart-upload" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - file, err := util.TempFileWithSize(1024 * 1024 * 6) - - defer func() { - if file != nil { - file.Close() - os.Remove(file.Name()) - } - }() - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - var partSize int64 = 1024 * 1024 * 2 - - completeMultipartUploadResponse, err := bosClient.MultipartUploadFromFile(bucketName, - objectKey, file.Name(), partSize) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if completeMultipartUploadResponse.ETag == "" { - t.Error(util.FormatTest(method, "etag is not exists", "etag")) - } - }) -} - -func TestAbortMultipartUpload(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-abort-multipart-upload-" - method := "AbortMultipartUpload" - objectKey := "test-multipart-upload" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - initiateMultipartUploadRequest := InitiateMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - ObjectMetadata: &ObjectMetadata{}, - } - - initiateMultipartUploadResponse, err := bosClient.InitiateMultipartUpload(initiateMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - uploadId := initiateMultipartUploadResponse.UploadId - - abortMultipartUploadRequest := AbortMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: uploadId, - } - - err = bosClient.AbortMultipartUpload(abortMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - }) -} - -func TestListParts(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-list-parts-" - objectKey := "test-list-parts" - method := "ListParts" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - initiateMultipartUploadRequest := InitiateMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - } - - initiateMultipartUploadResponse, err := bosClient.InitiateMultipartUpload(initiateMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - defer func() { - if initiateMultipartUploadResponse != nil { - abortMultipartUploadRequest := AbortMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - } - - err := bosClient.AbortMultipartUpload(abortMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }() - - files := make([]*os.File, 0) - file, err := util.TempFileWithSize(1024 * 1024 * 6) - files = append(files, file) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - defer func() { - for _, f := range files { - f.Close() - os.Remove(f.Name()) - } - }() - - fileInfo, err := file.Stat() - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - var partSize int64 = 1024 * 1024 * 5 - var totalSize int64 = fileInfo.Size() - var partCount int = int(math.Ceil(float64(totalSize) / float64(partSize))) - - var waitGroup sync.WaitGroup - parts := make([]PartSummary, 0, partCount) - - for i := 0; i < partCount; i++ { - var skipBytes int64 = partSize * int64(i) - var size int64 = int64(math.Min(float64(totalSize-skipBytes), float64(partSize))) - - tempFile, err := util.TempFile(nil, "", "") - files = append(files, tempFile) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - limitReader := io.LimitReader(file, size) - _, err = io.Copy(tempFile, limitReader) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partNumber := i + 1 - - uploadPartRequest := UploadPartRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - PartSize: size, - PartNumber: partNumber, - PartData: tempFile, - } - - waitGroup.Add(1) - - parts = append(parts, PartSummary{PartNumber: partNumber}) - - go func(partNumber int) { - defer waitGroup.Done() - - uploadPartResponse, err := bosClient.UploadPart(uploadPartRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - parts[partNumber-1].ETag = uploadPartResponse.GetETag() - }(partNumber) - } - - waitGroup.Wait() - - listPartsResponse, err := bosClient.ListParts(bucketName, objectKey, initiateMultipartUploadResponse.UploadId, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partCount = len(listPartsResponse.Parts) - - if partCount != 2 { - t.Error(util.FormatTest(method, fmt.Sprintf("part count is %d", partCount), "part count should be 2")) - } - - listPartsResponse, err = bosClient.ListPartsFromRequest( - ListPartsRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - MaxParts: 100, - PartNumberMarker: "1", - }, - nil, - ) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partCount = len(listPartsResponse.Parts) - - if partCount != 1 { - t.Error(util.FormatTest(method, fmt.Sprintf("part count is %d", partCount), "part count should be 1")) - } - - func() { - defer func() { - if err := recover(); err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } - }() - - uploadPartRequest := UploadPartRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - PartSize: 1024*1024*1024*5 + 1, - PartNumber: partCount + 1, - PartData: nil, - } - - bosClient.UploadPart(uploadPartRequest, nil) - }() - - func() { - defer func() { - if err := recover(); err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } - }() - - uploadPartRequest := UploadPartRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - PartSize: 1024 * 1024 * 1024 * 5, - PartNumber: MAX_PART_NUMBER + 1, - PartData: nil, - } - - bosClient.UploadPart(uploadPartRequest, nil) - }() - }) -} - -func TestListMultipartUploads(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-list-multipart-uploads-" - objectKey := "test-multipart-upload" - method := "ListMultipartUploads" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - initiateMultipartUploadRequest := InitiateMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - } - - initiateMultipartUploadResponse, err := bosClient.InitiateMultipartUpload(initiateMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - defer func() { - if initiateMultipartUploadResponse != nil { - abortMultipartUploadRequest := AbortMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - } - - err = bosClient.AbortMultipartUpload(abortMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }() - - listMultipartUploadsResponse, err := bosClient.ListMultipartUploads(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partCount := len(listMultipartUploadsResponse.Uploads) - - if partCount != 1 { - t.Error(util.FormatTest(method, fmt.Sprintf("part count is %d", partCount), "part count should be 1")) - } - - commonPrefixes := listMultipartUploadsResponse.GetCommonPrefixes() - - if len(commonPrefixes) != 0 { - t.Error(util.FormatTest(method, fmt.Sprintf("length of common prefixes is %d", len(commonPrefixes)), "length of common prefixes should be 0")) - } - }) -} - -func TestListMultipartUploadsFromRequest(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-list-multipart-uploads-from-request-" - objectKey := "test-multipart-upload" - method := "ListMultipartUploadsFromRequest" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - initiateMultipartUploadRequest := InitiateMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - } - - initiateMultipartUploadResponse, err := bosClient.InitiateMultipartUpload(initiateMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - defer func() { - if initiateMultipartUploadResponse != nil { - abortMultipartUploadRequest := AbortMultipartUploadRequest{ - BucketName: bucketName, - ObjectKey: objectKey, - UploadId: initiateMultipartUploadResponse.UploadId, - } - - err = bosClient.AbortMultipartUpload(abortMultipartUploadRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }() - - listMultipartUploadsRequest := ListMultipartUploadsRequest{ - BucketName: bucketName, - Delimiter: "/", - Prefix: objectKey, - MaxUploads: 100, - KeyMarker: "", - } - listMultipartUploadsResponse, err := bosClient.ListMultipartUploadsFromRequest(listMultipartUploadsRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partCount := len(listMultipartUploadsResponse.Uploads) - - if partCount != 1 { - t.Error(util.FormatTest(method, fmt.Sprintf("part count is %d", partCount), "part count should be 1")) - } - - listMultipartUploadsRequest = ListMultipartUploadsRequest{ - BucketName: bucketName, - Delimiter: "/", - Prefix: objectKey, - MaxUploads: 100, - KeyMarker: objectKey, - } - listMultipartUploadsResponse, err = bosClient.ListMultipartUploadsFromRequest(listMultipartUploadsRequest, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - return - } - - partCount = len(listMultipartUploadsResponse.Uploads) - - if partCount != 0 { - t.Error(util.FormatTest(method, fmt.Sprintf("part count is %d", partCount), "part count should be 0")) - } - }) -} - -func TestSetBucketCors(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-cors-" - method := "SetBucketCors" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketCors := BucketCors{ - CorsConfiguration: []BucketCorsItem{ - BucketCorsItem{ - AllowedOrigins: []string{"http://*", "https://*"}, - AllowedMethods: []string{"GET", "HEAD", "POST", "PUT"}, - AllowedHeaders: []string{"*"}, - AllowedExposeHeaders: []string{"ETag", "x-bce-request-id", "Content-Type"}, - MaxAgeSeconds: 3600, - }, - BucketCorsItem{ - AllowedOrigins: []string{"http://www.example.com", "www.example2.com"}, - AllowedMethods: []string{"GET", "HEAD", "DELETE"}, - AllowedHeaders: []string{"Authorization", "x-bce-test", "x-bce-test2"}, - AllowedExposeHeaders: []string{"user-custom-expose-header"}, - MaxAgeSeconds: 2000, - }, - }, - } - - if err := bosClient.SetBucketCors(bucketName, bucketCors, nil); err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestGetBucketCors(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-bucket-cors-" - method := "GetBucketCors" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketCors := BucketCors{ - CorsConfiguration: []BucketCorsItem{ - BucketCorsItem{ - AllowedOrigins: []string{"http://*", "https://*"}, - AllowedMethods: []string{"GET", "HEAD", "POST", "PUT"}, - AllowedHeaders: []string{"*"}, - AllowedExposeHeaders: []string{"ETag", "x-bce-request-id", "Content-Type"}, - MaxAgeSeconds: 3600, - }, - BucketCorsItem{ - AllowedOrigins: []string{"http://www.example.com", "www.example2.com"}, - AllowedMethods: []string{"GET", "HEAD", "DELETE"}, - AllowedHeaders: []string{"Authorization", "x-bce-test", "x-bce-test2"}, - AllowedExposeHeaders: []string{"user-custom-expose-header"}, - MaxAgeSeconds: 2000, - }, - }, - } - - if err := bosClient.SetBucketCors(bucketName, bucketCors, nil); err != nil { - t.Error(util.FormatTest(method+":SetBucketCors", err.Error(), "nil")) - } - - _, err := bosClient.GetBucketCors(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestDeleteBucketCors(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-bucket-cors-" - method := "DeleteBucketCors" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - err := bosClient.DeleteBucketCors(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestOptionsObject(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-options-object-" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - method := "OptionsObject" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, nil) - - if err != nil { - t.Error(util.FormatTest(method+":PutObject", err.Error(), "nil")) - } - - bucketCors := BucketCors{ - CorsConfiguration: []BucketCorsItem{ - BucketCorsItem{ - AllowedOrigins: []string{"http://*", "https://*"}, - AllowedMethods: []string{"GET", "HEAD", "POST", "PUT"}, - AllowedHeaders: []string{"*"}, - AllowedExposeHeaders: []string{"ETag", "x-bce-request-id", "Content-Type"}, - MaxAgeSeconds: 3600, - }, - BucketCorsItem{ - AllowedOrigins: []string{"http://www.example.com", "www.example2.com"}, - AllowedMethods: []string{"GET", "HEAD", "DELETE"}, - AllowedHeaders: []string{"Authorization", "x-bce-test", "x-bce-test2"}, - AllowedExposeHeaders: []string{"user-custom-expose-header"}, - MaxAgeSeconds: 2000, - }, - }, - } - - if err := bosClient.SetBucketCors(bucketName, bucketCors, nil); err != nil { - t.Error(util.FormatTest(method+":SetBucketCors", err.Error(), "nil")) - } - _, err = bosClient.OptionsObject(bucketName, objectKey, "http://www.example.com", "GET", "x-bce-test") - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestSetBucketLogging(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-logging-" - targetBucket := "baidubce-sdk-go-test-for-set-bucket-logging-logs" + strconv.Itoa(int(time.Now().UnixNano())) - - if len(targetBucket) > 63 { - targetBucket = targetBucket[:63] - } - - targetPrefix := "baidubce-sdk-go" - method := "SetBucketLogging" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - defer bosClient.DeleteBucket(targetBucket, nil) - - err := bosClient.CreateBucket(targetBucket, nil) - - if err != nil { - t.Error(util.FormatTest(method+":CreateBucket", err.Error(), "nil")) - } else { - err = bosClient.SetBucketLogging(bucketName, targetBucket, targetPrefix, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }) -} - -func TestGetBucketLogging(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-bucket-logging-" - targetBucket := "baidubce-sdk-go-test-for-get-bucket-logging-logs" + strconv.Itoa(int(time.Now().UnixNano())) - - if len(targetBucket) > 63 { - targetBucket = targetBucket[:63] - } - - targetPrefix := "baidubce-sdk-go" - method := "GetBucketLogging" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - defer bosClient.DeleteBucket(targetBucket, nil) - - err := bosClient.CreateBucket(targetBucket, nil) - - if err != nil { - t.Error(util.FormatTest(method+":CreateBucket", err.Error(), "nil")) - } else { - err = bosClient.SetBucketLogging(bucketName, targetBucket, targetPrefix, nil) - - if err != nil { - t.Error(util.FormatTest(method+":SetBucketLogging", err.Error(), "nil")) - } else { - bucketLogging, err := bosClient.GetBucketLogging(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if bucketLogging.Status != "enabled" { - t.Error(util.FormatTest(method, bucketLogging.Status, "enabled")) - } - } - } - }) -} - -func TestDeleteBucketLogging(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-bucket-logging-" - targetBucket := "baidubce-sdk-go-test-for-delete-bucket-logging-logs" + strconv.Itoa(int(time.Now().UnixNano())) - - if len(targetBucket) > 63 { - targetBucket = targetBucket[:63] - } - - targetPrefix := "baidubce-sdk-go" - method := "DeleteBucketLogging" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - defer bosClient.DeleteBucket(targetBucket, nil) - - err := bosClient.CreateBucket(targetBucket, nil) - - if err != nil { - t.Error(util.FormatTest(method+":CreateBucket", err.Error(), "nil")) - } else { - err := bosClient.SetBucketLogging(bucketName, targetBucket, targetPrefix, nil) - - if err != nil { - t.Error(util.FormatTest(method+":SetBucketLogging", err.Error(), "nil")) - } else { - err := bosClient.DeleteBucketLogging(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - } - }) -} - -func TestSetBucketLifecycle(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-set-bucket-lifecycle-" - method := "SetBucketLifecycle" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketLifecycle := BucketLifecycle{ - Rule: []BucketLifecycleItem{ - BucketLifecycleItem{ - Id: "1", - Status: "disabled", - Resource: []string{bucketName + "/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "2017-01-30T00:00:00Z"}, - }, - Action: BucketLifecycleItemAction{Name: "DeleteObject"}, - }, - BucketLifecycleItem{ - Id: "2", - Status: "enabled", - Resource: []string{bucketName + "/test/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "Transition", StorageClass: "STANDARD_IA"}, - }, - BucketLifecycleItem{ - Id: "3", - Status: "enabled", - Resource: []string{bucketName + "/multi/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "AbortMultipartUpload"}, - }, - }, - } - - if err := bosClient.SetBucketLifecycle(bucketName, bucketLifecycle, nil); err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - }) -} - -func TestGetBucketLifecycle(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-get-bucket-lifecycle-" - method := "GetBucketLifecycle" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketLifecycle := BucketLifecycle{ - Rule: []BucketLifecycleItem{ - BucketLifecycleItem{ - Id: "1", - Status: "disabled", - Resource: []string{bucketName + "/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "2017-01-30T00:00:00Z"}, - }, - Action: BucketLifecycleItemAction{Name: "DeleteObject"}, - }, - BucketLifecycleItem{ - Id: "2", - Status: "enabled", - Resource: []string{bucketName + "/test/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "Transition", StorageClass: "STANDARD_IA"}, - }, - BucketLifecycleItem{ - Id: "3", - Status: "enabled", - Resource: []string{bucketName + "/multi/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "AbortMultipartUpload"}, - }, - }, - } - - if err := bosClient.SetBucketLifecycle(bucketName, bucketLifecycle, nil); err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - gotBucketLifecycle, err := bosClient.GetBucketLifecycle(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - byteArrayOfBucketLifecycle, err := util.ToJson(bucketLifecycle, "rule") - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - byteArrayOfGotBucketLifecycle, err := util.ToJson(gotBucketLifecycle, "rule") - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if string(byteArrayOfBucketLifecycle) != string(byteArrayOfGotBucketLifecycle) { - t.Error(util.FormatTest(method, string(byteArrayOfBucketLifecycle), string(byteArrayOfGotBucketLifecycle))) - } - } - } - } - }) -} - -func TestDeleteBucketLifecycle(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-delete-bucket-lifecycle-" - method := "DeleteBucketLifecycle" - - around(t, method, bucketNamePrefix, "", func(bucketName string) { - bucketLifecycle := BucketLifecycle{ - Rule: []BucketLifecycleItem{ - BucketLifecycleItem{ - Id: "1", - Status: "disabled", - Resource: []string{bucketName + "/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "2017-01-30T00:00:00Z"}, - }, - Action: BucketLifecycleItemAction{Name: "DeleteObject"}, - }, - BucketLifecycleItem{ - Id: "2", - Status: "enabled", - Resource: []string{bucketName + "/test/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "Transition", StorageClass: "STANDARD_IA"}, - }, - BucketLifecycleItem{ - Id: "3", - Status: "enabled", - Resource: []string{bucketName + "/multi/*"}, - Condition: BucketLifecycleItemCondition{ - Time: BucketLifecycleItemConditionTime{DateGreaterThan: "$(lastModified)+P7D"}, - }, - Action: BucketLifecycleItemAction{Name: "AbortMultipartUpload"}, - }, - }, - } - - if err := bosClient.SetBucketLifecycle(bucketName, bucketLifecycle, nil); err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - gotBucketLifecycle, err := bosClient.GetBucketLifecycle(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if len(gotBucketLifecycle.Rule) != 3 { - t.Error(util.FormatTest(method, strconv.Itoa(len(gotBucketLifecycle.Rule)), "3")) - } else { - err = bosClient.DeleteBucketLifecycle(bucketName, nil) - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else { - _, err := bosClient.GetBucketLifecycle(bucketName, nil) - if err == nil { - t.Error(util.FormatTest(method, "nil", "error")) - } else if bceError, ok := err.(*bce.Error); ok && bceError.StatusCode != 404 { - t.Error(util.FormatTest(method, err.Error(), "bce.Error with status code 404")) - } - } - } - } - }) -} - -func TestPubObjectBySTS(t *testing.T) { - bucketNamePrefix := "baidubce-sdk-go-test-for-put-object-by-sts-" - method := "PutObject" - objectKey := "put-object-from-string.txt" - str := "Hello World 你好" - - around(t, method, bucketNamePrefix, objectKey, func(bucketName string) { - req := bce.SessionTokenRequest{ - DurationSeconds: 600, - Id: "ef5a4b19192f4931adcf0e12f82795e2", - AccessControlList: []bce.AccessControlListItem{ - bce.AccessControlListItem{ - Service: "bce:bos", - Region: bceConfig.GetRegion(), - Effect: "Allow", - Resource: []string{bucketName + "/*"}, - Permission: []string{"READ", "WRITE"}, - }, - }, - } - - sessionTokenResponse, err := bosClient.GetSessionToken(req, nil) - - if err != nil { - t.Error(util.FormatTest(method+":GetSessionToken", err.Error(), "nil")) - } else { - option := &bce.SignOption{ - Credentials: bce.NewCredentials(sessionTokenResponse.AccessKeyId, sessionTokenResponse.SecretAccessKey), - Headers: map[string]string{"x-bce-security-token": sessionTokenResponse.SessionToken}, - } - - _, err := bosClient.PutObject(bucketName, objectKey, str, nil, option) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } - } - }) -} - -func around(t *testing.T, method, bucketNamePrefix string, objectKey interface{}, f func(string)) { - bucketName := bucketNamePrefix + strconv.Itoa(int(time.Now().UnixNano())) - if len(bucketName) > 63 { - bucketName = bucketName[:63] - } - - err := bosClient.CreateBucket(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at creating bucket", err.Error(), "nil")) - } else { - defer func() { - if key, ok := objectKey.(string); ok { - if key != "" { - err = bosClient.DeleteObject(bucketName, key, nil) - - if bceError, ok := err.(*bce.Error); ok && bceError.StatusCode != 404 { - t.Error(util.FormatTest(method+" at deleting object", err.Error(), "nil")) - } - } - } else if keys, ok := objectKey.([]string); ok { - deleteMultipleObjectsResponse, err := bosClient.DeleteMultipleObjects(bucketName, keys, nil) - - if err != nil { - t.Error(util.FormatTest(method, err.Error(), "nil")) - } else if deleteMultipleObjectsResponse != nil { - str := "" - - for _, deleteMultipleObjectsError := range deleteMultipleObjectsResponse.Errors { - if deleteMultipleObjectsError.Code != "NoSuchKey" { - str += deleteMultipleObjectsError.Error() - } - } - - if str != "" { - t.Error(util.FormatTest(method, str, "empty string")) - } - } - } else { - t.Error(util.FormatTest(method, "objectKey is not valid", "objectKey should be string or []string")) - } - - err = bosClient.DeleteBucket(bucketName, nil) - - if err != nil { - t.Error(util.FormatTest(method+" at deleting bucket", err.Error(), "nil")) - } - }() - - if f != nil { - f(bucketName) - } - } -} diff --git a/pkg/sdk/cce/client_test.go b/pkg/sdk/cce/client_test.go deleted file mode 100644 index c85a31e..0000000 --- a/pkg/sdk/cce/client_test.go +++ /dev/null @@ -1,157 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 cce - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" -) - -var credentials, _ = bce.NewCredentialsFromFile("../aksk-test.json") - -//var bceConfig = bce.NewConfig(credentials) -var bceConfig = &bce.Config{ - Credentials: credentials, - Checksum: true, -} -var cceConfig = NewConfig(bceConfig) -var cceClient = NewClient(cceConfig) - -func ClusterHandler() http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("/v1/instance", func(w http.ResponseWriter, r *http.Request) { - handleInstanceList(w, r) - }) - mux.HandleFunc("/v2/instance/", func(w http.ResponseWriter, r *http.Request) { - handleDescribeInstance(w, r) - }) - mux.HandleFunc("/v1/cluster", func(w http.ResponseWriter, r *http.Request) { - handleScaleUpCluster(w, r) - }) - - return mux -} - -func handleInstanceList(w http.ResponseWriter, r *http.Request) { - switch r.Method { - case http.MethodGet: - w.Header().Set("Content-Type", "application/json") - response := `{ - "instances": [ - { - "id": "i-IyWRtII7", - "name": "instance-j93wzbn1", - "internalIp": "192.168.6.15", - "zoneName": "cn-bj-a", - "vpcId": "vpc-9999" - }, - { - "id": "i-YufwpQAe", - "name": "instance-luz2ef4l-1", - "internalIp": "192.168.0.25", - "zoneName": "cn-bj-a", - "vpcId": "vpc-i80sab3o" - } - ] -}` - fmt.Fprint(w, response) - } -} - -func handleDescribeInstance(w http.ResponseWriter, r *http.Request) { - _, id := path.Split(r.URL.Path) - if id != "i-YufwpQAe" { - return - } - switch r.Method { - case http.MethodGet: - w.Header().Set("Content-Type", "application/json") - response := `{ - "instance": { - "id": "i-YufwpQAe", - "createTime": "2015-07-09T10:27:15Z", - "name": "instance-luz2ef4l-1", - "status": "Stopped", - "desc": "console", - "paymentTiming":"Postpaid", - "expireTime": null, - "internalIp": "192.168.0.25", - "publicIp": "-", - "cpuCount": 1, - "memoryCapacityInGB": 1, - "localDiskSizeInGB": 0, - "networkCapacityInMbps": 5, - "imageId": "m-nky7qeom", - "placementPolicy": "default", - "zoneName": "cn-bj-a", - "subnetId": "sbn-oioiadda", - "vpcId": "vpc-i80sab3o" - } -}` - fmt.Fprint(w, response) - } -} - -func handleScaleUpCluster(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - query := r.URL.Query() - act := query["scalingUp"] - if len(act) > 0 { - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &ScaleUpClusterArgs{} - json.Unmarshal(body, args) - if args.ClusterID != "c-NqYwWEhu" { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "clusterUuid": "c-NqYwWEhu", - "orderId": [ - "8d58c20f46294a7ea4922928db1fddea" - ] - }` - fmt.Fprint(w, response) - return - } - act = query["scalingDown"] - if len(act) > 0 { - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &ScaleDownClusterArgs{} - json.Unmarshal(body, args) - if args.ClusterID != "c-NqYwWEhu" || args.AuthCode != "123456" { - w.WriteHeader(http.StatusBadRequest) - return - } - - w.WriteHeader(200) - return - } - w.WriteHeader(400) -} diff --git a/pkg/sdk/cce/cluster_test.go b/pkg/sdk/cce/cluster_test.go deleted file mode 100644 index f4ee8be..0000000 --- a/pkg/sdk/cce/cluster_test.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 cce - -import ( - "fmt" - "net/http/httptest" - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/util" -) - -func TestListInstances(t *testing.T) { - ts := httptest.NewServer(ClusterHandler()) - defer ts.Close() - cceClient.Endpoint = ts.URL - cceClient.SetDebug(true) - list, err := cceClient.ListInstances("a") - - if err != nil { - t.Error(util.FormatTest("ListInstances", err.Error(), "nil")) - } - for _, ins := range list { - fmt.Println(ins.VpcId) - } -} - -func TestScaleUp(t *testing.T) { - ts := httptest.NewServer(ClusterHandler()) - defer ts.Close() - cceClient.Endpoint = ts.URL - cceClient.SetDebug(true) - args := &ScaleUpClusterArgs{ - ClusterID: "c-NqYwWEhu", - OrderContent: OrderContent{ - Items: []OrderItem{ - OrderItem{ - Config: BccOrderConfig{ - CPU: 100, - }, - }, - }, - }, - } - res, err := cceClient.ScaleUpCluster(args) - - if err != nil { - t.Fatalf("ScaleUpCluster fail: %v", err) - } - if res.ClusterID != "c-NqYwWEhu" { - t.Fatalf("ScaleUpCluster ClusterID fail") - } -} - -func TestScaleDown(t *testing.T) { - ts := httptest.NewServer(ClusterHandler()) - defer ts.Close() - cceClient.Endpoint = ts.URL - cceClient.SetDebug(true) - args := &ScaleDownClusterArgs{ - ClusterID: "c-NqYwWEhu", - AuthCode: "123456", - } - - err := cceClient.ScaleDownCluster(args) - - if err != nil { - t.Fatalf("ScaleDownCluster fail: %v", err) - } - -} diff --git a/pkg/sdk/clientset/clientset_test.go b/pkg/sdk/clientset/clientset_test.go deleted file mode 100644 index 0ce949a..0000000 --- a/pkg/sdk/clientset/clientset_test.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 clientset - -import ( - "testing" - - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" -) - -var credentials, _ = bce.NewCredentialsFromFile("../aksk-test.json") - -func TestNewFromConfig(t *testing.T) { - cfg, err := bce.NewConfigFromFile("../aksk-test.json") - if err != nil { - t.Error(err) - } else { - cs, err := NewFromConfig(cfg) - if err != nil { - t.Error(err) - } else { - if cs.Bcc().AccessKeyID != credentials.AccessKeyID { - t.Error("ak error") - } - if cs.Blb().AccessKeyID != credentials.AccessKeyID { - t.Error("ak error") - } - if cs.Eip().AccessKeyID != credentials.AccessKeyID { - t.Error("ak error") - } - } - } -} diff --git a/pkg/sdk/eip/client_test.go b/pkg/sdk/eip/client_test.go deleted file mode 100644 index 5a4e845..0000000 --- a/pkg/sdk/eip/client_test.go +++ /dev/null @@ -1,165 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 eip - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - - "io/ioutil" - - "time" - - "github.com/gorilla/mux" - "k8s.io/cloud-provider-baiducloud/pkg/sdk/bce" -) - -var ( - testHTTPServer *httptest.Server - eipClient *Client -) - -func init() { - var credentials, _ = bce.NewCredentialsFromFile("../aksk-test.json") - - //var bceConfig = bce.NewConfig(credentials) - var bceConfig = &bce.Config{ - Credentials: credentials, - Checksum: true, - Timeout: 5 * time.Second, - Region: os.Getenv("BOS_REGION"), - } - var bccConfig = NewConfig(bceConfig) - eipClient = NewEIPClient(bccConfig) - // eipClient.SetDebug(true) - r := mux.NewRouter() - r.HandleFunc("/v1/eip", handleGetEips).Methods("GET") - r.HandleFunc("/v1/eip/{ip}", handleDeleteEip).Methods("DELETE") - r.HandleFunc("/v1/eip/{ip}", handleUnbindEip).Methods("PUT") - r.HandleFunc("/v1/eip", handleCreateEip).Methods("POST") - testHTTPServer = httptest.NewServer(r) - eipClient.Endpoint = testHTTPServer.URL -} - -func handleCreateEip(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - body, err := ioutil.ReadAll(r.Body) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - return - } - args := &CreateEipArgs{} - json.Unmarshal(body, args) - if args.Billing.BillingMethod != "ByTraffic" { - w.WriteHeader(http.StatusBadRequest) - return - } - response := `{ - "eip":"180.181.3.133" -}` - fmt.Fprint(w, response) -} - -func handleGetEips(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - response := `{ - "eipList": [ - { - "name":"eip-xrllt5M-1", - "eip": "180.181.3.133", - "status":"binded", - "instanceType": "BCC", - "instanceId": "i-IyWRtII7", - "shareGroupId": "eg-0c31c93a", - "eipInstanceType": "shared", - "bandwidthInMbps": 5, - "paymentTiming":"Prepaid", - "billingMethod":null, - "createTime":"2016-03-08T08:13:09Z", - "expireTime":"2016-04-08T08:13:09Z" - }, - { - "name":"eip-scewa1M-1", - "eip": "180.181.3.134", - "status":"binded", - "instanceType": "BCC", - "instanceId": "i-KjdgweC4", - "shareGroupId": null, - "eipInstanceType": "normal", - "bandwidthInMbps": 1, - "paymentTiming":"Postpaid", - "billingMethod":"ByTraffic", - "createTime":"2016-03-08T08:13:09Z", - "expireTime":null - } - ], - "marker":"eip-DCB50385", - "isTruncated": true, - "nextMarker": "eip-DCB50387", - "maxKeys": 2 -}` - fmt.Fprint(w, response) -} - -func handleDeleteEip(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - vars := mux.Vars(r) - ip := vars["ip"] - if ip == "180.76.154.83" { - w.WriteHeader(200) - } else { - w.WriteHeader(400) - } - -} - -func handleUnbindEip(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - query := r.URL.Query() - act := query["bind"] - if len(act) > 0 { - vars := mux.Vars(r) - ip := vars["ip"] - if ip == "180.76.247.62" { - w.WriteHeader(200) - return - } - } - act = query["unbind"] - if len(act) > 0 { - vars := mux.Vars(r) - ip := vars["ip"] - if ip == expectUnbindEip.Ip { - w.WriteHeader(200) - return - } - } - - act = query["resize"] - if len(act) > 0 { - vars := mux.Vars(r) - ip := vars["ip"] - if ip == expectResizeEip.Ip { - w.WriteHeader(200) - return - } - } - w.WriteHeader(400) -} diff --git a/pkg/sdk/eip/eip_test.go b/pkg/sdk/eip/eip_test.go deleted file mode 100644 index 5701c27..0000000 --- a/pkg/sdk/eip/eip_test.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright 2018 The Kubernetes 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 eip - -import ( - "testing" -) - -func TestCreateEip(t *testing.T) { - bill := &Billing{ - PaymentTiming: "Postpaid", - BillingMethod: "ByTraffic", - } - args := &CreateEipArgs{ - BandwidthInMbps: 998, - Billing: bill, - Name: "k8stestcgy", - } - ip, err := eipClient.CreateEip(args) - if err != nil { - t.Error(err) - } - if ip != "180.181.3.133" { - t.Error("ip error") - } -} - -var expectResizeEip = &ResizeEipArgs{ - BandwidthInMbps: 111, - Ip: "180.76.242.209", -} - -func TestResizeEip(t *testing.T) { - err := eipClient.ResizeEip(expectResizeEip) - if err != nil { - t.Error(err) - } -} - -var expectBindEip = &BindEipArgs{ - Ip: "180.76.247.62", - InstanceType: "BCC", - InstanceId: "i-VAEyKKTh", -} -var expectUnbindEip = &EipArgs{ - Ip: "180.76.154.83", -} - -func TestBindEip(t *testing.T) { - err := eipClient.BindEip(expectBindEip) - if err != nil { - t.Error(err) - } -} - -func TestUnbindEip(t *testing.T) { - err := eipClient.UnbindEip(expectUnbindEip) - if err != nil { - t.Error(err) - } -} - -func TestDeleteEip(t *testing.T) { - err := eipClient.DeleteEip(expectUnbindEip) - if err != nil { - t.Error(err) - } -} -func TestGetEips(t *testing.T) { - eips, err := eipClient.GetEips(nil) - if err != nil { - t.Error(err) - } - for _, eip := range eips { - if eip.Eip != "180.181.3.133" && eip.Eip != "180.181.3.134" { - t.Fatal("eip errpr") - } - } -} diff --git a/pkg/sdk/util/mime_types_test.go b/pkg/sdk/util/mime_types_test.go deleted file mode 100644 index 2f8220e..0000000 --- a/pkg/sdk/util/mime_types_test.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2018 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package util - -import ( - "testing" -) - -func TestGuessMimeType(t *testing.T) { - expected := "image/png" - result := GuessMimeType("examples/test.png") - - if expected != result { - t.Error(FormatTest("GuessMimeType", result, expected)) - } - - expected = "image/png" - result = GuessMimeType(".png") - - if expected != result { - t.Error(FormatTest("GuessMimeType", result, expected)) - } - - expected = "application/octet-stream" - result = GuessMimeType("png") - - if expected != result { - t.Error(FormatTest("GuessMimeType", result, expected)) - } - - expected = "application/octet-stream" - result = GuessMimeType("examples/test") - - if expected != result { - t.Error(FormatTest("GuessMimeType", result, expected)) - } -} diff --git a/pkg/sdk/util/util_test.go b/pkg/sdk/util/util_test.go deleted file mode 100644 index a6d6c44..0000000 --- a/pkg/sdk/util/util_test.go +++ /dev/null @@ -1,752 +0,0 @@ -/* -Copyright 2018 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package util - -import ( - "bufio" - "fmt" - "io/ioutil" - "os" - "path" - "strconv" - "strings" - "testing" - "time" -) - -func TestGetURL(t *testing.T) { - expected := "http://bos.cn-n1.baidubce.com/v1/example/测试" - url := GetURL("", "bos.cn-n1.baidubce.com", "v1/example/测试", nil) - - if url != expected { - t.Error(FormatTest("GetURL", url, expected)) - } - - url = GetURL("", "bos.cn-n1.baidubce.com", "/v1/example/测试", nil) - - if url != expected { - t.Error(FormatTest("GetURL", url, expected)) - } - - expected = expected + "?id=123&name=abc" - params := map[string]string{"id": "123", "name": "abc"} - url = GetURL("", "bos.cn-n1.baidubce.com", "v1/example/测试", params) - - if url != expected { - t.Error(FormatTest("GetURL", url, expected)) - } - - expected = "https://bos.cn-n1.baidubce.com/v1/example/测试" + "?id=123&name=abc" - url = GetURL("https", "bos.cn-n1.baidubce.com", "v1/example/测试", params) - - if url != expected { - t.Error(FormatTest("GetURL", url, expected)) - } -} - -func TestGetURIPath(t *testing.T) { - const URI string = "http://bos.cn-n1.baidubce.com/v1/example/测试" - expected := "/v1/example/测试" - path := GetURIPath(URI) - - if path != expected { - t.Error(FormatTest("GetURIPath", path, expected)) - } -} - -func TestURIEncodeExceptSlash(t *testing.T) { - const URI string = "http://bos.cn-n1.baidubce.com/v1/example/测试" - expected := "/v1/example/%E6%B5%8B%E8%AF%95" - path := GetURIPath(URI) - path = URIEncodeExceptSlash(path) - - if path != expected { - t.Error(FormatTest("URIEncodeExceptSlash", path, expected)) - } -} - -func TestHmacSha256Hex(t *testing.T) { - expected := "6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a" - encrypted := HmacSha256Hex("key", "message") - - if encrypted != expected { - t.Error(FormatTest("HmacSha256Hex", encrypted, expected)) - } -} - -func TestGetMD5(t *testing.T) { - expected := "de22e061b93b832dd8af907ca9002fd7" - result := GetMD5("baidubce-sdk-go", false) - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - - result = GetMD5([]byte("baidubce-sdk-go"), false) - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - - result = GetMD5(strings.NewReader("baidubce-sdk-go"), false) - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - - f, err := TempFile([]byte("baidubce-sdk-go"), "", "") - - if err != nil { - t.Error(FormatTest("GetMD5", err.Error(), "nil")) - } else { - defer func() { - f.Close() - os.Remove(f.Name()) - }() - - result = GetMD5(f, false) - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - } - - result = GetMD5(bufio.NewReader(strings.NewReader("baidubce-sdk-go")), false) - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - - result = GetMD5("baidubce-sdk-go", true) - expected = "3iLgYbk7gy3Yr5B8qQAv1w==" - - if result != expected { - t.Error(FormatTest("GetMD5", result, expected)) - } - - defer func() { - if err := recover(); err == nil { - t.Error(FormatTest("GetMD5", "nil", "error")) - } - }() - - result = GetMD5(1, false) -} - -func TestGetSha256(t *testing.T) { - expected := "b39aa8e24bcfc4b20c77f7ab36021e5c23cce79df034279ca9991e0472368b89" - result := GetSha256("baidubce-sdk-go") - - if result != expected { - t.Error(FormatTest("GetSha256", result, expected)) - } - - result = GetSha256([]byte("baidubce-sdk-go")) - - if result != expected { - t.Error(FormatTest("GetSha256", result, expected)) - } - - result = GetSha256(strings.NewReader("baidubce-sdk-go")) - - if result != expected { - t.Error(FormatTest("GetSha256", result, expected)) - } - - f, err := TempFile([]byte("baidubce-sdk-go"), "", "") - - if err != nil { - t.Error(FormatTest("GetSha256", err.Error(), "nil")) - } else { - defer func() { - f.Close() - os.Remove(f.Name()) - }() - - result = GetSha256(f) - - if result != expected { - t.Error(FormatTest("GetSha256", result, expected)) - } - } - - result = GetSha256(bufio.NewReader(strings.NewReader("baidubce-sdk-go"))) - - if result != expected { - t.Error(FormatTest("GetSha256", result, expected)) - } - - defer func() { - if err := recover(); err == nil { - t.Error(FormatTest("GetSha256", "nil", "error")) - } - }() - - result = GetSha256(1) -} - -func TestBase64Encode(t *testing.T) { - expected := "YmFpZHViY2Utc2RrLWdv" - result := Base64Encode([]byte("baidubce-sdk-go")) - - if result != expected { - t.Error(FormatTest("Base64Encode", result, expected)) - } -} - -func TestContains(t *testing.T) { - expected := true - arr := []string{"abc", "XYz"} - result := Contains(arr, "abc", true) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = false - result = Contains(arr, "Abc", false) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = true - result = Contains(arr, "xyz", true) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - result = Contains(arr, "Xyz", true) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - result = Contains(arr, "xYZ", true) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - result = Contains(arr, "XYZ", true) - - if result != expected { - t.Error(FormatTest("Contains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } -} - -func TestMapContains(t *testing.T) { - expected := true - m := map[string]string{"id": "123", "name": "Matt"} - result := MapContains(m, func(key, value string) bool { - return key == "id" - }) - - if result != expected { - t.Error(FormatTest("MapContains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - result = MapContains(m, func(key, value string) bool { - return value == "123" - }) - - if result != expected { - t.Error(FormatTest("MapContains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = false - result = MapContains(m, func(key, value string) bool { - return value == "matt" - }) - - if result != expected { - t.Error(FormatTest("MapContains", strconv.FormatBool(result), strconv.FormatBool(expected))) - } -} - -func TestGetMapKey(t *testing.T) { - expected := "id" - m := map[string]string{"id": "123", "Name": "Matt"} - result := GetMapKey(m, "id", true) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } - - result = GetMapKey(m, "id", false) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } - - result = GetMapKey(m, "Id", true) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } - - expected = "" - result = GetMapKey(m, "Id", false) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } - - expected = "" - result = GetMapKey(m, "age", true) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } - - expected = "" - result = GetMapKey(m, "age", false) - - if result != expected { - t.Error(FormatTest("GetMapKey", result, expected)) - } -} - -func TestGetMapValue(t *testing.T) { - expected := "123" - m := map[string]string{"id": "123", "Name": "Matt"} - result := GetMapValue(m, "id", true) - - if result != expected { - t.Error(FormatTest("GetMapValue", result, expected)) - } - - result = GetMapValue(m, "id", false) - - if result != expected { - t.Error(FormatTest("GetMapValue", result, expected)) - } - - result = GetMapValue(m, "Id", true) - - if result != expected { - t.Error(FormatTest("GetMapValue", result, expected)) - } - - expected = "" - result = GetMapValue(m, "Id", false) - - if result != expected { - t.Error(FormatTest("GetMapValue", result, expected)) - } -} - -func TestTimeToUTCString(t *testing.T) { - expected := "2015-11-16T15:33:15Z" - datetime, _ := time.Parse(time.RFC1123, "Mon, 16 Nov 2015 15:33:15 CST") - _, offset := datetime.Zone() - offset = offset / 3600 - datetime = datetime.Add(time.Duration(offset) * time.Hour) - utc := TimeToUTCString(datetime) - - if utc != expected { - t.Error(FormatTest("TimeToUTCString", utc, expected)) - } -} - -func TestTimeStringToRFC1123(t *testing.T) { - expected := "Mon, 16 Nov 2015 07:33:15 UTC" - result := TimeStringToRFC1123("2015-11-16T07:33:15Z") - - if result != expected { - t.Error(FormatTest("TimeStringToRFC1123", result, expected)) - } - - defer func() { - if err := recover(); err == nil { - t.Error(FormatTest("TimeStringToRFC1123", "nil", "error")) - } - }() - - TimeStringToRFC1123("Invalid") -} - -func TestHostToURL(t *testing.T) { - expected := "http://bj.bcebos.com" - host := "bj.bcebos.com" - url := HostToURL(host, "http") - - if url != expected { - t.Error(FormatTest("HostToURL", url, expected)) - } - - host = "http://bj.bcebos.com" - url = HostToURL(host, "http") - - if url != expected { - t.Error(FormatTest("HostToURL", url, expected)) - } - - host = "bj.bcebos.com" - url = HostToURL(host, "") - - if url != expected { - t.Error(FormatTest("HostToURL", url, expected)) - } - - host = "http://bj.bcebos.com" - url = HostToURL(host, "") - - if url != expected { - t.Error(FormatTest("HostToURL", url, expected)) - } -} - -func TestToCanonicalQueryString(t *testing.T) { - expected := "" - encodedQueryString := ToCanonicalQueryString(nil) - - if encodedQueryString != expected { - t.Error(FormatTest("ToCanonicalQueryString", encodedQueryString, expected)) - } - - expected = "text10=test&text1=%E6%B5%8B%E8%AF%95&text=" - params := map[string]string{ - "text": "", - "text1": "测试", - "text10": "test", - } - encodedQueryString = ToCanonicalQueryString(params) - - if encodedQueryString != expected { - t.Error(FormatTest("ToCanonicalQueryString", encodedQueryString, expected)) - } -} - -func TestToCanonicalHeaderString(t *testing.T) { - expected := strings.Join([]string{ - "content-length:8", - "content-md5:0a52730597fb4ffa01fc117d9e71e3a9", - "content-type:text%2Fplain", - "host:bj.bcebos.com", - "x-bce-date:2015-04-27T08%3A23%3A49Z", - }, "\n") - - header := map[string]string{ - "Host": "bj.bcebos.com", - "Content-Type": "text/plain", - "Content-Length": "8", - "Content-Md5": "0a52730597fb4ffa01fc117d9e71e3a9", - "x-bce-date": "2015-04-27T08:23:49Z", - } - - canonicalHeader := ToCanonicalHeaderString(header) - - if canonicalHeader != expected { - t.Error(FormatTest("ToCanonicalHeaderString", canonicalHeader, expected)) - } -} - -func TestURLEncode(t *testing.T) { - expected := "test-%E6%B5%8B%E8%AF%95" - result := URLEncode("test-测试") - - if result != expected { - t.Error(FormatTest("URLEncode", result, expected)) - } -} - -func TestSliceToLower(t *testing.T) { - expected := "name age" - arr := []string{"Name", "Age"} - SliceToLower(arr) - - result := fmt.Sprintf("%s %s", arr[0], arr[1]) - - if result != expected { - t.Error(FormatTest("SliceToLower", result, expected)) - } -} - -func TestMapKeyToLower(t *testing.T) { - expected := "name gender" - m := map[string]string{"Name": "guoyao", "Gender": "male"} - MapKeyToLower(m) - - result := "" - - if _, ok := m["name"]; ok { - result += "name" - } - - if _, ok := m["gender"]; ok { - result += " gender" - } - - if result != expected { - t.Error(FormatTest("MapKeyToLower", result, expected)) - } -} - -func TestToMap(t *testing.T) { - expected := "guoyao:10" - - str := "{\"Name\": \"guoyao\", \"Age\": \"10\", \"Gender\": \"male\"}" - m, err := ToMap(str, "Name", "Age") - - if err != nil { - t.Error(FormatTest("ToMap", err.Error(), "nil")) - } else { - result := fmt.Sprintf("%s:%v", m["Name"], m["Age"]) - - if result != expected { - t.Error(FormatTest("ToMap", result, expected)) - } - } - - byteArray := []byte(str) - m, err = ToMap(byteArray, "Name", "Age") - - if err != nil { - t.Error(FormatTest("ToMap", err.Error(), "nil")) - } else { - result := fmt.Sprintf("%s:%v", m["Name"], m["Age"]) - - if result != expected { - t.Error(FormatTest("ToMap", result, expected)) - } - } - - p := struct { - Name string - Age int - Gender string - }{"guoyao", 10, "male"} - - m, err = ToMap(p, "Name", "Age") - - if err != nil { - t.Error(FormatTest("ToMap", err.Error(), "nil")) - } else { - result := fmt.Sprintf("%s:%v", m["Name"], m["Age"]) - - if result != expected { - t.Error(FormatTest("ToMap", result, expected)) - } - } - - m, err = ToMap(1) - - if err == nil { - t.Error(FormatTest("ToMap", "nil", "error")) - } -} - -func TestToJson(t *testing.T) { - p := struct { - Name string `json:"name"` - Age int `json:"age"` - Gender string `json:"gender"` - }{"guoyao", 10, "male"} - - byteArray, err := ToJson(p) - - if err != nil { - t.Error(FormatTest("ToMap", err.Error(), "nil")) - } else { - expected := "{\"name\":\"guoyao\",\"age\":10,\"gender\":\"male\"}" - result := string(byteArray) - - if result != expected { - t.Error(FormatTest("ToMap", result, expected)) - } - } - - byteArray, err = ToJson(p, "name", "age") - - if err != nil { - t.Error(FormatTest("ToMap", err.Error(), "nil")) - } else { - expected := "{\"age\":10,\"name\":\"guoyao\"}" - result := string(byteArray) - - if result != expected { - t.Error(FormatTest("ToMap", result, expected)) - } - } - - byteArray, err = ToJson(1, "name") - - if err == nil { - t.Error(FormatTest("ToJson", "nil", "error")) - } -} - -func TestCheckFileExists(t *testing.T) { - expected := true - result := CheckFileExists("util_test.go") - - if result != expected { - t.Error(FormatTest("CheckFileExists", strconv.FormatBool(result), strconv.FormatBool(expected))) - } - - expected = false - result = CheckFileExists("util_test_2.go") - - if result != expected { - t.Error(FormatTest("CheckFileExists", strconv.FormatBool(result), strconv.FormatBool(expected))) - } -} - -func TestTempFileWithSize(t *testing.T) { - var size int64 = 1024 - f, err := TempFileWithSize(size) - - defer func() { - f.Close() - os.Remove(f.Name()) - }() - - if err != nil { - t.Error(FormatTest("TempFileWithSize", err.Error(), "nil")) - } else { - stat, err := f.Stat() - - if err != nil { - t.Error(FormatTest("TempFileWithSize", err.Error(), "nil")) - } else if stat.Size() != size { - t.Error(FormatTest("TempFileWithSize", strconv.FormatInt(stat.Size(), 10), strconv.FormatInt(size, 10))) - } - } -} - -func TestTempFile(t *testing.T) { - content := "hello" - f, err := TempFile([]byte(content), "", "") - - defer func() { - f.Close() - os.Remove(f.Name()) - }() - - if err != nil { - t.Error(FormatTest("TempFile", err.Error(), "nil")) - } else { - byteArray, err := ioutil.ReadAll(f) - - if err != nil { - t.Error(FormatTest("TempFile", err.Error(), "nil")) - } else if string(byteArray) != content { - t.Error(FormatTest("TempFile", string(byteArray), content)) - } - } - - pwd, err := os.Getwd() - - if err != nil { - t.Error(FormatTest("TempFile", err.Error(), "nil")) - } else { - content = "world" - dir := path.Join(pwd, "guoyao") - f2, err := TempFile([]byte(content), dir, "temp") - - defer func() { - f2.Close() - os.RemoveAll(dir) - }() - - if err != nil { - t.Error(FormatTest("TempFile", err.Error(), "nil")) - } else { - byteArray, err := ioutil.ReadAll(f2) - - if err != nil { - t.Error(FormatTest("TempFile", err.Error(), "nil")) - } else if string(byteArray) != content { - t.Error(FormatTest("TempFile", string(byteArray), content)) - } - } - } -} - -func TestHomeDir(t *testing.T) { - home, err := HomeDir() - - if err != nil { - t.Error(FormatTest("HomeDir", err.Error(), "nil")) - } else if home == "" { - t.Error(FormatTest("HomeDir", home, "non empty path")) - } -} - -func TestDirUnix(t *testing.T) { - home, err := dirUnix() - - if err != nil { - t.Error(FormatTest("dirUnix", err.Error(), "nil")) - } else if home == "" { - t.Error(FormatTest("dirUnix", home, "non empty path")) - } else { - os.Setenv("HOME", "") - home2, err := dirUnix() - os.Setenv("HOME", home) - - if err != nil { - t.Error(FormatTest("dirUnix", err.Error(), "nil")) - } else if home2 == "" { - t.Error(FormatTest("dirUnix", home2, "non empty path")) - } - } -} - -func TestDirWindows(t *testing.T) { - home, err := dirWindows() - - if err != nil { - t.Error(FormatTest("dirWindows", err.Error(), "nil")) - } else if home == "" { - t.Error(FormatTest("dirWindows", home, "non empty path")) - } else { - os.Setenv("HOME", "") - os.Setenv("USERPROFILE", "C:\\Users\\guoyao") - home2, err := dirWindows() - os.Setenv("HOME", home) - os.Setenv("USERPROFILE", "") - - if err != nil { - t.Error(FormatTest("dirWindows", err.Error(), "nil")) - } else if home2 == "" { - t.Error(FormatTest("dirWindows", home2, "non empty path")) - } - } -} - -func TestDebug(t *testing.T) { - Debug("title", "message") -} - -func TestFormatTest(t *testing.T) { - expected := "funcName failed. Got a, expected b" - str := FormatTest("funcName", "a", "b") - - if str != expected { - t.Error(FormatTest("FormatTest", str, expected)) - } -} - -func TestCreateRandomString(t *testing.T) { - for i := 0; i < 10; i++ { - s := CreateRandomString() - t.Logf("Generated Random String: %s", s) - } -}