Skip to content

Commit

Permalink
Improve test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
kuskoman committed Mar 20, 2023
1 parent 6327e1c commit fe2ec07
Show file tree
Hide file tree
Showing 5 changed files with 176 additions and 17 deletions.
9 changes: 9 additions & 0 deletions collectors/collector_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ import (
"github.com/prometheus/client_golang/prometheus"
)

func TestNewCollectorManager(t *testing.T) {
mockEndpoint := "http://localhost:9600"
cm := NewCollectorManager(mockEndpoint)

if cm == nil {
t.Error("Expected collector manager to be initialized")
}
}

type mockCollector struct{}

func (m *mockCollector) Collect(ctx context.Context, ch chan<- prometheus.Metric) error {
Expand Down
9 changes: 9 additions & 0 deletions config/env_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,12 @@ func TestGetEnvWithDefault(t *testing.T) {
}
})
}

func TestInitializeEnv(t *testing.T) {
t.Run("should throw an error if .env file is not found", func(t *testing.T) {
err := InitializeEnv()
if err == nil {
t.Errorf("expected error but got nil")
}
})
}
117 changes: 117 additions & 0 deletions fetcher/logstash_client/client_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
package logstash_client

import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

type TestResponse struct {
Foo string `json:"foo"`
}

func TestNewClient(t *testing.T) {
t.Run("should return a new client for the default endpoint", func(t *testing.T) {
client := NewClient("")
Expand All @@ -22,3 +32,110 @@ func TestNewClient(t *testing.T) {
}
})
}

func TestGetMetrics(t *testing.T) {
t.Run("should return a valid response", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"foo": "bar"}`))
}))
defer server.Close()

httpClient := &http.Client{}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

result, err := getMetrics[TestResponse](ctx, httpClient, server.URL)
if err != nil {
t.Errorf("expected no error, got %s", err)
}

if result.Foo != "bar" {
t.Errorf("expected foo to be bar, got %s", result.Foo)
}
})

t.Run("should return an error if the response is invalid", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"foo": "bar"`))
}))
defer server.Close()

httpClient := &http.Client{}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

result, err := getMetrics[TestResponse](ctx, httpClient, server.URL)
if err == nil {
t.Errorf("expected error, got nil")
}

if result != nil {
t.Errorf("expected result to be nil, got %v", result)
}
})

t.Run("should return an error if the request fails", func(t *testing.T) {
httpClient := &http.Client{}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

result, err := getMetrics[TestResponse](ctx, httpClient, "http://localhost:96010")
if err == nil {
t.Errorf("expected error, got nil")
}

if result != nil {
t.Errorf("expected result to be nil, got %v", result)
}
})

t.Run("should return an error if the context is cancelled", func(t *testing.T) {
httpClient := &http.Client{}
ctx, cancel := context.WithCancel(context.Background())
cancel()

result, err := getMetrics[TestResponse](ctx, httpClient, "http://localhost:96010")
if err == nil {
t.Errorf("expected error, got nil")
}

if result != nil {
t.Errorf("expected result to be nil, got %v", result)
}
})
}

func TestDeserializeHttpResponse(t *testing.T) {

t.Run("should properly deserialize a valid response", func(t *testing.T) {
httpResponseMock := &http.Response{
Body: io.NopCloser(strings.NewReader(`{"foo": "bar"}`)),
}

result, err := deserializeHttpResponse[TestResponse](httpResponseMock)
if err != nil {
t.Errorf("expected no error, got %s", err)
}

if result.Foo != "bar" {
t.Errorf("expected foo to be bar, got %s", result.Foo)
}
})

t.Run("should return an error if the response is invalid", func(t *testing.T) {
httpResponseMock := &http.Response{
Body: io.NopCloser(strings.NewReader(`{"foo": "bar"`)),
}

result, err := deserializeHttpResponse[TestResponse](httpResponseMock)
if err == nil {
t.Errorf("expected error, got nil")
}

if result != nil {
t.Errorf("expected result to be nil, got %v", result)
}
})
}
43 changes: 26 additions & 17 deletions prometheus_helper/prometheus_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,36 @@ func TestSimpleDescHelper(t *testing.T) {
}

func TestExtractFqdnName(t *testing.T) {
helper := &SimpleDescHelper{
Namespace: "logstash_exporter",
Subsystem: "test",
}
t.Run("should properly extract fqdn from valid metric description", func(t *testing.T) {
helper := &SimpleDescHelper{
Namespace: "logstash_exporter",
Subsystem: "test",
}

metricSubname := "fqdn_metric"
metricSubname := "fqdn_metric"

descriptors := []*prometheus.Desc{
helper.NewDesc(metricSubname),
helper.NewDescWithHelp(metricSubname, "help"),
helper.NewDescWithHelpAndLabel(metricSubname, "help", "label"),
}
descriptors := []*prometheus.Desc{
helper.NewDesc(metricSubname),
helper.NewDescWithHelp(metricSubname, "help"),
helper.NewDescWithHelpAndLabel(metricSubname, "help", "label"),
}

for _, desc := range descriptors {
fqdn, err := ExtractFqName(desc.String())
if err != nil {
t.Errorf("failed to extract fqName from metric %s", desc)
}

for _, desc := range descriptors {
fqdn, err := ExtractFqName(desc.String())
if err != nil {
t.Errorf("failed to extract fqName from metric %s", desc)
if fqdn != fmt.Sprintf("logstash_exporter_test_%s", metricSubname) {
t.Errorf("incorrect fqdn, expected %s but got %s", "logstash_exporter_test_"+metricSubname, fqdn)
}
}
})

if fqdn != fmt.Sprintf("logstash_exporter_test_%s", metricSubname) {
t.Errorf("incorrect fqdn, expected %s but got %s", "logstash_exporter_test_"+metricSubname, fqdn)
t.Run("should return error if metric description is invalid", func(t *testing.T) {
_, err := ExtractFqName("invalid metric description")
if err == nil {
t.Errorf("expected error but got nil")
}
}
})
}
15 changes: 15 additions & 0 deletions server/healthcheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,19 @@ func TestHealthCheck(t *testing.T) {
t.Run("404 status", func(t *testing.T) {
runTest(http.StatusNotFound, http.StatusInternalServerError)
})

t.Run("no response", func(t *testing.T) {
handler := getHealthCheck("http://localhost:12345")
req, err := http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
t.Fatalf("Error creating request: %v", err)
}
rr := httptest.NewRecorder()

handler(rr, req)

if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("Handler returned wrong status code: got %v want %v", status, http.StatusInternalServerError)
}
})
}

0 comments on commit fe2ec07

Please sign in to comment.