Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foundation unit tests and existing test fixes #433

242 changes: 193 additions & 49 deletions client/client_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"bytes"
"context"
"fmt"
"io"
Expand All @@ -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) {
Expand All @@ -38,7 +40,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)
Expand All @@ -49,6 +51,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)

Expand All @@ -73,6 +92,179 @@ 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, req.Header[k][0], v)
}
}
}

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 := map[string]string{"name": "bar", "fullname": "foobar"}
outBody := map[string][]string{"name": {"bar"}, "fullname": {"foobar"}}

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
// 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
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, _ := 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 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
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,
}
for k, v := range inHeaders {
if v != req.Header[k][0] {
t.Errorf("NewUploadRequest() Header value for %v = %v, expected %v", k, req.Header[k][0], v)
}
}
}

func TestErrorResponse_Error(t *testing.T) {
messageResource := MessageResource{Message: "This field may not be blank."}
messageList := make([]MessageResource, 1)
Expand Down Expand Up @@ -351,54 +543,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
Expand Down
52 changes: 52 additions & 0 deletions client/foundation/foundation_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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)
}
}
Loading