Skip to content

Commit

Permalink
Unit test is added - Signed-off-by: Emincan Oguz <mailto:emincanoguz1…
Browse files Browse the repository at this point in the history
[email protected]> (#1209)

Signed-off-by: emincanoguz11 <[email protected]>
  • Loading branch information
emincanoguz11 authored Oct 22, 2024
1 parent 4eaaadb commit 4e264bb
Show file tree
Hide file tree
Showing 9 changed files with 1,136 additions and 4 deletions.
118 changes: 118 additions & 0 deletions app/safe/internal/server/handle/handle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,121 @@
*/

package handle

/*
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/spiffe/go-spiffe/v2/bundle/x509bundle"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/svid/x509svid"
"github.com/spiffe/go-spiffe/v2/workloadapi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
// X509Source interface
type X509Source interface {
GetX509SVID() (*x509svid.SVID, error)
GetX509BundleForTrustDomain(td spiffeid.TrustDomain) (*x509bundle.Bundle, error)
}
// MockX509Source is a mock implementation of the X509Source interface
type MockX509Source struct {
mock.Mock
}
// Ensure MockX509Source implements X509Source
var _ X509Source = (*MockX509Source)(nil)
func (m *MockX509Source) GetX509SVID() (*x509svid.SVID, error) {
args := m.Called()
return args.Get(0).(*x509svid.SVID), args.Error(1)
}
func (m *MockX509Source) GetX509BundleForTrustDomain(td spiffeid.TrustDomain) (*x509bundle.Bundle, error) {
args := m.Called(td)
return args.Get(0).(*x509bundle.Bundle), args.Error(1)
}
func TestInitializeRoutes(t *testing.T) {
tests := []struct {
name string
method string
path string
expectedStatus int
}{
{
name: "GET_root",
method: http.MethodGet,
path: "/",
expectedStatus: http.StatusOK,
},
{
name: "POST_root",
method: http.MethodPost,
path: "/",
expectedStatus: http.StatusOK,
},
{
name: "Invalid_path",
method: http.MethodGet,
path: "/invalid",
expectedStatus: http.StatusNotFound,
},
{
name: "Method_not_allowed",
method: http.MethodPut,
path: "/",
expectedStatus: http.StatusMethodNotAllowed,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock source
source := new(MockX509Source)
// Set up expectations for the mock
source.On("GetX509SVID").Return(&x509svid.SVID{}, nil)
source.On("GetX509BundleForTrustDomain", mock.Anything).Return(&x509bundle.Bundle{}, nil)
// Save the original DefaultServeMux and create a new one for testing
originalServeMux := http.DefaultServeMux
http.DefaultServeMux = http.NewServeMux()
// Initialize routes
InitializeRoutes((*workloadapi.X509Source)(nil))
// Create test request
req := httptest.NewRequest(tt.method, tt.path, nil)
w := httptest.NewRecorder()
// Serve request
http.DefaultServeMux.ServeHTTP(w, req)
// Assert status code
assert.Equal(t, tt.expectedStatus, w.Code)
// Restore the original DefaultServeMux
http.DefaultServeMux = originalServeMux
// Assert that our expectations were met
source.AssertExpectations(t)
})
}
}
func TestConcurrentRequests(t *testing.T) {
// Create a mock source := new(MockX509Source)
// Set up expectations for the mock
source.On("GetX509SVID").Return(&x509svid.SVID{}, nil)
source.On("GetX509BundleForTrustDomain", mock.Anything).Return(&x509bundle.Bundle{}, nil)
// Initialize routes
InitializeRoutes((*workloadapi.X509Source)(nil))
// Number of concurrent requests
numRequests := 10
results := make(chan int, numRequests)
// Launch concurrent requests
for i := 0; i < numRequests; i++ {
go func() {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
http.DefaultServeMux.ServeHTTP(w, req)
results <- w.Code
}()
}
// Collect and verify results
for i := 0; i < numRequests; i++ {
statusCode := <-results
assert.Equal(t, http.StatusOK, statusCode, "Expected status OK for concurrent request")
}
// Assert that our expectations were met
source.AssertExpectations(t)
}
*/
111 changes: 110 additions & 1 deletion app/safe/internal/server/route/base/http/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,113 @@
>/' SPDX-License-Identifier: BSD-2-Clause
*/

package http
package http_test

import (
"github.com/vmware-tanzu/secrets-manager/core/constants/audit"
"io"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
"github.com/vmware-tanzu/secrets-manager/app/safe/internal/server/route/base/http"
"github.com/vmware-tanzu/secrets-manager/core/entity/v1/data"
)

func TestSendEncryptedValue(t *testing.T) {
tests := []struct {
name string
cid string
value string
expectedStatus int
expectedBody string
expectedEvent audit.Event
expectedEntry data.JournalEntry
}{
{
name: "Empty Value",
cid: "1234",
value: "",
expectedStatus: 400,
expectedBody: "",
expectedEvent: audit.NoValue,
expectedEntry: data.JournalEntry{
CorrelationId: "1234",
Payload: "some_payload",
Method: "POST",
Url: "https://example.com/api/secret",
SpiffeId: "spiffe://example.org/service",
Event: audit.NoValue,
},
},
{
name: "Encryption Failure",
cid: "1234",
value: "fail",
expectedStatus: 500,
expectedBody: "",
expectedEvent: audit.EncryptionFailed,
expectedEntry: data.JournalEntry{
CorrelationId: "1234",
Payload: "some_payload",
Method: "POST",
Url: "https://example.com/api/secret",
SpiffeId: "spiffe://example.org/service",
Event: audit.EncryptionFailed,
},
},

//TODO: Expected Entry is not initialized for the test.
/*{
name: "Successful Encryption",
cid: "1234",
value: "[\"{\\\"name\\\": \\\"PASSWORD\\\", \\\"value\\\": \\\"VSecMRocks!\\\"}\",\"{\\\"name\\\": \\\"USERNAME\\\", \\\"value\\\": \\\"admin\\\"}\",\"VSecMRocks\"]",
expectedStatus: 200,
expectedBody: "",
expectedEvent: "", // No event should be logged on success
expectedEntry: data.JournalEntry{
CorrelationId: "1234",
Payload: "[\"{\\\"name\\\": \\\"PASSWORD\\\", \\\"value\\\": \\\"VSecMRocks!\\\"}\",\"{\\\"name\\\": \\\"USERNAME\\\", \\\"value\\\": \\\"admin\\\"}\",\"VSecMRocks\"]",
Method: "POST",
Url: "https://vsecm-safe.vsecm-system.svc.cluster.local:8443/workload/v1/secrets",
SpiffeId: "spiffe://vsecm.com/workload/example/ns/default/sa/example/n/example-c5dccdb67-xxtpv",
Event: "", // No event should be set on success
},
},
*/
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Initialize the JournalEntry based on the test case
journalEntry := data.JournalEntry{
CorrelationId: tt.cid,
Payload: tt.expectedEntry.Payload,
Method: tt.expectedEntry.Method,
Url: tt.expectedEntry.Url,
SpiffeId: tt.expectedEntry.SpiffeId,
Event: tt.expectedEntry.Event,
}

w := httptest.NewRecorder()

http.SendEncryptedValue(tt.cid, tt.value, journalEntry, w)

resp := w.Result()
body, _ := io.ReadAll(resp.Body)

// Assert HTTP status code
assert.Equal(t, tt.expectedStatus, resp.StatusCode)

// Assert response body
assert.Equal(t, tt.expectedBody, string(body))

// Assert journal event
assert.Equal(t, tt.expectedEvent, journalEntry.Event)

// Assert the entire journal entry matches expectations
assert.Equal(t, tt.expectedEntry, journalEntry)
})
}

}
86 changes: 85 additions & 1 deletion app/safe/internal/server/route/base/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,88 @@
>/' SPDX-License-Identifier: BSD-2-Clause
*/

package http
package http_test

import (
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
http_vmware "github.com/vmware-tanzu/secrets-manager/app/safe/internal/server/route/base/http" // Replace with the actual path to the `http` package
)

func TestReadBody_Success(t *testing.T) {
// Prepare the test data
cid := "test-cid"
expectedBody := []byte("test body content")
r := &http.Request{
Body: ioutil.NopCloser(bytes.NewBuffer(expectedBody)),
}

// Call the function
body, err := http_vmware.ReadBody(cid, r)

// Assertions
require.NoError(t, err, "Expected no error reading the body")
assert.Equal(t, expectedBody, body, "Expected the body to match the input")
}

func TestReadBody_ErrorReadingBody(t *testing.T) {
// Prepare the test data
cid := "test-cid"
r := &http.Request{
Body: ioutil.NopCloser(&errorReader{}),
}

// Call the function
body, err := http_vmware.ReadBody(cid, r)

// Assertions
assert.Nil(t, body, "Expected body to be nil on error")
assert.Error(t, err, "Expected an error reading the body")
}

func TestReadBody_ErrorClosingBody(t *testing.T) {
// Prepare the test data
cid := "test-cid"
expectedBody := []byte("test body content")
r := &http.Request{
Body: &closerWithError{
ReadCloser: ioutil.NopCloser(bytes.NewBuffer(expectedBody)),
},
}

// Call the function
body, err := http_vmware.ReadBody(cid, r)

// Assertions
require.NoError(t, err, "Expected no error reading the body")
assert.Equal(t, expectedBody, body, "Expected the body to match the input")

// If you want to test log output, you need to set up log capturing and assertions
// Example (assuming a log package that allows this):
// var logOutput bytes.Buffer
// log.SetOutput(&logOutput)
// assert.Contains(t, logOutput.String(), "ReadBody: Problem closing body", "Expected log to contain close error message")
}

// Helper types for testing error cases
type errorReader struct{}

func (e *errorReader) Read(p []byte) (n int, err error) {
return 0, errors.New("read error")
}

type closerWithError struct {
io.ReadCloser
}

func (c *closerWithError) Close() error {
return errors.New("close error")

}
Loading

0 comments on commit 4e264bb

Please sign in to comment.