Skip to content
This repository has been archived by the owner on Nov 20, 2020. It is now read-only.

Commit

Permalink
Unit testing - code coverage (#48)
Browse files Browse the repository at this point in the history
* unit testing code coverage
Signed-off-by: Viraj Indasrao <[email protected]>

* unit testing code coverage - got fmt/go vet changes
Signed-off-by: Viraj Indasrao <[email protected]>

* unit testing code coverage - catalogItem name changes
Signed-off-by: Viraj Indasrao <[email protected]>

* unit testing code coverage - comment changes
Signed-off-by: Viraj Indasrao <[email protected]>

* unit testing code coverage - comment changes
Signed-off-by: Viraj Indasrao <[email protected]>

* Unit test - review comment fixes
Signed-off-by: Viraj Indasrao <[email protected]>

* Review comment fixes
Signed-off-by: Viraj Indasrao <[email protected]>
  • Loading branch information
virajindasrao authored and Vijay Raghavan committed Jun 6, 2018
1 parent d6ea956 commit c6cc054
Show file tree
Hide file tree
Showing 7 changed files with 538 additions and 90 deletions.
180 changes: 180 additions & 0 deletions vrealize/action_test.go

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion vrealize/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ func (c *APIClient) Authenticate() error {
log.Printf("%s\n", apiError.Error())
return fmt.Errorf("%s", apiError.Error())
}
//Get a brearer token

//Get a bearer token
c.BearerToken = authRes.ID
//Set bearer token
c.HTTPClient = c.HTTPClient.New().Set("Authorization",
Expand Down
65 changes: 34 additions & 31 deletions vrealize/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (c *APIClient) GetCatalogItem(uuid string) (*CatalogItemTemplate, error) {

template := new(CatalogItemTemplate)
apiError := new(APIError)
//Set REST call to get catalog template
//Make a REST call to get catalog item template
_, err := c.HTTPClient.New().Get(path).Receive(template, apiError)

if err != nil {
Expand All @@ -49,7 +49,7 @@ func (c *APIClient) GetCatalogItem(uuid string) (*CatalogItemTemplate, error) {
if !apiError.isEmpty() {
return nil, apiError
}
//Return catalog template
//Return catalog item template
log.Printf("GetCatalogItem->template %v\n", template)
return template, nil
}
Expand All @@ -60,20 +60,20 @@ type entitledCatalogItemViews struct {
Metadata Metadata `json:"metadata"`
}

//Metadata - Metadata used to store metadata of resource list response
// Metadata - Metadata used to store metadata of resource list response
type Metadata struct {
TotalElements int `json:"totalElements"`
}

//readCatalogNameById - To read name of catalog from vRA using catalog_name
func (c *APIClient) readCatalogNameByID(catalogID string) (interface{}, error) {
// readCatalogItemNameByID - This function returns the catalog item name using catalog item ID
func (c *APIClient) readCatalogItemNameByID(catalogItemID string) (interface{}, error) {
//Form a path to read catalog template via REST call
path := fmt.Sprintf("/catalog-service/api/consumer/entitledCatalogItems/"+
"%s", catalogID)
"%s", catalogItemID)

template := new(CatalogItem)
apiError := new(APIError)
//Set REST call to get catalog template
//Make a REST call to get catalog template
_, err := c.HTTPClient.New().Get(path).Receive(template, apiError)

if err != nil {
Expand All @@ -87,11 +87,11 @@ func (c *APIClient) readCatalogNameByID(catalogID string) (interface{}, error) {
return template.CatalogItem.Name, nil
}

//readCatalogIdByName - To read id of catalog from vRA using catalog_name
func (c *APIClient) readCatalogIDByName(catalogName string) (interface{}, error) {
var catalogID string
//readCatalogItemIdByName - To read id of catalog from vRA using catalog_name
func (c *APIClient) readCatalogItemIDByName(catalogName string) (interface{}, error) {
var catalogItemID string

log.Printf("readCatalogIdByName->catalog_name %v\n", catalogName)
log.Printf("readCatalogItemIdByName->catalog_name %v\n", catalogName)

//Set a call to read number of catalogs from vRA
path := fmt.Sprintf("catalog-service/api/consumer/entitledCatalogItemViews")
Expand All @@ -112,50 +112,53 @@ func (c *APIClient) readCatalogIDByName(catalogName string) (interface{}, error)
//Fetch all catalogs from vRA
path = fmt.Sprintf("catalog-service/api/consumer/entitledCatalogItemViews?page=1&"+
"limit=%d", template.Metadata.TotalElements)
_, err := c.HTTPClient.New().Get(path).Receive(template, apiError)

if err != nil {
return nil, err
}
resp, errResp := c.HTTPClient.New().Get(path).Receive(template, apiError)

if !apiError.isEmpty() {
return nil, apiError
}

var catalogNameArray []string
if resp.StatusCode != 200 {
return nil, errResp
}

var catalogItemNameArray []string
interfaceArray := template.Content.([]interface{})
catalogNameLen := len(catalogName)
catalogItemNameLen := len(catalogName)

//Iterate over all catalog results to find out matching catalog name
// provided in terraform configuration file
for i := range interfaceArray {
catalogItem := interfaceArray[i].(map[string]interface{})
if catalogNameLen <= len(catalogItem["name"].(string)) {
if catalogItemNameLen <= len(catalogItem["name"].(string)) {
//If exact name matches then return respective catalog_id
//else if provided catalog matches as a substring in name then store it in array
if catalogName == catalogItem["name"].(string) {
return catalogItem["catalogItemId"].(interface{}), nil
} else if catalogName == catalogItem["name"].(string)[0:catalogNameLen] {
catalogNameArray = append(catalogNameArray, catalogItem["name"].(string))
} else if catalogName == catalogItem["name"].(string)[0:catalogItemNameLen] {
catalogItemNameArray = append(catalogItemNameArray, catalogItem["name"].(string))
}
}
}

//If multiple catalogs are present with provided catalog_name
// then raise an error and show all names of catalogs with similar name
if len(catalogNameArray) > 0 {
for index := range catalogNameArray {
catalogNameArray[index] = strconv.Itoa(index+1) + " " + catalogNameArray[index]
// If multiple catalog items are present with provided catalog_name
// then raise an error and show all names of catalog items with similar name
if len(catalogItemNameArray) > 0 {
for index := range catalogItemNameArray {
catalogItemNameArray[index] = strconv.Itoa(index+1) + " " + catalogItemNameArray[index]
}
errorMessage := strings.Join(catalogNameArray, "\n")
errorMessage := strings.Join(catalogItemNameArray, "\n")
fmt.Println(errorMessage)

return nil, fmt.Errorf("There are total %d catalog present with same name.\n%s\n"+
"Please select from above.", len(catalogNameArray), errorMessage)
punctuation := "is"
if len(catalogItemNameArray) > 1 {
punctuation = "are"
}
return nil, fmt.Errorf("There %s total %d catalog(s) present with same name.\n%s\n"+
"Please select from above.", punctuation, len(catalogItemNameArray), errorMessage)
}

if !apiError.isEmpty() {
return nil, apiError
}
return catalogID, nil
return catalogItemID, nil
}
206 changes: 206 additions & 0 deletions vrealize/catalog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
package vrealize

import (
"errors"
"fmt"
"gopkg.in/jarcoal/httpmock.v1"
"testing"
)

func init() {
fmt.Println("init")
// These are mock test credentials
client = NewClient(
"[email protected]",
"pass!@#",
"vsphere.local",
"http://localhost/",
true,
)
}

var catalogItemId1 = "e5dd4fba-45ed-4943-b1fc-7f96239286be"
var catalogItemId2 = "e5dd4fba-45ed-4943-b1fc-7f96239286b1"

var entitledCatalogItemViewsResp = `{"links":[{"@type":"link","rel":"next",
"href":"https://vra-01a.corp.local/catalog-service/api/consumer/entitledCatalogItemViews?page=2&limit=20"}],
"content":[{"@type":"ConsumerEntitledCatalogItemView","entitledOrganizations":[{"tenantRef":"vsphere.local",
"tenantLabel":"vsphere.local","subtenantRef":"53619006-56bb-4788-9723-9eab79752cc1","subtenantLabel":"Content"}],
"catalogItemId":"502efc1b-d5ce-4ef9-99ee-d4e2a741747c","name":"CentOS 6.3 - IPAM EXT",
"description":"CentOS 6.3 IaaS Blueprint w/Infoblox IPAM","isNoteworthy":false,"dateCreated":"2016-09-26T13:42:51.564Z",
"lastUpdatedDate":"2017-01-06T05:11:51.682Z","links":[{"@type":"link","rel":"GET: Request Template",
"href":"https://vra-01a.corp.local/catalog-service/api/consumer/entitledCatalogItems/502efc1b-d5ce-4ef9-99ee-d4e2a741747c/requests/template{?businessGroupId,requestedFor}"},
{"@type":"link","rel":"POST: Submit Request",
"href":"https://vra-01a.corp.local/catalog-service/api/consumer/entitledCatalogItems/502efc1b-d5ce-4ef9-99ee-d4e2a741747c/requests{?businessGroupId,requestedFor}"}],
"iconId":"502efc1b-d5ce-4ef9-99ee-d4e2a741747c","catalogItemTypeRef":{"id":"com.vmware.csp.component.cafe.composition.blueprint",
"label":"Composite Blueprint"},"serviceRef":{"id":"baad0ad2-8b96-4347-b188-f534dad53a0d","label":"Infrastructure"},
"outputResourceTypeRef":{"id":"composition.resource.type.deployment","label":"Deployment"}}],"metadata":{"size":20,
"totalElements":44,"totalPages":3,"number":1,"offset":0}}`

var entitledCatalogItemViewsErrorResp = `{"errors":[{"code":20116,"source":null,
"message":"Unable to find the specified catalog item in the service catalog: e5dd4fba-45ed-4943-b1fc-07f96239286b.",
"systemMessage":"Unable to find the specified catalog item in the service catalog: e5dd4fba-45ed-4943-b1fc-07f96239286b.",
"moreInfoUrl":null}]}`

var catalogItemViewsErrorResp = `{"errors":[{"code":50505,"source":null,"message":"System exception.",
"systemMessage":null,"moreInfoUrl":null}]}`

var catalogItemTemplateResp = `{"catalogItem":{"callbacks":null,"catalogItemTypeRef":{"id":"com.vmware.csp.component.cafe.composition.blueprint",
"label":"Composite Blueprint"},"dateCreated":"2015-12-22T03:16:19.289Z","description":"CentOS 6.3 IaaS Blueprint",
"forms":{"itemDetails":{"type":"external","formId":"composition.catalog.item.details"},"catalogRequestInfoHidden":true,
"requestFormScale":"BIG","requestSubmission":{"type":"extension","extensionId":"com.vmware.vcac.core.design.blueprints.requestForm",
"extensionPointId":null},"requestDetails":{"type":"extension","extensionId":"com.vmware.vcac.core.design.blueprints.requestDetailsForm",
"extensionPointId":null},"requestPreApproval":null,"requestPostApproval":null},"iconId":"e5dd4fba-45ed-4943-b1fc-7f96239286be",
"id":"e5dd4fba-45ed-4943-b1fc-7f96239286be","isNoteworthy":false,"lastUpdatedDate":"2017-01-06T05:12:56.690Z",
"name":"CentOS 6.3","organization":{"tenantRef":"vsphere.local","tenantLabel":"vsphere.local","subtenantRef":null,
"subtenantLabel":null},"outputResourceTypeRef":{"id":"composition.resource.type.deployment","label":"Deployment"},
"providerBinding":{"bindingId":"vsphere.local!::!CentOS63","providerRef":{"id":"2fbaabc5-3a48-488a-9f2a-a42616345445",
"label":"Blueprint Service"}},"serviceRef":{"id":"baad0ad2-8b96-4347-b188-f534dad53a0d","label":"Infrastructure"},
"status":"PUBLISHED","statusName":"Published","quota":0,"version":4,"requestable":true},"entitledOrganizations":[{"tenantRef":"vsphere.local",
"tenantLabel":"vsphere.local","subtenantRef":"53619006-56bb-4788-9723-9eab79752cc1","subtenantLabel":"Content"}]}`

func TestFetchCatalogItemByName(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewStringResponder(200, entitledCatalogItemViewsResp))

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews?page=1&limit=44",
httpmock.NewStringResponder(200, entitledCatalogItemViewsResp))

//Fetch catalog Item by correct and exact name
catalogItemID, err := client.readCatalogItemIDByName("CentOS 6.3 - IPAM EXT")

if err != nil {
t.Errorf("Error while fetching catalog Item %v", err)
}

if catalogItemID == nil || catalogItemID == "" {
t.Errorf("Catalog ID is nil")
}

// Fetch catalog item by false name
// The name is not present in catalog item list
// This should return an error
catalogItemID, err = client.readCatalogItemIDByName("Cent OS 6.3")

if catalogItemID != nil && catalogItemID != "" {
t.Errorf("Catalog Item ID is not nil")
}

if err != nil {
t.Errorf("Error while fetching catalog item %v", err)
}

// Fetch catalog item by correct and incomplete name
// The name provided (CentOS) to the readCatalogItemIDByName() is substring of correct name (CentOS_6.3)
// This should return empty catalogItemID with suggestions with full name
catalogItemID, err = client.readCatalogItemIDByName("CentOS")

if catalogItemID != nil && catalogItemID != "" {
t.Errorf("Catalog Item ID is not nil")
}

if err == nil {
t.Errorf("Error should have been occurred while fetching the catalog item with encomplete name")
}
httpmock.Reset()

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewStringResponder(404, entitledCatalogItemViewsResp))

// Fetch catalog item by correct and incomplete name
// The name provided (CentOS) to the readCatalogItemIDByName() is substring of correct name (CentOS_6.3)
// This should return empty catalogItemID with suggestions with full name
catalogItemID, err = client.readCatalogItemIDByName("CentOS")

if catalogItemID != nil {
t.Errorf("Catalog Item ID is not nil")
}

if err == nil {
t.Errorf("Error should have been occurred while fetching the catalog item with encomplete name")
}
httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewStringResponder(404, entitledCatalogItemViewsErrorResp))
catalogItemID, err = client.readCatalogItemIDByName("CentOS")

if err == nil {
t.Errorf("Data fetched with wrong catalog ID")
}

if catalogItemID != nil {
t.Errorf("Wrong catalog data got fetched")
}
httpmock.Reset()

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewStringResponder(200, entitledCatalogItemViewsResp))

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews?page=1&limit=44",
httpmock.NewStringResponder(404, entitledCatalogItemViewsErrorResp))

catalogItemID, err = client.readCatalogItemIDByName("CentOS")

if err == nil {
t.Errorf("Data fetched with wrong catalog item ID")
}

if catalogItemID != nil {
t.Errorf("Wrong catalog item data got fetched")
}

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewErrorResponder(errors.New(catalogItemViewsErrorResp)))
httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItemViews",
httpmock.NewStringResponder(500, entitledCatalogItemViewsErrorResp))
catalogItemID, err = client.readCatalogItemIDByName("CentOS")
}


// This unit test function contains test cases related to catalog ID in tf config files
// Scenarios :
// 1) Fetch catalog item details using correct catalog item ID
// 2) Fetch catalog item details with invalid catalog item ID
func TestFetchCatalogItemByID(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItems/"+catalogItemId1,
httpmock.NewStringResponder(200, catalogItemTemplateResp))

catalogItemName, err := client.readCatalogItemNameByID(catalogItemId1)

if err != nil {
t.Errorf("Error while fetching catalog item %v", err)
}

if catalogItemName == nil {
t.Errorf("Catalog Item Name is is nil")
}

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItems/"+catalogItemId1,
httpmock.NewStringResponder(404, entitledCatalogItemViewsErrorResp))

catalogItemName, err = client.readCatalogItemNameByID(catalogItemId2)

if err == nil {
t.Errorf("Data fetched with wrong catalog ID")
}

if catalogItemName != nil {
t.Errorf("Wrong catalog item data got fetched")
}

httpmock.RegisterResponder("GET", "http://localhost/catalog-service/api/consumer/entitledCatalogItems/"+catalogItemId2,
httpmock.NewStringResponder(404, entitledCatalogItemViewsErrorResp))
catalogItemName, err = client.readCatalogItemNameByID(catalogItemId2)

if err == nil {
t.Errorf("Data fetched with wrong catalog ID")
}

if catalogItemName != nil {
t.Errorf("Wrong catalog data got fetched")
}
}
Loading

0 comments on commit c6cc054

Please sign in to comment.