From 8648527445c1eb7200fcac32ca119f4ce4c48680 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Fri, 22 Apr 2022 11:42:19 +0530 Subject: [PATCH 01/13] Add foundation and client unit tests --- client/client_test.go | 135 ++++++++++++++++++++++- client/foundation/foundation_api_test.go | 53 +++++++++ 2 files changed, 187 insertions(+), 1 deletion(-) create mode 100644 client/foundation/foundation_api_test.go diff --git a/client/client_test.go b/client/client_test.go index 7ade16eb4..95d247a9b 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -38,7 +38,7 @@ func TestNewClient(t *testing.T) { t.Errorf("Unexpected Error: %v", err) } - expectedURL := fmt.Sprintf(defaultBaseURL, "https", "foo.com") + expectedURL := fmt.Sprintf(defaultBaseURL, httpsPrefix, "foo.com") if c.BaseURL == nil || c.BaseURL.String() != expectedURL { t.Errorf("NewClient BaseURL = %v, expected %v", c.BaseURL, expectedURL) @@ -49,6 +49,23 @@ func TestNewClient(t *testing.T) { } } +func TestNewBaseClient(t *testing.T) { + c, err := NewBaseClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testAbsolutePath, true) + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + expectedURL := fmt.Sprintf(defaultBaseURL, httpPrefix, "foo.com") + + if c.BaseURL == nil || c.BaseURL.String() != expectedURL { + t.Errorf("NewBaseClient BaseURL = %v, expected %v", c.BaseURL, expectedURL) + } + + if c.AbsolutePath != testAbsolutePath { + t.Errorf("NewBaseClient UserAgent = %v, expected %v", c.AbsolutePath, testAbsolutePath) + } +} + func TestNewRequest(t *testing.T) { c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, false) @@ -73,6 +90,122 @@ func TestNewRequest(t *testing.T) { } } +func TestNewUnAuthRequest(t *testing.T) { + c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, true) + + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") + inBody, outBody := map[string]interface{}{"name": "bar"}, `{"name":"bar"}`+"\n" + + req, _ := c.NewUnAuthRequest(context.TODO(), http.MethodPost, inURL, inBody) + + // test relative URL was expanded + if req.URL.String() != outURL { + t.Errorf("NewUnAuthRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) + } + + // test body was JSON encoded + body, _ := ioutil.ReadAll(req.Body) + if string(body) != outBody { + t.Errorf("NewUnAuthRequest(%v) Body = %v, expected %v", inBody, string(body), outBody) + } + + // test headers. Authorization header shouldn't exist + if _, ok := req.Header["Authorization"]; ok { + t.Errorf("Unexpected Authorization header obtained in request from NewUnAuthRequest()") + } + inHeaders := map[string]string{ + "Content-Type": mediaType, + "Accept": mediaType, + "User-Agent": testUserAgent, + } + for k, v := range req.Header { + if v[0] != inHeaders[k] { + t.Errorf("NewUnAuthRequest() Header value for %v = %v, expected %v", k, v[0], inHeaders[k]) + } + } +} + +func TestNewUnAuthFormEncodedRequest(t *testing.T) { + c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, true) + + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") + inBody, outBody := map[string]string{"name": "bar", "fullname": "foobar"}, "name=bar&fullname=foobar"+"\n" + + req, _ := c.NewUnAuthFormEncodedRequest(context.TODO(), http.MethodPost, inURL, inBody) + + // test relative URL was expanded + if req.URL.String() != outURL { + t.Errorf("NewUnAuthFormEncodedRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) + } + + // test body was JSON encoded + body, _ := ioutil.ReadAll(req.Body) + if string(body) != outBody { + t.Errorf("NewUnAuthFormEncodedRequest(%v) Body = %v, expected %v", inBody, string(body), outBody) + } + + // test headers. Authorization header shouldn't exist + if _, ok := req.Header["Authorization"]; ok { + t.Errorf("Unexpected Authorization header obtained in request from NewUnAuthFormEncodedRequest()") + } + inHeaders := map[string]string{ + "Content-Type": formEncodedType, + "Accept": mediaType, + "User-Agent": testUserAgent, + } + for k, v := range req.Header { + if v[0] != inHeaders[k] { + t.Errorf("NewUnAuthFormEncodedRequest() Header value for %v = %v, expected %v", k, v[0], inHeaders[k]) + } + } +} + +func TestNewUnAuthUploadRequest(t *testing.T) { + c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, true) + + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") + inBody, outBody := []byte("Yeah I am genius!"), "Yeah I am genius!" + req, _ := c.NewUnAuthUploadRequest(context.TODO(), http.MethodPost, inURL, inBody) + + // test relative URL was expanded + if req.URL.String() != outURL { + t.Errorf("NewUnAuthUploadRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) + } + + //test body was JSON encoded + body, _ := ioutil.ReadAll(req.Body) + if string(body) != outBody { + t.Errorf("NewUnAuthUploadRequest(%v) Body = %v, expected %v", inBody, string(body), outBody) + } + + // test headers. Authorization header shouldn't exist + if _, ok := req.Header["Authorization"]; ok { + t.Errorf("Unexpected Authorization header obtained in request from NewUnAuthUploadRequest()") + } + inHeaders := map[string]string{ + "Content-Type": octetStreamType, + "Accept": mediaType, + "User-Agent": testUserAgent, + } + for k, v := range req.Header { + if v[0] != inHeaders[k] { + t.Errorf("NewUnAuthUploadRequest() Header value for %v = %v, expected %v", k, v[0], inHeaders[k]) + } + } +} + func TestErrorResponse_Error(t *testing.T) { messageResource := MessageResource{Message: "This field may not be blank."} messageList := make([]MessageResource, 1) diff --git a/client/foundation/foundation_api_test.go b/client/foundation/foundation_api_test.go new file mode 100644 index 000000000..fbfc45ec2 --- /dev/null +++ b/client/foundation/foundation_api_test.go @@ -0,0 +1,53 @@ +package foundation + +import ( + "fmt" + "testing" + + "github.com/terraform-providers/terraform-provider-nutanix/client" +) + +func TestNewFoundationAPIClient(t *testing.T) { + + // verifies positive client creation + cred := client.Credentials{ + URL: "foo.com", + Username: "username", + Password: "password", + Port: "", + Endpoint: "0.0.0.0", + Insecure: true, + FoundationEndpoint: "10.0.0.0", + FoundationPort: "8000", + RequiredFields: nil, + } + foundationClient, err := NewFoundationAPIClient(cred) + if err != nil { + t.Errorf(err.Error()) + } + outUrl := fmt.Sprintf("http://%s:%s/", cred.FoundationEndpoint, cred.FoundationPort) + if foundationClient.client.BaseURL.String() != outUrl { + t.Errorf("NewFoundationAPIClient(%v) BaseUrl in base client of foundation client = %v, expected %v", cred, foundationClient.client.BaseURL.String(), outUrl) + } + + // verify missing client scenario + cred2 := client.Credentials{ + URL: "foo.com", + Username: "username", + Password: "password", + Port: "", + Endpoint: "0.0.0.0", + Insecure: true, + RequiredFields: map[string][]string{ + "foundation": {"foundation_endpoint"}, + }, + } + foundationClient2, err2 := NewFoundationAPIClient(cred2) + if err2 != nil { + t.Errorf(err2.Error()) + } + + if foundationClient2.client.ErrorMsg == "" { + t.Errorf("NewFoundationAPIClient(%v) expected the base client in foundation client to have some error message", cred2) + } +} From 3349f1229ec0dfd5693800c0ddca119c9925d1dd Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 23 Apr 2022 12:41:53 +0530 Subject: [PATCH 02/13] Fix and add tests for v3 and karbon client --- client/karbon/karbon_api_test.go | 44 ++++++++++++++++++++++ client/v3/v3_test.go | 64 ++++++++++++++------------------ 2 files changed, 71 insertions(+), 37 deletions(-) create mode 100644 client/karbon/karbon_api_test.go diff --git a/client/karbon/karbon_api_test.go b/client/karbon/karbon_api_test.go new file mode 100644 index 000000000..d5db00f6e --- /dev/null +++ b/client/karbon/karbon_api_test.go @@ -0,0 +1,44 @@ +package karbon + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-nutanix/client" +) + +func TestNewKarbonAPIClient(t *testing.T) { + + // verifies positive client creation + cred := client.Credentials{ + URL: "foo.com", + Username: "username", + Password: "password", + Port: "", + Endpoint: "0.0.0.0", + Insecure: true, + FoundationEndpoint: "10.0.0.0", + FoundationPort: "8000", + RequiredFields: nil, + } + _, err := NewKarbonAPIClient(cred) + if err != nil { + t.Errorf(err.Error()) + } + + // verify missing client scenario + cred2 := client.Credentials{ + URL: "foo.com", + Insecure: true, + RequiredFields: map[string][]string{ + "karbon": {"username", "password", "endpoint"}, + }, + } + v3Client2, err2 := NewKarbonAPIClient(cred2) + if err2 != nil { + t.Errorf(err2.Error()) + } + + if v3Client2.client.ErrorMsg == "" { + t.Errorf("NewKarbonAPIClient(%v) expected the base client in karbon client to have some error message", cred2) + } +} diff --git a/client/v3/v3_test.go b/client/v3/v3_test.go index dca654a9a..a70fc011e 100644 --- a/client/v3/v3_test.go +++ b/client/v3/v3_test.go @@ -1,54 +1,44 @@ package v3 import ( - "reflect" "testing" "github.com/terraform-providers/terraform-provider-nutanix/client" ) func TestNewV3Client(t *testing.T) { - cred := client.Credentials{URL: "foo.com", Username: "username", Password: "password", Port: "", Endpoint: "0.0.0.0", Insecure: true} - c, _ := NewV3Client(cred) - cred2 := client.Credentials{URL: "^^^", Username: "username", Password: "password", Port: "", Endpoint: "0.0.0.0", Insecure: true} - c2, _ := NewV3Client(cred2) - - type args struct { - credentials client.Credentials + // verifies positive client creation + cred := client.Credentials{ + URL: "foo.com", + Username: "username", + Password: "password", + Port: "", + Endpoint: "0.0.0.0", + Insecure: true, + FoundationEndpoint: "10.0.0.0", + FoundationPort: "8000", + RequiredFields: nil, + } + _, err := NewV3Client(cred) + if err != nil { + t.Errorf(err.Error()) } - tests := []struct { - name string - args args - want *Client - wantErr bool - }{ - { - "test one", - args{cred}, - c, - false, - }, - { - "test one", - args{cred2}, - c2, - true, + // verify missing client scenario + cred2 := client.Credentials{ + URL: "foo.com", + Insecure: true, + RequiredFields: map[string][]string{ + "prism_central": {"username", "password", "endpoint"}, }, } + v3Client2, err2 := NewV3Client(cred2) + if err2 != nil { + t.Errorf(err2.Error()) + } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - got, err := NewV3Client(tt.args.credentials) - if (err != nil) != tt.wantErr { - t.Errorf("NewV3Client() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("NewV3Client() = %v, want %v", got, tt.want) - } - }) + if v3Client2.client.ErrorMsg == "" { + t.Errorf("NewV3Client(%v) expected the base client in v3 client to have some error message", cred2) } } From 94a389ce99bc7950bd27e2def417d18724ad014a Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Tue, 26 Apr 2022 03:13:42 +0530 Subject: [PATCH 03/13] Add image nodes service func unit test --- .../foundation_node_imaging_service_test.go | 154 ++++++++++++++++++ client/foundation/foundation_structs.go | 2 +- 2 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 client/foundation/foundation_node_imaging_service_test.go diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go new file mode 100644 index 000000000..143648d34 --- /dev/null +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -0,0 +1,154 @@ +package foundation + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "testing" + + "github.com/terraform-providers/terraform-provider-nutanix/client" + "github.com/terraform-providers/terraform-provider-nutanix/utils" +) + +func setup() (*http.ServeMux, *client.Client, *httptest.Server) { + mux := http.NewServeMux() + server := httptest.NewServer(mux) + c, _ := client.NewClient(&client.Credentials{ + URL: "", + Username: "username", + Password: "password", + Port: "", + Endpoint: "0.0.0.0", + Insecure: true}, + userAgent, + absolutePath, + true) + c.UserAgent = userAgent + c.BaseURL, _ = url.Parse(server.URL) + + return mux, c, server +} + +func TestOperation_ImageNodes(t *testing.T) { + mux, c, server := setup() + defer server.Close() + + mux.HandleFunc("/foundation/image_nodes", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("Request method = %v, expected %v", r.Method, http.MethodPost) + } + + expected := map[string]interface{}{ + "ipmi_password": "test_password", + "ipmi_user": "test_user", + "cvm_gateway": "0.0.0.0", + "cvm_netmask": "255.255.255.0", + "hypervisor_gateway": "0.0.0.0", + "hypervisor_netmask": "255.255.255.0", + "nos_package": "test_nos.tar.gz", + "hypervisor_iso": map[string]interface{}{}, + "blocks": []interface{}{ + map[string]interface{}{ + "block_id": "N123", + "nodes": []interface{}{ + map[string]interface{}{ + "ipmi_configure_now": true, + "ipmi_ip": "0.0.0.0", + "cvm_ip": "0.0.0.0", + "hypervisor_ip": "0.0.0.0", + "image_now": true, + "ipmi_password": "test_password", + "ipmi_user": "test_user", + "hypervisor_hostname": "test_hostname", + "hypervisor": "kvm", + "node_position": "A", + }, + }, + }, + }, + "clusters": []interface{}{ + map[string]interface{}{ + "redundancy_factor": 1, + "cluster_init_now": true, + "cluster_external_ip": interface{}(nil), + "cluster_name": "test_cluster", + "cluster_members": []interface{}{"0.0.0.0"}, + }, + }, + } + + // checks + var b map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&b) + if err != nil { + t.Fatalf("decode json: %v", err) + } + if !reflect.DeepEqual(b, expected) { + t.Errorf("Request body\n got=%#v\nwant=%#v", b, expected) + } + + // mock response + fmt.Fprintf(w, `{ + "session_id" : "123456-1234-123456" + }`) + }) + ctx := context.TODO() + inp := &ImageNodesInput{ + IpmiPassword: "test_password", + IpmiUser: "test_user", + CvmGateway: "0.0.0.0", + CvmNetmask: "255.255.255.0", + HypervisorGateway: "0.0.0.0", + HypervisorNetmask: "255.255.255.0", + NosPackage: "test_nos.tar.gz", + Blocks: []*Block{ + { + BlockID: "N123", + Nodes: []*Node{ + { + IpmiConfigureNow: utils.BoolPtr(true), + IpmiIP: "0.0.0.0", + IpmiUser: "test_user", + IpmiPassword: "test_password", + CvmIP: "0.0.0.0", + ImageNow: utils.BoolPtr(true), + HypervisorIP: "0.0.0.0", + HypervisorHostname: "test_hostname", + Hypervisor: "kvm", + NodePosition: "A", + }, + }, + }, + }, + Clusters: []*Clusters{ + { + RedundancyFactor: utils.Int64Ptr(1), + ClusterInitNow: utils.BoolPtr(true), + ClusterName: "test_cluster", + ClusterMembers: []string{"0.0.0.0"}, + }, + }, + } + + out := &ImageNodesAPIResponse{ + SessionID: "123456-1234-123456", + } + + op := NodeImagingOperations{ + client: c, + } + + // checks + got, err := op.ImageNodes(ctx, inp) + if err != nil { + t.Errorf("NodeImagingOperations.ImageNodes() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("NodeImagingOperations.ImageNodes() = %+v, want %+v", got, out) + } + +} diff --git a/client/foundation/foundation_structs.go b/client/foundation/foundation_structs.go index 6b863024f..a51b2e77e 100644 --- a/client/foundation/foundation_structs.go +++ b/client/foundation/foundation_structs.go @@ -70,7 +70,7 @@ type FcSettings struct { type Clusters struct { EnableNs *bool `json:"enable_ns,omitempty"` BackplaneSubnet string `json:"backplane_subnet,omitempty"` - ClusterInitSuccessful *bool `json:"cluster_init_successful"` + ClusterInitSuccessful *bool `json:"cluster_init_successful,omitempty"` BackplaneNetmask string `json:"backplane_netmask,omitempty"` RedundancyFactor *int64 `json:"redundancy_factor"` BackplaneVlan string `json:"backplane_vlan,omitempty"` From 3a920b7de4bc245d5579c2accae5faee84481c85 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Wed, 27 Apr 2022 02:32:33 +0530 Subject: [PATCH 04/13] Image nodes test fixes --- .../foundation_node_imaging_service_test.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go index 143648d34..8cd1f1b95 100644 --- a/client/foundation/foundation_node_imaging_service_test.go +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -74,7 +74,7 @@ func TestOperation_ImageNodes(t *testing.T) { map[string]interface{}{ "redundancy_factor": 1, "cluster_init_now": true, - "cluster_external_ip": interface{}(nil), + "cluster_external_ip": nil, "cluster_name": "test_cluster", "cluster_members": []interface{}{"0.0.0.0"}, }, @@ -82,13 +82,14 @@ func TestOperation_ImageNodes(t *testing.T) { } // checks - var b map[string]interface{} - err := json.NewDecoder(r.Body).Decode(&b) + var v map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&v) if err != nil { t.Fatalf("decode json: %v", err) } - if !reflect.DeepEqual(b, expected) { - t.Errorf("Request body\n got=%#v\nwant=%#v", b, expected) + + if !reflect.DeepEqual(v, expected) { + t.Errorf("Request body\n got=%#v\nwant=%#v", v, expected) } // mock response @@ -145,7 +146,7 @@ func TestOperation_ImageNodes(t *testing.T) { // checks got, err := op.ImageNodes(ctx, inp) if err != nil { - t.Errorf("NodeImagingOperations.ImageNodes() error = %v", err) + t.Fatalf("NodeImagingOperations.ImageNodes() error = %v", err) } if !reflect.DeepEqual(got, out) { t.Errorf("NodeImagingOperations.ImageNodes() = %+v, want %+v", got, out) From a64f4315f07ffa88983f9da3d8e6124f4067d075 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Wed, 27 Apr 2022 20:51:54 +0530 Subject: [PATCH 05/13] 1. Add networking and file management foundation service unit tests. 2. Add progress of image nodes unit test. 3. Fix v3 image upload test. --- ...foundation_file_management_service_test.go | 199 +++++++++++++ .../foundation_networking_service_test.go | 281 ++++++++++++++++++ .../foundation_node_imaging_service_test.go | 86 +++++- client/v3/v3_service_test.go | 6 +- 4 files changed, 561 insertions(+), 11 deletions(-) create mode 100644 client/foundation/foundation_file_management_service_test.go create mode 100644 client/foundation/foundation_networking_service_test.go diff --git a/client/foundation/foundation_file_management_service_test.go b/client/foundation/foundation_file_management_service_test.go new file mode 100644 index 000000000..66f7ae691 --- /dev/null +++ b/client/foundation/foundation_file_management_service_test.go @@ -0,0 +1,199 @@ +package foundation + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "reflect" + "testing" + + "github.com/terraform-providers/terraform-provider-nutanix/utils" +) + +func TestFMOperations_ListNOSPackages(t *testing.T) { + mux, c, server := setup() + defer server.Close() + mux.HandleFunc("/foundation/enumerate_nos_packages", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodGet) + + // mock response + fmt.Fprintf(w, `[ + "package1", + "package2" + ]`) + }) + ctx := context.TODO() + + out := &ListNOSPackagesResponse{ + "package1", + "package2", + } + + op := FileManagementOperations{ + client: c, + } + + // checks + got, err := op.ListNOSPackages(ctx) + if err != nil { + t.Fatalf("FileManagementOperations.ListNOSPackages() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("FileManagementOperations.ListNOSPackages() got = %#v, want = %#v", got, out) + } + +} + +func TestFMOperations_ListHypervisorISOs(t *testing.T) { + mux, c, server := setup() + defer server.Close() + mux.HandleFunc("/foundation/enumerate_hypervisor_isos", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodGet) + + // mock response + fmt.Fprintf(w, `{ + "hyperv": [{ + "filename": "hyperv1.iso", + "supported": true + }, + { + "filename": "hyperv2.iso", + "supported": false + } + ], + "kvm": [{ + "filename": "kvm1.iso", + "supported": true + }, + { + "filename": "kvm2.iso", + "supported": false + } + ] + }`) + }) + ctx := context.TODO() + + out := &ListHypervisorISOsResponse{ + Hyperv: []*HypervisorISOReference{ + { + Supported: utils.BoolPtr(true), + Filename: "hyperv1.iso", + }, + { + Supported: utils.BoolPtr(false), + Filename: "hyperv2.iso", + }, + }, + Kvm: []*HypervisorISOReference{ + { + Supported: utils.BoolPtr(true), + Filename: "kvm1.iso", + }, + { + Supported: utils.BoolPtr(false), + Filename: "kvm2.iso", + }, + }, + } + + op := FileManagementOperations{ + client: c, + } + + // checks + got, err := op.ListHypervisorISOs(ctx) + if err != nil { + t.Fatalf("FileManagementOperations.ListHypervisorISOs() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("FileManagementOperations.ListHypervisorISOs() got = %#v, want = %#v", got, out) + } + +} + +func TestFMOperations_UploadImage(t *testing.T) { + mux, c, server := setup() + defer server.Close() + installer_type := "kvm" + filename := "test_ahv.iso" + source := "foundation_api.go" + mux.HandleFunc("/foundation/upload", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodPost) + + expectedURL := fmt.Sprintf("/foundation/upload?installer_type=%v&filename=%v", installer_type, filename) + if expectedURL != r.URL.String() { + t.Errorf("FileManagementOperations.UploadImage() expected URL %v, got %v", expectedURL, r.URL.String()) + } + + body, _ := ioutil.ReadAll(r.Body) + file, _ := ioutil.ReadFile(source) + + if !reflect.DeepEqual(body, file) { + t.Errorf("FileManagementOperations.UploadImage() error: different uploaded files") + } + + // mock response + fmt.Fprintf(w, `{ + "md5sum": "1234QAA", + "name": "/home/foundation/kvm/%v", + "in_whitelist": false + }`, filename) + }) + ctx := context.TODO() + + out := &UploadImageResponse{ + Md5Sum: "1234QAA", + Name: "/home/foundation/kvm/" + filename, + InWhitelist: false, + } + + op := FileManagementOperations{ + client: c, + } + + // checks + got, err := op.UploadImage(ctx, installer_type, filename, source) + if err != nil { + t.Fatalf("FileManagementOperations.UploadImage() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("FileManagementOperations.UploadImage() got = %#v, want = %#v", got, out) + } + +} + +func TestFMOperations_DeleteImage(t *testing.T) { + mux, c, server := setup() + defer server.Close() + installer_type := "kvm" + filename := "test_ahv.iso" + mux.HandleFunc("/foundation/delete/", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodPost) + + body, err := ioutil.ReadAll(r.Body) + if err != nil { + t.Fatalf("FileManagementOperations.DeleteImage() error reading request body = %v", err) + } + + // check form encoded body + expected := fmt.Sprintf("filename=%v&installer_type=%v", filename, installer_type) + if string(body) != expected { + t.Errorf("FileManagementOperations.DeleteImage() request body expected = %v, got = %v", expected, string(body)) + } + + }) + ctx := context.TODO() + + op := FileManagementOperations{ + client: c, + } + + // checks + err := op.DeleteImage(ctx, installer_type, filename) + if err != nil { + t.Fatalf("FileManagementOperations.DeleteImage() error = %v", err) + } + +} diff --git a/client/foundation/foundation_networking_service_test.go b/client/foundation/foundation_networking_service_test.go new file mode 100644 index 000000000..c4ccee992 --- /dev/null +++ b/client/foundation/foundation_networking_service_test.go @@ -0,0 +1,281 @@ +package foundation + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "reflect" + "testing" + + "github.com/terraform-providers/terraform-provider-nutanix/utils" +) + +func TestNtwOperations_DiscoverNodes(t *testing.T) { + mux, c, server := setup() + defer server.Close() + mux.HandleFunc("/foundation/discover_nodes", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodGet) + + // mock response + fmt.Fprintf(w, `[{ + "model": "XCV10", + "nodes": [{ + "node_position": "A", + "hypervisor": "kvm", + "svm_ip": "0.0.0.0", + "configured": true + }], + "block_id": "GMD1" + }, { + "model": "XCV10", + "nodes": [{ + "node_position": "A", + "hypervisor": "kvm", + "svm_ip": "0.0.0.0", + "configured": false + } + ], + "block_id": "GMD2" + }]`) + }) + ctx := context.TODO() + + out := &DiscoverNodesAPIResponse{ + { + Model: "XCV10", + Nodes: []DiscoveredNode{ + { + NodePosition: "A", + Hypervisor: "kvm", + SvmIP: "0.0.0.0", + Configured: utils.BoolPtr(true), + }, + }, + BlockID: "GMD1", + }, + { + Model: "XCV10", + Nodes: []DiscoveredNode{ + { + NodePosition: "A", + Hypervisor: "kvm", + SvmIP: "0.0.0.0", + Configured: utils.BoolPtr(false), + }, + }, + BlockID: "GMD2", + }, + } + + op := NetworkingOperations{ + client: c, + } + + // checks + got, err := op.DiscoverNodes(ctx) + if err != nil { + t.Fatalf("NetworkingOperations.DiscoverNodes() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("NetworkingOperations.DiscoverNodes() got = %#v, want = %#v", got, out) + } +} + +func TestNtwOperations_NodeNetworkDetails(t *testing.T) { + mux, c, server := setup() + defer server.Close() + mux.HandleFunc("/foundation/node_network_details", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodPost) + + expected := map[string]interface{}{ + "nodes": []interface{}{ + map[string]interface{}{ + "ipv6_address": "ffff::ffff:fffff:ffff", + }, + map[string]interface{}{ + "ipv6_address": "ec12::ec12:ec12:ec12", + }, + }, + "timeout": "30", + } + + // checks + var v map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&v) + if err != nil { + t.Fatalf("decode json: %v", err) + } + + if !reflect.DeepEqual(v, expected) { + t.Errorf("Request body\n got=%#v\nwant=%#v", v, expected) + } + + // mock response + fmt.Fprintf(w, `{ + "nodes" : [ + { + "cvm_ip" : "0.0.0.0", + "node_serial" : "NX1234", + "ipmi_ip" : "0.0.0.0" + }, + { + "cvm_ip" : "0.0.0.0", + "node_serial" : "NX1235", + "ipmi_ip" : "0.0.0.0" + } + ] + }`) + }) + ctx := context.TODO() + inp := &NodeNetworkDetailsInput{ + Nodes: []NodeIpv6Input{ + { + Ipv6Address: "ffff::ffff:fffff:ffff", + }, + { + Ipv6Address: "ec12::ec12:ec12:ec12", + }, + }, + Timeout: "30", + } + out := &NodeNetworkDetailsResponse{ + Nodes: []NodeNetworkDetail{ + { + CvmIP: "0.0.0.0", + NodeSerial: "NX1234", + IpmiIP: "0.0.0.0", + }, + { + CvmIP: "0.0.0.0", + NodeSerial: "NX1235", + IpmiIP: "0.0.0.0", + }, + }, + } + + op := NetworkingOperations{ + client: c, + } + + // checks + got, err := op.NodeNetworkDetails(ctx, inp) + if err != nil { + t.Fatalf("NetworkingOperations.NodeNetworkDetails() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("NetworkingOperations.NodeNetworkDetails() got = %#v, want = %#v", got, out) + } +} + +func TestNtwOperations_ConfigureIPMI(t *testing.T) { + mux, c, server := setup() + defer server.Close() + mux.HandleFunc("/foundation/ipmi_config", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodPost) + + expected := map[string]interface{}{ + "blocks": []interface{}{ + map[string]interface{}{ + "nodes": []interface{}{ + map[string]interface{}{ + "ipmi_ip": "0.0.0.0", + "ipmi_mac": "ac:da:af:fa:af:fa", + "ipmi_configure_now": true, + }, + }, + "block_id": "GMD10", + }, + }, + "ipmi_netmask": "255.255.255.0", + "ipmi_gateway": "0.0.0.0", + "ipmi_user": "username", + "ipmi_password": "password", + } + + // checks + var v map[string]interface{} + err := json.NewDecoder(r.Body).Decode(&v) + if err != nil { + t.Fatalf("decode json: %v", err) + } + + if !reflect.DeepEqual(v, expected) { + t.Errorf("Request body\n got=%#v\nwant=%#v", v, expected) + } + + // mock response + fmt.Fprintf(w, `{ + "blocks": [ + { + "nodes":[ + { + "ipmi_ip": "0.0.0.0", + "ipmi_mac": "ac:da:af:fa:af:fa", + "ipmi_configure_now": true, + "ipmi_configure_successful": true, + "ipmi_message" : "success" + } + ], + "block_id": "GMD10" + } + ], + "ipmi_netmask": "255.255.255.0", + "ipmi_gateway": "0.0.0.0", + "ipmi_user": "username", + "ipmi_password": "password" + }`) + }) + ctx := context.TODO() + inp := &IPMIConfigAPIInput{ + IpmiUser: "username", + IpmiPassword: "password", + IpmiNetmask: "255.255.255.0", + IpmiGateway: "0.0.0.0", + Blocks: []IPMIConfigBlockInput{ + { + Nodes: []IPMIConfigNodeInput{ + { + IpmiIP: "0.0.0.0", + IpmiMac: "ac:da:af:fa:af:fa", + IpmiConfigureNow: true, + }, + }, + BlockID: "GMD10", + }, + }, + } + out := &IPMIConfigAPIResponse{ + IpmiUser: "username", + IpmiPassword: "password", + IpmiNetmask: "255.255.255.0", + IpmiGateway: "0.0.0.0", + Blocks: []IPMIConfigBlockResponse{ + { + Nodes: []IPMIConfigNodeResponse{ + { + IpmiIP: "0.0.0.0", + IpmiMac: "ac:da:af:fa:af:fa", + IpmiConfigureNow: true, + IpmiConfigureSuccessful: true, + IpmiMessage: "success", + }, + }, + BlockID: "GMD10", + }, + }, + } + + op := NetworkingOperations{ + client: c, + } + + // checks + got, err := op.ConfigureIPMI(ctx, inp) + if err != nil { + t.Fatalf("NetworkingOperations.ConfigureIPMI() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("NetworkingOperations.ConfigureIPMI() got = %#v, want = %#v", got, out) + } +} diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go index 8cd1f1b95..a3a53d704 100644 --- a/client/foundation/foundation_node_imaging_service_test.go +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -17,14 +17,13 @@ import ( func setup() (*http.ServeMux, *client.Client, *httptest.Server) { mux := http.NewServeMux() server := httptest.NewServer(mux) - c, _ := client.NewClient(&client.Credentials{ + c, _ := client.NewBaseClient(&client.Credentials{ URL: "", Username: "username", Password: "password", Port: "", Endpoint: "0.0.0.0", Insecure: true}, - userAgent, absolutePath, true) c.UserAgent = userAgent @@ -33,14 +32,18 @@ func setup() (*http.ServeMux, *client.Client, *httptest.Server) { return mux, c, server } -func TestOperation_ImageNodes(t *testing.T) { +func testHTTPMethod(t *testing.T, r *http.Request, expected string) { + if expected != r.Method { + t.Errorf("Request method = %v, expected %v", r.Method, expected) + } +} + +func TestNodeImagingOperations_ImageNodes(t *testing.T) { mux, c, server := setup() defer server.Close() mux.HandleFunc("/foundation/image_nodes", func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - t.Errorf("Request method = %v, expected %v", r.Method, http.MethodPost) - } + testHTTPMethod(t, r, http.MethodPost) expected := map[string]interface{}{ "ipmi_password": "test_password", @@ -72,7 +75,7 @@ func TestOperation_ImageNodes(t *testing.T) { }, "clusters": []interface{}{ map[string]interface{}{ - "redundancy_factor": 1, + "redundancy_factor": int64(1), "cluster_init_now": true, "cluster_external_ip": nil, "cluster_name": "test_cluster", @@ -149,7 +152,74 @@ func TestOperation_ImageNodes(t *testing.T) { t.Fatalf("NodeImagingOperations.ImageNodes() error = %v", err) } if !reflect.DeepEqual(got, out) { - t.Errorf("NodeImagingOperations.ImageNodes() = %+v, want %+v", got, out) + t.Errorf("NodeImagingOperations.ImageNodes() got = %#v, want = %#v", got, out) + } + +} + +func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { + mux, c, server := setup() + defer server.Close() + sessionId := "123456-1234-123456" + mux.HandleFunc("/foundation/progress", func(w http.ResponseWriter, r *http.Request) { + testHTTPMethod(t, r, http.MethodGet) + + // mock response + fmt.Fprintf(w, `{ + "session_id": "%v", + "imaging_stopped": true, + "aggregate_percent_complete": 100.00, + "clusters": [{ + "cluster_name": "test_cluster", + "time_elapsed": 102.33, + "cluster_members": [ + "0.0.0.0" + ], + "percent_complete": 100.00 + }], + "nodes": [{ + "cvm_ip": "0.0.0.0", + "hypervisor_ip": "0.0.0.0", + "time_elapsed": 102.33, + "percent_complete": 100.00 + }] + }`, sessionId) + }) + ctx := context.TODO() + + out := &ImageNodesProgressResponse{ + SessionID: "123456-1234-123456", + ImagingStopped: utils.BoolPtr(true), + AggregatePercentComplete: utils.Float64Ptr(100.00), + Clusters: []*ClusterProgress{ + { + ClusterName: "test_cluster", + TimeElapsed: utils.Float64Ptr(102.33), + ClusterMembers: []string{"0.0.0.0"}, + PercentComplete: utils.Float64Ptr(100.00), + }, + }, + Nodes: []*NodeProgress{ + { + CvmIP: "0.0.0.0", + HypervisorIP: "0.0.0.0", + TimeElapsed: utils.Float64Ptr(102.33), + PercentComplete: utils.Float64Ptr(100.00), + }, + }, + } + + op := NodeImagingOperations{ + client: c, + } + + // checks + got, err := op.ImageNodesProgress(ctx, sessionId) + if err != nil { + t.Fatalf("NodeImagingOperations.ImageNodesProgress() error = %v", err) + } + if !reflect.DeepEqual(got, out) { + t.Errorf("NodeImagingOperations.ImageNodesProgress() got = %#v, want = %#v", got, out) } } diff --git a/client/v3/v3_service_test.go b/client/v3/v3_service_test.go index b8c915e34..d7350f64a 100644 --- a/client/v3/v3_service_test.go +++ b/client/v3/v3_service_test.go @@ -1003,9 +1003,9 @@ func TestOperations_UploadImage(t *testing.T) { testHTTPMethod(t, r, http.MethodPut) bodyBytes, _ := ioutil.ReadAll(r.Body) - file, _ := ioutil.ReadFile("/v3.go") + file, _ := ioutil.ReadFile("v3.go") - if reflect.DeepEqual(bodyBytes, file) { + if !reflect.DeepEqual(bodyBytes, file) { t.Errorf("Operations.UploadImage() error: different uploaded files") } }) @@ -1027,7 +1027,7 @@ func TestOperations_UploadImage(t *testing.T) { { "TestOperations_UploadImage Upload Image", fields{c}, - args{"cfde831a-4e87-4a75-960f-89b0148aa2cc", "./v3.go"}, + args{"cfde831a-4e87-4a75-960f-89b0148aa2cc", "v3.go"}, }, } From 9a2e49d0965d31875de5f47af24b01f6ada7d920 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Fri, 29 Apr 2022 14:42:08 +0530 Subject: [PATCH 06/13] Resolve lint erros --- client/foundation/foundation_api_test.go | 6 +++--- .../foundation_file_management_service_test.go | 12 ++++++------ .../foundation_node_imaging_service_test.go | 6 +++--- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/client/foundation/foundation_api_test.go b/client/foundation/foundation_api_test.go index fbfc45ec2..786483d01 100644 --- a/client/foundation/foundation_api_test.go +++ b/client/foundation/foundation_api_test.go @@ -25,9 +25,9 @@ func TestNewFoundationAPIClient(t *testing.T) { if err != nil { t.Errorf(err.Error()) } - outUrl := fmt.Sprintf("http://%s:%s/", cred.FoundationEndpoint, cred.FoundationPort) - if foundationClient.client.BaseURL.String() != outUrl { - t.Errorf("NewFoundationAPIClient(%v) BaseUrl in base client of foundation client = %v, expected %v", cred, foundationClient.client.BaseURL.String(), outUrl) + outURL := fmt.Sprintf("http://%s:%s/", cred.FoundationEndpoint, cred.FoundationPort) + if foundationClient.client.BaseURL.String() != outURL { + t.Errorf("NewFoundationAPIClient(%v) BaseUrl in base client of foundation client = %v, expected %v", cred, foundationClient.client.BaseURL.String(), outURL) } // verify missing client scenario diff --git a/client/foundation/foundation_file_management_service_test.go b/client/foundation/foundation_file_management_service_test.go index 66f7ae691..73972ce5e 100644 --- a/client/foundation/foundation_file_management_service_test.go +++ b/client/foundation/foundation_file_management_service_test.go @@ -116,13 +116,13 @@ func TestFMOperations_ListHypervisorISOs(t *testing.T) { func TestFMOperations_UploadImage(t *testing.T) { mux, c, server := setup() defer server.Close() - installer_type := "kvm" + installerType := "kvm" filename := "test_ahv.iso" source := "foundation_api.go" mux.HandleFunc("/foundation/upload", func(w http.ResponseWriter, r *http.Request) { testHTTPMethod(t, r, http.MethodPost) - expectedURL := fmt.Sprintf("/foundation/upload?installer_type=%v&filename=%v", installer_type, filename) + expectedURL := fmt.Sprintf("/foundation/upload?installer_type=%v&filename=%v", installerType, filename) if expectedURL != r.URL.String() { t.Errorf("FileManagementOperations.UploadImage() expected URL %v, got %v", expectedURL, r.URL.String()) } @@ -154,7 +154,7 @@ func TestFMOperations_UploadImage(t *testing.T) { } // checks - got, err := op.UploadImage(ctx, installer_type, filename, source) + got, err := op.UploadImage(ctx, installerType, filename, source) if err != nil { t.Fatalf("FileManagementOperations.UploadImage() error = %v", err) } @@ -167,7 +167,7 @@ func TestFMOperations_UploadImage(t *testing.T) { func TestFMOperations_DeleteImage(t *testing.T) { mux, c, server := setup() defer server.Close() - installer_type := "kvm" + installerType := "kvm" filename := "test_ahv.iso" mux.HandleFunc("/foundation/delete/", func(w http.ResponseWriter, r *http.Request) { testHTTPMethod(t, r, http.MethodPost) @@ -178,7 +178,7 @@ func TestFMOperations_DeleteImage(t *testing.T) { } // check form encoded body - expected := fmt.Sprintf("filename=%v&installer_type=%v", filename, installer_type) + expected := fmt.Sprintf("filename=%v&installer_type=%v", filename, installerType) if string(body) != expected { t.Errorf("FileManagementOperations.DeleteImage() request body expected = %v, got = %v", expected, string(body)) } @@ -191,7 +191,7 @@ func TestFMOperations_DeleteImage(t *testing.T) { } // checks - err := op.DeleteImage(ctx, installer_type, filename) + err := op.DeleteImage(ctx, installerType, filename) if err != nil { t.Fatalf("FileManagementOperations.DeleteImage() error = %v", err) } diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go index a3a53d704..00a0eacec 100644 --- a/client/foundation/foundation_node_imaging_service_test.go +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -160,7 +160,7 @@ func TestNodeImagingOperations_ImageNodes(t *testing.T) { func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { mux, c, server := setup() defer server.Close() - sessionId := "123456-1234-123456" + sessionID := "123456-1234-123456" mux.HandleFunc("/foundation/progress", func(w http.ResponseWriter, r *http.Request) { testHTTPMethod(t, r, http.MethodGet) @@ -183,7 +183,7 @@ func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { "time_elapsed": 102.33, "percent_complete": 100.00 }] - }`, sessionId) + }`, sessionID) }) ctx := context.TODO() @@ -214,7 +214,7 @@ func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { } // checks - got, err := op.ImageNodesProgress(ctx, sessionId) + got, err := op.ImageNodesProgress(ctx, sessionID) if err != nil { t.Fatalf("NodeImagingOperations.ImageNodesProgress() error = %v", err) } From a6c5b93b07cb5ec80ee7d90708aa2bf9e51c3ae2 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Fri, 29 Apr 2022 17:27:52 +0530 Subject: [PATCH 07/13] Fix upload unit test after rebase --- client/client_test.go | 123 ++++++++++++++++++++++-------------------- 1 file changed, 65 insertions(+), 58 deletions(-) diff --git a/client/client_test.go b/client/client_test.go index 95d247a9b..8f8b92d31 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -1,6 +1,7 @@ package client import ( + "bytes" "context" "fmt" "io" @@ -19,6 +20,7 @@ const ( testLibraryVersion = "v3" testAbsolutePath = "api/nutanix/" + testLibraryVersion testUserAgent = "nutanix/" + testLibraryVersion + fileName = "v3/v3.go" ) func setup() (*http.ServeMux, *Client, *httptest.Server) { @@ -90,6 +92,50 @@ func TestNewRequest(t *testing.T) { } } +func TestNewUploadRequest(t *testing.T) { + c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, true) + + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") + inBody, _ := os.Open(fileName) + if err != nil { + t.Fatalf("Error opening file %v, error : %v", fileName, err) + } + + // expected body + out, _ := os.Open(fileName) + outBody, _ := ioutil.ReadAll(out) + + req, err := c.NewUploadRequest(context.TODO(), http.MethodPost, inURL, inBody) + if err != nil { + t.Fatalf("NewUploadRequest() errored out with error : %v", err.Error()) + } + // test relative URL was expanded + if req.URL.String() != outURL { + t.Errorf("NewUploadRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) + } + + //test body contents + got, _ := ioutil.ReadAll(req.Body) + if !bytes.Equal(got, outBody) { + t.Errorf("NewUploadRequest(%v) Body = %v, expected %v", inBody, string(got), string(outBody)) + } + + // test headers. + inHeaders := map[string]string{ + "Content-Type": octetStreamType, + "Accept": mediaType, + } + for k, v := range inHeaders { + if v != req.Header[k][0] { + t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, v, req.Header[k][0]) + } + } +} + func TestNewUnAuthRequest(t *testing.T) { c, err := NewClient(&Credentials{"foo.com", "username", "password", "", "", true, false, "", "", "", nil}, testUserAgent, testAbsolutePath, true) @@ -176,18 +222,28 @@ func TestNewUnAuthUploadRequest(t *testing.T) { } inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") - inBody, outBody := []byte("Yeah I am genius!"), "Yeah I am genius!" - req, _ := c.NewUnAuthUploadRequest(context.TODO(), http.MethodPost, inURL, inBody) + inBody, _ := os.Open(fileName) + if err != nil { + t.Fatalf("Error opening fiele %v, error : %v", fileName, err) + } + + // expected body + out, _ := os.Open(fileName) + outBody, _ := ioutil.ReadAll(out) + req, err := c.NewUnAuthUploadRequest(context.TODO(), http.MethodPost, inURL, inBody) + if err != nil { + t.Fatalf("NewUnAuthUploadRequest() errored out with error : %v", err.Error()) + } // test relative URL was expanded if req.URL.String() != outURL { t.Errorf("NewUnAuthUploadRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) } - //test body was JSON encoded - body, _ := ioutil.ReadAll(req.Body) - if string(body) != outBody { - t.Errorf("NewUnAuthUploadRequest(%v) Body = %v, expected %v", inBody, string(body), outBody) + //test body contents + got, _ := ioutil.ReadAll(req.Body) + if !bytes.Equal(got, outBody) { + t.Errorf("NewUnAuthUploadRequest(%v) Body = %v, expected %v", inBody, string(got), string(outBody)) } // test headers. Authorization header shouldn't exist @@ -197,11 +253,10 @@ func TestNewUnAuthUploadRequest(t *testing.T) { inHeaders := map[string]string{ "Content-Type": octetStreamType, "Accept": mediaType, - "User-Agent": testUserAgent, } - for k, v := range req.Header { - if v[0] != inHeaders[k] { - t.Errorf("NewUnAuthUploadRequest() Header value for %v = %v, expected %v", k, v[0], inHeaders[k]) + for k, v := range inHeaders { + if v != req.Header[k][0] { + t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, v, req.Header[k][0]) } } } @@ -484,54 +539,6 @@ func TestClient_NewRequest(t *testing.T) { } } -func TestClient_NewUploadRequest(t *testing.T) { - type fields struct { - Credentials *Credentials - client *http.Client - BaseURL *url.URL - UserAgent string - onRequestCompleted RequestCompletionCallback - } - type args struct { - ctx context.Context - method string - urlStr string - file *os.File - } - - tests := []struct { - name string - fields fields - args args - want *http.Request - wantErr bool - }{ - // TODO: Add test cases. - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - c := &Client{ - Credentials: tt.fields.Credentials, - client: tt.fields.client, - BaseURL: tt.fields.BaseURL, - UserAgent: tt.fields.UserAgent, - onRequestCompleted: tt.fields.onRequestCompleted, - } - got, err := c.NewUploadRequest(tt.args.ctx, tt.args.method, tt.args.urlStr, tt.args.file) - if (err != nil) != tt.wantErr { - t.Errorf("Client.NewUploadRequest() error = %v, wantErr %v", err, tt.wantErr) - - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Client.NewUploadRequest() = %v, want %v", got, tt.want) - } - }) - } -} - func TestClient_OnRequestCompleted(t *testing.T) { type fields struct { Credentials *Credentials From 56a0ec6ce1fe85a65e11515a3c1c234d2c653947 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Fri, 29 Apr 2022 17:32:59 +0530 Subject: [PATCH 08/13] Minor fix --- client/client_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/client_test.go b/client/client_test.go index 8f8b92d31..d4fb9c4b5 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -131,7 +131,7 @@ func TestNewUploadRequest(t *testing.T) { } for k, v := range inHeaders { if v != req.Header[k][0] { - t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, v, req.Header[k][0]) + t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, req.Header[k][0], v) } } } @@ -256,7 +256,7 @@ func TestNewUnAuthUploadRequest(t *testing.T) { } for k, v := range inHeaders { if v != req.Header[k][0] { - t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, v, req.Header[k][0]) + t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, req.Header[k][0], v) } } } From 8c6b1336ca73312775690d6c6876c9622bc6320d Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 30 Apr 2022 17:57:29 +0530 Subject: [PATCH 09/13] Resolve lint errors --- client/foundation/foundation_api_test.go | 1 - client/foundation/foundation_file_management_service_test.go | 4 ---- client/karbon/karbon_api_test.go | 1 - client/v3/v3_test.go | 1 - 4 files changed, 7 deletions(-) diff --git a/client/foundation/foundation_api_test.go b/client/foundation/foundation_api_test.go index 786483d01..dd4c073f9 100644 --- a/client/foundation/foundation_api_test.go +++ b/client/foundation/foundation_api_test.go @@ -8,7 +8,6 @@ import ( ) func TestNewFoundationAPIClient(t *testing.T) { - // verifies positive client creation cred := client.Credentials{ URL: "foo.com", diff --git a/client/foundation/foundation_file_management_service_test.go b/client/foundation/foundation_file_management_service_test.go index 73972ce5e..b79b7d459 100644 --- a/client/foundation/foundation_file_management_service_test.go +++ b/client/foundation/foundation_file_management_service_test.go @@ -42,7 +42,6 @@ func TestFMOperations_ListNOSPackages(t *testing.T) { if !reflect.DeepEqual(got, out) { t.Errorf("FileManagementOperations.ListNOSPackages() got = %#v, want = %#v", got, out) } - } func TestFMOperations_ListHypervisorISOs(t *testing.T) { @@ -110,7 +109,6 @@ func TestFMOperations_ListHypervisorISOs(t *testing.T) { if !reflect.DeepEqual(got, out) { t.Errorf("FileManagementOperations.ListHypervisorISOs() got = %#v, want = %#v", got, out) } - } func TestFMOperations_UploadImage(t *testing.T) { @@ -161,7 +159,6 @@ func TestFMOperations_UploadImage(t *testing.T) { if !reflect.DeepEqual(got, out) { t.Errorf("FileManagementOperations.UploadImage() got = %#v, want = %#v", got, out) } - } func TestFMOperations_DeleteImage(t *testing.T) { @@ -195,5 +192,4 @@ func TestFMOperations_DeleteImage(t *testing.T) { if err != nil { t.Fatalf("FileManagementOperations.DeleteImage() error = %v", err) } - } diff --git a/client/karbon/karbon_api_test.go b/client/karbon/karbon_api_test.go index d5db00f6e..7d299b140 100644 --- a/client/karbon/karbon_api_test.go +++ b/client/karbon/karbon_api_test.go @@ -7,7 +7,6 @@ import ( ) func TestNewKarbonAPIClient(t *testing.T) { - // verifies positive client creation cred := client.Credentials{ URL: "foo.com", diff --git a/client/v3/v3_test.go b/client/v3/v3_test.go index a70fc011e..fd2b58862 100644 --- a/client/v3/v3_test.go +++ b/client/v3/v3_test.go @@ -7,7 +7,6 @@ import ( ) func TestNewV3Client(t *testing.T) { - // verifies positive client creation cred := client.Credentials{ URL: "foo.com", From c7bb5b1a5169cd957dc39d4e6abd973f5cc6dd4f Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 30 Apr 2022 18:01:14 +0530 Subject: [PATCH 10/13] resolve lint errors --- client/foundation/foundation_node_imaging_service_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go index 00a0eacec..d91e09297 100644 --- a/client/foundation/foundation_node_imaging_service_test.go +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -154,7 +154,6 @@ func TestNodeImagingOperations_ImageNodes(t *testing.T) { if !reflect.DeepEqual(got, out) { t.Errorf("NodeImagingOperations.ImageNodes() got = %#v, want = %#v", got, out) } - } func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { @@ -221,5 +220,4 @@ func TestNodeImagingOperations_ImageNodesProgress(t *testing.T) { if !reflect.DeepEqual(got, out) { t.Errorf("NodeImagingOperations.ImageNodesProgress() got = %#v, want = %#v", got, out) } - } From 53687e92d3f79705eae705e59c0937f9f2a01b44 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 30 Apr 2022 18:06:39 +0530 Subject: [PATCH 11/13] fix lint errors --- client/foundation/foundation_file_management_service_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/client/foundation/foundation_file_management_service_test.go b/client/foundation/foundation_file_management_service_test.go index b79b7d459..f601ae35d 100644 --- a/client/foundation/foundation_file_management_service_test.go +++ b/client/foundation/foundation_file_management_service_test.go @@ -179,7 +179,6 @@ func TestFMOperations_DeleteImage(t *testing.T) { if string(body) != expected { t.Errorf("FileManagementOperations.DeleteImage() request body expected = %v, got = %v", expected, string(body)) } - }) ctx := context.TODO() From 1a318e3210faa3df7afceb273feafe9ee782ffed Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 30 Apr 2022 21:38:10 +0530 Subject: [PATCH 12/13] Fix image node unit test --- client/foundation/foundation_node_imaging_service_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/client/foundation/foundation_node_imaging_service_test.go b/client/foundation/foundation_node_imaging_service_test.go index d91e09297..e2b9296b5 100644 --- a/client/foundation/foundation_node_imaging_service_test.go +++ b/client/foundation/foundation_node_imaging_service_test.go @@ -75,7 +75,7 @@ func TestNodeImagingOperations_ImageNodes(t *testing.T) { }, "clusters": []interface{}{ map[string]interface{}{ - "redundancy_factor": int64(1), + "redundancy_factor": float64(1), "cluster_init_now": true, "cluster_external_ip": nil, "cluster_name": "test_cluster", @@ -90,7 +90,6 @@ func TestNodeImagingOperations_ImageNodes(t *testing.T) { if err != nil { t.Fatalf("decode json: %v", err) } - if !reflect.DeepEqual(v, expected) { t.Errorf("Request body\n got=%#v\nwant=%#v", v, expected) } From 03ac51ef3dc67c0a57496f65256cfad8e90ee0f2 Mon Sep 17 00:00:00 2001 From: bhatipradeep Date: Sat, 30 Apr 2022 22:00:03 +0530 Subject: [PATCH 13/13] Fix tests --- client/client_test.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/client/client_test.go b/client/client_test.go index d4fb9c4b5..f15692cc6 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -183,7 +183,8 @@ func TestNewUnAuthFormEncodedRequest(t *testing.T) { } inURL, outURL := "/foo", fmt.Sprintf(defaultBaseURL+testAbsolutePath+"/foo", httpPrefix, "foo.com") - inBody, outBody := map[string]string{"name": "bar", "fullname": "foobar"}, "name=bar&fullname=foobar"+"\n" + inBody := map[string]string{"name": "bar", "fullname": "foobar"} + outBody := map[string][]string{"name": {"bar"}, "fullname": {"foobar"}} req, _ := c.NewUnAuthFormEncodedRequest(context.TODO(), http.MethodPost, inURL, inBody) @@ -192,10 +193,13 @@ func TestNewUnAuthFormEncodedRequest(t *testing.T) { t.Errorf("NewUnAuthFormEncodedRequest(%v) URL = %v, expected %v", inURL, req.URL, outURL) } - // test body was JSON encoded - body, _ := ioutil.ReadAll(req.Body) - if string(body) != outBody { - t.Errorf("NewUnAuthFormEncodedRequest(%v) Body = %v, expected %v", inBody, string(body), outBody) + // test body + // Parse the body form data to a map structure which can be accessed by req.PostForm + req.ParseForm() + + // check form encoded key-values as compared to input values + if !reflect.DeepEqual(outBody, (map[string][]string)(req.PostForm)) { + t.Errorf("NewUnAuthFormEncodedRequest(%v) Form encoded k-v, got = %v, expected %v", inBody, req.PostForm, outBody) } // test headers. Authorization header shouldn't exist