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

PLT-1314: Completed Mock Api Initial implementation #506

Merged
merged 10 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,9 @@ kubeconfig_*
.local
dist
providers

# ignore for mock api server
mock_server.crt
mock_server.key
MockBuild
mock_api_server.log
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.22.5
require (
github.com/go-openapi/strfmt v0.23.0
github.com/google/go-cmp v0.6.0
github.com/gorilla/mux v1.8.0
github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320
github.com/hashicorp/terraform-plugin-docs v0.16.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.30.0
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m
github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU=
github.com/googleapis/gnostic v0.5.5/go.mod h1:7+EbHbldMins07ALC74bsA81Ovc97DwqyJO1AENw9kA=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
Expand Down
202 changes: 165 additions & 37 deletions spectrocloud/common_test.go
Original file line number Diff line number Diff line change
@@ -1,61 +1,189 @@
package spectrocloud

import (
"context"
"crypto/tls"
"errors"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/spectrocloud/palette-sdk-go/client"
"net/http"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)

type Cred struct {
hubbleHost string
project string
apikey string
component string
AlertUid string
}
//type Cred struct {
// hubbleHost string
// project string
// apikey string
// component string
// AlertUid string
//}

const (
negativeHost = "127.0.0.1:8888"
host = "127.0.0.1:8080"
trace = false
retryAttempts = 10
apiKey = "12345"
projectName = "unittest"
projectUID = "testprojectuid"
)

var baseConfig Cred
// var baseConfig Cred
var unitTestMockAPIClient interface{}
var unitTestMockAPINegativeClient interface{}

var basePath = ""
var startMockApiServerScript = ""
var stopMockApiServerScript = ""

func TestMain(m *testing.M) {
setup()
cwd, _ := os.Getwd()
_ = os.Setenv("TF_SRC", filepath.Dir(cwd))
basePath = os.Getenv("TF_SRC")
startMockApiServerScript = basePath + "/tests/mockApiServer/start_mock_api_server.sh"
stopMockApiServerScript = basePath + "/tests/mockApiServer/stop_mock_api_server.sh"

err := setup()
if err != nil {
fmt.Printf("Error during setup: %v\n", err)
os.Exit(1)
}
code := m.Run()
teardown()
os.Exit(code)
}

func setup() {
// Setting up test credentials & base config from env variables
baseConfig.hubbleHost = getEnvWithFallBack("TEST_HOST")
baseConfig.project = getEnvWithFallBack("TEST_PROJECT")
baseConfig.apikey = getEnvWithFallBack("TEST_API_KEY")
baseConfig.component = "ClusterHealth"
baseConfig.AlertUid = ""
if IsIntegrationTestEnvSet(baseConfig) {
fmt.Printf("\033[1;36m%s\033[0m", "> Credentials & Base config setup completed\n")
fmt.Printf("\033[1;36m%s\033[0m", "-- Test Runnig with below crdentials & base config\n")
fmt.Printf("* Test host - %s \n", baseConfig.hubbleHost)
fmt.Printf("* Test project - %s \n", baseConfig.project)
fmt.Printf("* Test key - %s \n", "***********************")
fmt.Printf("\033[1;36m%s\033[0m", "-------------------------------\n")
} else {
fmt.Printf("\033[1;36m%s\033[0m", "> Since env variable not sipping integration test\n")
}
fmt.Printf("\033[1;36m%s\033[0m", "> Setup completed \n")
func unitTestProviderConfigure(ctx context.Context) (interface{}, diag.Diagnostics) {
host := host
apiKey := apiKey
retryAttempts := retryAttempts

// Warning or errors can be collected in a slice type
var diags diag.Diagnostics

c := client.New(
client.WithPaletteURI(host),
client.WithAPIKey(apiKey),
client.WithRetries(retryAttempts),
client.WithInsecureSkipVerify(true),
client.WithRetries(1))

//// comment to trace flag
//client.WithTransportDebug()(c)

uid := projectUID
ProviderInitProjectUid = uid
client.WithScopeProject(uid)(c)
return c, diags
}

func unitTestNegativeCaseProviderConfigure(ctx context.Context) (interface{}, diag.Diagnostics) {
apiKey := apiKey
retryAttempts := retryAttempts

// Warning or errors can be collected in a slice type
var diags diag.Diagnostics

c := client.New(
client.WithPaletteURI(negativeHost),
client.WithAPIKey(apiKey),
client.WithRetries(retryAttempts),
client.WithInsecureSkipVerify(true),
client.WithRetries(1))

//// comment to trace flag
//client.WithTransportDebug()(c)

uid := projectUID
ProviderInitProjectUid = uid
client.WithScopeProject(uid)(c)
return c, diags
}
func IsIntegrationTestEnvSet(config Cred) (envSet bool) {
if config.hubbleHost != "" && config.project != "" && config.apikey != "" {
return true
} else {
return false

func checkMockServerHealth() error {
maxRetries := 5
delay := 2 * time.Second

// Skip TLS verification (use with caution; not recommended for production)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
c := &http.Client{Transport: tr}

for i := 0; i < maxRetries; i++ {
// Create a new HTTP request
req, err := http.NewRequest("GET", "https://127.0.0.1:8080/v1/health", nil)
if err != nil {
return err
}

// Add the API key as a header
req.Header.Set("ApiKey", "12345")

// Send the request
resp, err := c.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
// Server is up and running
err := resp.Body.Close()
if err != nil {
return err
}
return nil
}

if resp != nil {
err := resp.Body.Close()
if err != nil {
return err
}
}

// Wait before retrying
time.Sleep(delay)
}

return errors.New("server is not responding after multiple attempts")
}
func getEnvWithFallBack(key string) (response string) {
value := os.Getenv(key)
if len(value) == 0 {
return ""

func setup() error {
fmt.Printf("\033[1;36m%s\033[0m", "> Starting Mock API Server \n")
var ctx context.Context

cmd := exec.Command("sh", startMockApiServerScript)
output, err := cmd.CombinedOutput()
err = checkMockServerHealth()
if err != nil {
fmt.Printf("Failed to run start api server script: %s\nError: %s", output, err)
return err
}
return value

fmt.Printf("\033[1;36m%s\033[0m", "> Started Mock Api Server at https://127.0.0.1:8080 \n")
unitTestMockAPIClient, _ = unitTestProviderConfigure(ctx)
unitTestMockAPINegativeClient, _ = unitTestNegativeCaseProviderConfigure(ctx)
fmt.Printf("\033[1;36m%s\033[0m", "> Setup completed \n")
return nil
}

func teardown() {
cmd := exec.Command("bash", stopMockApiServerScript)
_, _ = cmd.CombinedOutput()
fmt.Printf("\033[1;36m%s\033[0m", "> Stopped Mock Api Server \n")
fmt.Printf("\033[1;36m%s\033[0m", "> Teardown completed \n")
err := deleteBuild()
if err != nil {
fmt.Printf("Test Clean up is incomplete: %v\n", err)
}
}

func deleteBuild() error {
err := os.Remove(basePath + "/tests/mockApiServer/MockBuild")
if err != nil {
return err
}
return nil
}
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")
}
}
Loading
Loading