Skip to content

Commit

Permalink
fix(6023): added unit test for kibanaFetchToken
Browse files Browse the repository at this point in the history
  • Loading branch information
kaanyalti committed Dec 31, 2024
1 parent acd1adf commit 9f9c2b9
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions internal/pkg/agent/cmd/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
package cmd

import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/elastic/elastic-agent-libs/kibana"
"github.com/elastic/elastic-agent/internal/pkg/cli"
"github.com/elastic/elastic-agent/internal/pkg/config"
)

Expand Down Expand Up @@ -173,3 +179,60 @@ func TestBuildEnrollArgs(t *testing.T) {
})
}
}

func TestKibanaFetchToken(t *testing.T) {
t.Run("should fetch details from items in the api response", func(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/fleet/enrollment_api_keys/", func(w http.ResponseWriter, r *http.Request) {
basePath := "/api/fleet/enrollment_api_keys/"

apiKey := kibanaAPIKey{
ID: "id",
PolicyID: "policyID",
Name: "tokenName",
APIKey: "apiKey",
}

trimmed := strings.TrimPrefix(r.URL.String(), basePath)
if trimmed == "" {
apiKeys := kibanaAPIKeys{
Items: []kibanaAPIKey{
apiKey,
},
}
b, err := json.Marshal(apiKeys)
require.NoError(t, err)
w.Write(b)

Check failure on line 205 in internal/pkg/agent/cmd/container_test.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `w.Write` is not checked (errcheck)
return
}

keyDetail := kibanaAPIKeyDetail{
Item: apiKey,
}
b, err := json.Marshal(keyDetail)
require.NoError(t, err)
w.Write(b)

Check failure on line 214 in internal/pkg/agent/cmd/container_test.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

Error return value of `w.Write` is not checked (errcheck)
})

policy := kibanaPolicy{
ID: "policyID",
}

server := httptest.NewServer(mux)
defer server.Close()

client := &kibana.Client{
Connection: kibana.Connection{
URL: server.URL,
Username: "",
Password: "",
APIKey: "",
ServiceToken: "",
HTTP: &http.Client{},
},
}
ak, err := kibanaFetchToken(setupConfig{Kibana: kibanaConfig{RetryMaxCount: 1}}, client, &policy, cli.NewIOStreams(), "tokenName")
require.NoError(t, err)
require.Equal(t, "apiKey", ak)
})
}

0 comments on commit 9f9c2b9

Please sign in to comment.