Skip to content

Commit

Permalink
completed unitest for data source appliance
Browse files Browse the repository at this point in the history
  • Loading branch information
SivaanandM committed Aug 27, 2024
1 parent 9cb4888 commit ea30cd3
Show file tree
Hide file tree
Showing 6 changed files with 300 additions and 3 deletions.
2 changes: 1 addition & 1 deletion spectrocloud/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func teardown() {
}

func deleteBuild() error {
err := os.Remove(basePath + "/tests/mockApiServer/MockAPIServer")
err := os.Remove(basePath + "/tests/mockApiServer/MockBuild")
if err != nil {
return err
}
Expand Down
55 changes: 55 additions & 0 deletions spectrocloud/data_source_appliance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package spectrocloud

import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/stretchr/testify/assert"
"testing"
)

func prepareBaseDataSourceApplianceSchema() *schema.ResourceData {
d := dataSourceAppliance().TestResourceData()
d.SetId("test123")
err := d.Set("name", "test-edge-01")
if err != nil {
return nil
}
err = d.Set("tags", map[string]string{"test": "true"})
if err != nil {
return nil
}
err = d.Set("status", "ready")
if err != nil {
return nil
}
err = d.Set("health", "healthy")
if err != nil {
return nil
}
err = d.Set("architecture", "amd")
if err != nil {
return nil
}
return d
}

func TestDataSourceApplianceReadFunc(t *testing.T) {
d := prepareBaseDataSourceApplianceSchema()
var diags diag.Diagnostics

var ctx context.Context
diags = dataSourceApplianceRead(ctx, d, unitTestMockAPIClient)
assert.Equal(t, 0, len(diags))
}

func TestDataSourceApplianceReadNegativeFunc(t *testing.T) {
d := prepareBaseDataSourceApplianceSchema()
var diags diag.Diagnostics

var ctx context.Context
diags = dataSourceApplianceRead(ctx, d, unitTestMockAPINegativeClient)
if assert.NotEmpty(t, diags, "Expected diags to contain at least one element") {
assert.Contains(t, diags[0].Summary, "No edge host found", "The first diagnostic message does not contain the expected error message")
}
}
55 changes: 55 additions & 0 deletions spectrocloud/data_source_appliances_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package spectrocloud

import (
"context"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/stretchr/testify/assert"
"testing"
)

func prepareBaseDataSourceAppliancesSchema() *schema.ResourceData {
d := dataSourceAppliances().TestResourceData()
d.SetId("test123")
err := d.Set("context", "project")
if err != nil {
return nil
}
err = d.Set("tags", map[string]string{"test": "true"})
if err != nil {
return nil
}
err = d.Set("status", "ready")
if err != nil {
return nil
}
err = d.Set("health", "healthy")
if err != nil {
return nil
}
err = d.Set("architecture", "amd")
if err != nil {
return nil
}
return d
}

func TestDataSourceAppliancesReadFunc(t *testing.T) {
d := prepareBaseDataSourceAppliancesSchema()
var diags diag.Diagnostics

var ctx context.Context
diags = dataSourcesApplianceRead(ctx, d, unitTestMockAPIClient)
assert.Equal(t, 0, len(diags))
}

func TestDataSourceAppliancesReadNegativeFunc(t *testing.T) {
d := prepareBaseDataSourceAppliancesSchema()
var diags diag.Diagnostics

var ctx context.Context
diags = dataSourcesApplianceRead(ctx, d, unitTestMockAPINegativeClient)
if assert.NotEmpty(t, diags, "Expected diags to contain at least one element") {
assert.Contains(t, diags[0].Summary, "No edge host found", "The first diagnostic message does not contain the expected error message")
}
}
2 changes: 2 additions & 0 deletions tests/mockApiServer/apiServerMock.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,11 @@ func setupRoutes(router *mux.Router, routes []routes.Route) {
func init() {
// Initialize routes for port 8080
allRoutesPositive = append(allRoutesPositive, routes.ProjectRoutes()...)
allRoutesPositive = append(allRoutesPositive, routes.AppliancesRoutes()...)
allRoutesPositive = append(allRoutesPositive, routes.CommonProjectRoutes()...)

// Initialize routes for port 8888
allRoutesNegative = append(allRoutesNegative, routes.ProjectNegativeRoutes()...)
allRoutesNegative = append(allRoutesNegative, routes.AppliancesNegativeRoutes()...)
allRoutesNegative = append(allRoutesNegative, routes.CommonProjectRoutes()...)
}
185 changes: 185 additions & 0 deletions tests/mockApiServer/routes/mockAppliances.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package routes

import (
"github.com/spectrocloud/gomi/pkg/ptr"
"github.com/spectrocloud/palette-sdk-go/api/models"
"net/http"
"strconv"
)

func getEdgeHostSearchSummary() models.V1EdgeHostsSearchSummary {
var items []*models.V1EdgeHostsMetadata
var profileSummary []*models.V1ProfileTemplateSummary
profileSummary = append(profileSummary, &models.V1ProfileTemplateSummary{
CloudType: "aws",
Name: "test-profile-1",
Packs: []*models.V1PackRefSummary{{
AddonType: "",
Annotations: nil,
DisplayName: "k8",
Layer: "infra",
LogoURL: "",
Name: "kubernetes_pack",
PackUID: generateRandomStringUID(),
Tag: "",
Type: "",
Version: "1.28.0",
}},
Type: "cluster",
UID: generateRandomStringUID(),
Version: "1.0",
})
items = append(items, &models.V1EdgeHostsMetadata{
Metadata: &models.V1ObjectMeta{
Annotations: nil,
CreationTimestamp: models.V1Time{},
DeletionTimestamp: models.V1Time{},
Labels: nil,
LastModifiedTimestamp: models.V1Time{},
Name: "test-edge-01",
UID: generateRandomStringUID(),
},
Spec: &models.V1EdgeHostsMetadataSpec{
ClusterProfileTemplates: profileSummary,
Device: &models.V1DeviceSpec{
ArchType: ptr.StringPtr("AMD"),
CPU: &models.V1CPU{
Cores: 2,
},
Disks: []*models.V1Disk{{
Controller: "",
Partitions: nil,
Size: 50,
Vendor: "",
}},
Gpus: []*models.V1GPUDeviceSpec{
{
Addresses: map[string]string{
"test": "121.0.0.1",
},
Model: "xyz",
Vendor: "abc",
},
},
Memory: nil,
Nics: nil,
Os: nil,
},
Host: &models.V1EdgeHostSpecHost{
HostAddress: "192.168.1.100",
MacAddress: "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
},
ProjectMeta: nil,
Type: "",
},
Status: &models.V1EdgeHostsMetadataStatus{
Health: &models.V1EdgeHostHealth{
AgentVersion: "",
Message: "",
State: "healthy",
},
InUseClusters: nil,
State: "",
},
})
return models.V1EdgeHostsSearchSummary{
Items: items,
Listmeta: &models.V1ListMetaData{
Continue: "",
Count: 1,
Limit: 50,
Offset: 0,
},
}
}

func getEdgeHostPayload() models.V1EdgeHostDevice {
return models.V1EdgeHostDevice{
Aclmeta: &models.V1ACLMeta{
OwnerUID: generateRandomStringUID(),
ProjectUID: generateRandomStringUID(),
TenantUID: generateRandomStringUID(),
},
Metadata: &models.V1ObjectMeta{
Annotations: nil,
CreationTimestamp: models.V1Time{},
DeletionTimestamp: models.V1Time{},
Labels: map[string]string{"type": "test"},
LastModifiedTimestamp: models.V1Time{},
Name: "test-edge-01",
UID: generateRandomStringUID(),
},
Spec: &models.V1EdgeHostDeviceSpec{
CloudProperties: nil,
ClusterProfileTemplates: nil,
Device: &models.V1DeviceSpec{
ArchType: ptr.StringPtr("amd64"),
CPU: nil,
Disks: nil,
Gpus: nil,
Memory: nil,
Nics: nil,
Os: nil,
},
Host: nil,
Properties: nil,
Service: nil,
Type: "",
Version: "1.0",
},
Status: &models.V1EdgeHostDeviceStatus{
Health: &models.V1EdgeHostHealth{
AgentVersion: "",
Message: "",
State: "healthy",
},
InUseClusters: nil,
Packs: nil,
ProfileStatus: nil,
ServiceAuthToken: "",
State: "ready",
},
}
}

func AppliancesRoutes() []Route {
return []Route{
{
Method: "POST",
Path: "/v1/dashboard/edgehosts/search",
Response: ResponseData{
StatusCode: http.StatusOK,
Payload: getEdgeHostSearchSummary(),
},
},
{
Method: "GET",
Path: "/v1/edgehosts/{uid}",
Response: ResponseData{
StatusCode: http.StatusOK,
Payload: getEdgeHostPayload(),
},
},
}
}

func AppliancesNegativeRoutes() []Route {
return []Route{
{
Method: "POST",
Path: "/v1/dashboard/edgehosts/search",
Response: ResponseData{
StatusCode: http.StatusNotFound,
Payload: getError(strconv.Itoa(http.StatusNotFound), "No edge host found"),
},
},
{
Method: "GET",
Path: "/v1/edgehosts/{uid}",
Response: ResponseData{
StatusCode: http.StatusNotFound,
Payload: getError(strconv.Itoa(http.StatusNotFound), "No edge host found"),
},
},
}
}
4 changes: 2 additions & 2 deletions tests/mockApiServer/stop_mock_api_server.sh
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#!/bin/bash

# Find the process ID of the running mockApiserver
PID=$(pgrep -f MockAPIServer)
PID=$(pgrep -f MockBuild)

if [ -z "$PID" ]; then
echo "MockAPIServer is not running."
else
# Kill the process
kill $PID
# [ -f ./MockAPIServer ] && rm -f ./MockAPIServer
kill -9 $(lsof -t -i :8080) $(lsof -t -i :8888)
echo "MockAPIServer (PID: $PID) has been stopped."
fi

0 comments on commit ea30cd3

Please sign in to comment.