Skip to content

Commit

Permalink
Merge pull request #1593 from saithsab877/add-unit-tests-metrics-go
Browse files Browse the repository at this point in the history
Backend [Integration Test] metrics.go handlers MetricsBountiesProviders
  • Loading branch information
elraphty authored Mar 7, 2024
2 parents 8635b75 + eadf96c commit d16ab6e
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions handlers/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/stakwork/sphinx-tribes/db"
mocks "github.com/stakwork/sphinx-tribes/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)

func TestBountyMetrics(t *testing.T) {
Expand Down Expand Up @@ -345,3 +346,69 @@ func TestConvertMetricsToCSV(t *testing.T) {
})

}

func TestMetricsBountiesProviders(t *testing.T) {
ctx := context.Background()
mockDb := mocks.NewDatabase(t)
mh := NewMetricHandler(mockDb)
unauthorizedCtx := context.WithValue(context.Background(), auth.ContextKey, "")
authorizedCtx := context.WithValue(ctx, auth.ContextKey, "valid-key")

t.Run("should return 401 error if user is unauthorized", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(mh.MetricsBountiesProviders)

req, err := http.NewRequestWithContext(unauthorizedCtx, http.MethodPost, "/bounties/providers", nil)
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusUnauthorized, rr.Code)
})

t.Run("should return 406 error if wrong data is passed", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(mh.MetricsBountiesProviders)

invalidJson := []byte(`{"start_date": "2021-01-01"`)
req, err := http.NewRequestWithContext(authorizedCtx, http.MethodPost, "/bounties/providers", bytes.NewReader(invalidJson))
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

assert.Equal(t, http.StatusNotAcceptable, rr.Code)
})

t.Run("should return bounty providers and 200 status code if there is no error", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(mh.MetricsBountiesProviders)

validJson := []byte(`{"start_date": "2021-01-01", "end_date": "2021-12-31"}`)
req, err := http.NewRequestWithContext(authorizedCtx, http.MethodPost, "/bounties/providers", bytes.NewReader(validJson))
if err != nil {
t.Fatal(err)
}

expectedProviders := []db.Person{
{ID: 1, OwnerAlias: "Provider One"},
{ID: 2, OwnerAlias: "Provider Two"},
}

mockDb.On("GetBountiesProviders", mock.Anything, req).Return(expectedProviders).Once()

handler.ServeHTTP(rr, req)

var actualProviders []db.Person
err = json.Unmarshal(rr.Body.Bytes(), &actualProviders)
if err != nil {
t.Fatal("Failed to unmarshal response:", err)
}

assert.Equal(t, http.StatusOK, rr.Code)
assert.EqualValues(t, expectedProviders, actualProviders)
})
}

0 comments on commit d16ab6e

Please sign in to comment.