From 10b6d63fd8f97d83236c934d82f743e670f96246 Mon Sep 17 00:00:00 2001 From: FaisalIqbal211 Date: Wed, 21 Feb 2024 18:01:12 +0500 Subject: [PATCH] Implemented unit tests --- handlers/tribes.go | 26 ++++++---- handlers/tribes_test.go | 109 ++++++++++++++++++++++++++++++++++++++++ routes/index.go | 4 +- routes/tribes.go | 2 +- 4 files changed, 128 insertions(+), 13 deletions(-) diff --git a/handlers/tribes.go b/handlers/tribes.go index 041698fb2..525c69110 100644 --- a/handlers/tribes.go +++ b/handlers/tribes.go @@ -18,11 +18,17 @@ import ( ) type tribeHandler struct { - db db.Database + db db.Database + verifyTribeUUID func(uuid string, checkTimestamp bool) (string, error) + tribeUniqueNameFromName func(name string) (string, error) } func NewTribeHandler(db db.Database) *tribeHandler { - return &tribeHandler{db: db} + return &tribeHandler{ + db: db, + verifyTribeUUID: auth.VerifyTribeUUID, + tribeUniqueNameFromName: TribeUniqueNameFromName, + } } func GetAllTribes(w http.ResponseWriter, r *http.Request) { @@ -185,21 +191,21 @@ func GetFirstTribeByFeed(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(theTribe) } -func GetTribeByUniqueName(w http.ResponseWriter, r *http.Request) { +func (th *tribeHandler) GetTribeByUniqueName(w http.ResponseWriter, r *http.Request) { uuid := chi.URLParam(r, "un") - tribe := db.DB.GetTribeByUniqueName(uuid) + tribe := th.db.GetTribeByUniqueName(uuid) var theTribe map[string]interface{} j, _ := json.Marshal(tribe) json.Unmarshal(j, &theTribe) - theTribe["channels"] = db.DB.GetChannelsByTribe(tribe.UUID) + theTribe["channels"] = th.db.GetChannelsByTribe(tribe.UUID) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(theTribe) } -func CreateOrEditTribe(w http.ResponseWriter, r *http.Request) { +func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request) { ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) @@ -221,7 +227,7 @@ func CreateOrEditTribe(w http.ResponseWriter, r *http.Request) { now := time.Now() //.Format(time.RFC3339) - extractedPubkey, err := auth.VerifyTribeUUID(tribe.UUID, false) + extractedPubkey, err := th.verifyTribeUUID(tribe.UUID, false) if err != nil { fmt.Println("extract UUID error", err) w.WriteHeader(http.StatusUnauthorized) @@ -238,9 +244,9 @@ func CreateOrEditTribe(w http.ResponseWriter, r *http.Request) { } } - existing := db.DB.GetTribe(tribe.UUID) + existing := th.db.GetTribe(tribe.UUID) if existing.UUID == "" { // if doesn't exist already, create unique name - tribe.UniqueName, _ = TribeUniqueNameFromName(tribe.Name) + tribe.UniqueName, _ = th.tribeUniqueNameFromName(tribe.Name) } else { // already exists! make sure it's owned if existing.OwnerPubKey != extractedPubkey { fmt.Println("createOrEditTribe tribe.ownerPubKey not match") @@ -255,7 +261,7 @@ func CreateOrEditTribe(w http.ResponseWriter, r *http.Request) { tribe.Updated = &now tribe.LastActive = now.Unix() - _, err = db.DB.CreateOrEditTribe(tribe) + _, err = th.db.CreateOrEditTribe(tribe) if err != nil { fmt.Println("=> ERR createOrEditTribe", err) w.WriteHeader(http.StatusBadRequest) diff --git a/handlers/tribes_test.go b/handlers/tribes_test.go index bfc409c68..71a8181f5 100644 --- a/handlers/tribes_test.go +++ b/handlers/tribes_test.go @@ -1,6 +1,7 @@ package handlers import ( + "bytes" "context" "encoding/json" "net/http" @@ -8,6 +9,7 @@ import ( "testing" "github.com/go-chi/chi" + "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" mocks "github.com/stakwork/sphinx-tribes/mocks" "github.com/stretchr/testify/assert" @@ -183,3 +185,110 @@ func TestGetTribesByAppUrl(t *testing.T) { assert.ElementsMatch(t, mockTribes, responseData) }) } + +func TestCreateOrEditTribe(t *testing.T) { + mockDb := mocks.NewDatabase(t) + tHandler := NewTribeHandler(mockDb) + + t.Run("Should test that a tribe can be created when the right data is passed", func(t *testing.T) { + // Mock data + mockPubKey := "valid_pubkey" + mockUUID := "valid_uuid" + mockName := "Test Tribe" + mockDescription := "This is a test tribe." + mockTags := []string{"tag1", "tag2"} + + mockVerifyTribeUUID := func(uuid string, checkTimestamp bool) (string, error) { + return mockPubKey, nil + } + + tHandler.verifyTribeUUID = mockVerifyTribeUUID + + // Mock request body + requestBody := map[string]interface{}{ + "UUID": mockUUID, + "Name": mockName, + "Description": mockDescription, + "Tags": mockTags, + } + requestBodyBytes, err := json.Marshal(requestBody) + if err != nil { + t.Fatal(err) + } + + // Mock database calls + mockDb.On("GetTribe", mock.Anything).Return(db.Tribe{ + UUID: mockUUID, + OwnerPubKey: mockPubKey, + }).Once() + mockDb.On("CreateOrEditTribe", mock.Anything).Return(db.Tribe{ + UUID: mockUUID, + }, nil) + + // Create request with mock body + req, err := http.NewRequest("POST", "/", bytes.NewBuffer(requestBodyBytes)) + if err != nil { + t.Fatal(err) + } + + // Set context with mock pub key + ctx := context.WithValue(req.Context(), auth.ContextKey, mockPubKey) + req = req.WithContext(ctx) + + // Serve request + rr := httptest.NewRecorder() + handler := http.HandlerFunc(tHandler.CreateOrEditTribe) + handler.ServeHTTP(rr, req) + + // Verify response + assert.Equal(t, http.StatusOK, rr.Code) + var responseData map[string]interface{} + err = json.Unmarshal(rr.Body.Bytes(), &responseData) + if err != nil { + t.Fatalf("Error decoding JSON response: %s", err) + } + assert.Equal(t, mockUUID, responseData["uuid"]) + }) +} + +func TestGetTribeByUniqueName(t *testing.T) { + mockDb := mocks.NewDatabase(t) + tHandler := NewTribeHandler(mockDb) + + t.Run("Should test that a tribe can be fetched by its unique name", func(t *testing.T) { + // Mock data + mockUniqueName := "test_tribe" + mockTribe := db.Tribe{ + UniqueName: mockUniqueName, + UUID: "valid_uuid", + } + mockChannels := []db.Channel{ + {ID: 1, TribeUUID: "UUID"}, + {ID: 2, TribeUUID: "UUID"}, + } + + // Mock database calls + mockDb.On("GetTribeByUniqueName", mock.Anything).Return(mockTribe) + mockDb.On("GetChannelsByTribe", mock.Anything).Return(mockChannels).Once() + + // Create request with mock unique name + req, err := http.NewRequest("GET", "/tribe_by_un/"+mockUniqueName, nil) + if err != nil { + t.Fatal(err) + } + + // Serve request + rr := httptest.NewRecorder() + handler := http.HandlerFunc(tHandler.GetTribeByUniqueName) + handler.ServeHTTP(rr, req) + + // Verify response + assert.Equal(t, http.StatusOK, rr.Code) + var responseData map[string]interface{} + err = json.Unmarshal(rr.Body.Bytes(), &responseData) + if err != nil { + t.Fatalf("Error decoding JSON response: %s", err) + } + assert.Equal(t, mockUniqueName, responseData["unique_name"]) + }) +} diff --git a/routes/index.go b/routes/index.go index 4cb494c62..4690b6a2a 100644 --- a/routes/index.go +++ b/routes/index.go @@ -36,7 +36,7 @@ func NewRouter() *http.Server { r.Group(func(r chi.Router) { r.Get("/tribe_by_feed", handlers.GetFirstTribeByFeed) r.Get("/leaderboard/{tribe_uuid}", handlers.GetLeaderBoard) - r.Get("/tribe_by_un/{un}", handlers.GetTribeByUniqueName) + r.Get("/tribe_by_un/{un}", tribeHandlers.GetTribeByUniqueName) r.Get("/tribes_by_owner/{pubkey}", tribeHandlers.GetTribesByOwner) r.Get("/search/bots/{query}", handlers.SearchBots) @@ -63,7 +63,7 @@ func NewRouter() *http.Server { r.Post("/channel", handlers.CreateChannel) r.Post("/leaderboard/{tribe_uuid}", handlers.CreateLeaderBoard) r.Put("/leaderboard/{tribe_uuid}", handlers.UpdateLeaderBoard) - r.Put("/tribe", handlers.CreateOrEditTribe) + r.Put("/tribe", tribeHandlers.CreateOrEditTribe) r.Put("/tribestats", handlers.PutTribeStats) r.Delete("/tribe/{uuid}", handlers.DeleteTribe) r.Put("/tribeactivity/{uuid}", handlers.PutTribeActivity) diff --git a/routes/tribes.go b/routes/tribes.go index 72ce7cb1b..7e8e68439 100644 --- a/routes/tribes.go +++ b/routes/tribes.go @@ -15,7 +15,7 @@ func TribeRoutes() chi.Router { r.Get("/app_urls/{app_urls}", handlers.GetTribesByAppUrls) r.Get("/{uuid}", tribeHandlers.GetTribe) r.Get("/total", handlers.GetTotalribes) - r.Post("/", handlers.CreateOrEditTribe) + r.Post("/", tribeHandlers.CreateOrEditTribe) }) return r }