From ce74b2cb30316e1f15c5f022504a1d72d5d61fd3 Mon Sep 17 00:00:00 2001 From: Sebastien Le Digabel Date: Fri, 4 Aug 2023 12:38:55 +0100 Subject: [PATCH] Adding tests for SaveCredentials --- helper/credentials/saml.go | 4 +++ helper/credentials/saml_test.go | 59 ++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/helper/credentials/saml.go b/helper/credentials/saml.go index 98fdff5e5..74c599898 100644 --- a/helper/credentials/saml.go +++ b/helper/credentials/saml.go @@ -1,6 +1,7 @@ package credentials import ( + "errors" "path" "github.com/versent/saml2aws/v2/pkg/creds" @@ -67,6 +68,9 @@ func SaveCredentials(idpName, url, username, password string) error { Secret: password, } + if idpName == "" { + return errors.New("idpName is empty") + } return CurrentHelper.Add(creds) } diff --git a/helper/credentials/saml_test.go b/helper/credentials/saml_test.go index d2bd4fb83..3cbdc99df 100644 --- a/helper/credentials/saml_test.go +++ b/helper/credentials/saml_test.go @@ -15,6 +15,12 @@ type MockHelper struct { DeleteFailError error } +func NewMockHelper() *MockHelper { + return &MockHelper{ + Credentials: make(map[string]*Credentials), + } +} + func (m *MockHelper) Add(c *Credentials) error { if m.AddFailError != nil { return m.AddFailError @@ -230,7 +236,7 @@ func TestLookupCredentials(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.CaseName, func(t *testing.T) { t.Log(testCase.CaseName) - m := &MockHelper{} + m := NewMockHelper() CurrentHelper = m m.Credentials = testCase.initialCredentials t.Log(testCase.initialCredentials) @@ -251,3 +257,54 @@ func TestLookupCredentials(t *testing.T) { // restoring the old Helper CurrentHelper = oldHelper } + +func TestSaveCredentials(t *testing.T) { + oldHelper := CurrentHelper + + testCases := []struct { + CaseName string + IdpName string + URL string + Username string + Password string + expectedCredentialKeyName string + expectedError bool + }{ + { + CaseName: "SaveCredentials", + IdpName: "test", + URL: "http://test.com/", + Username: "user1", + Password: "password1", + expectedCredentialKeyName: "saml2aws_credentials_test", + }, + { + CaseName: "EmptyIdpNameRaisesError", + IdpName: "", + URL: "http://test.com/", + Username: "user2", + Password: "password2", + expectedError: true, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.CaseName, func(t *testing.T) { + m := NewMockHelper() + CurrentHelper = m + err := SaveCredentials(testCase.IdpName, testCase.URL, testCase.Username, testCase.Password) + if testCase.expectedError { + assert.NotNil(t, err) + } else { + assert.Nil(t, err) + _, ok := m.Credentials[testCase.expectedCredentialKeyName] + assert.True(t, ok) + assert.EqualValues(t, testCase.Username, m.Credentials[testCase.expectedCredentialKeyName].Username) + assert.EqualValues(t, testCase.Password, m.Credentials[testCase.expectedCredentialKeyName].Secret) + } + }) + } + + // restoring the old Helper + CurrentHelper = oldHelper +}