Skip to content

Commit

Permalink
Merge pull request #1545 from FaisalIqbal211/GHI-1533
Browse files Browse the repository at this point in the history
Backend [Integration Test] tribes.go handlers GetTribe, CreateOrEditTribe, & GetTribeByUniqueName
  • Loading branch information
elraphty authored Feb 21, 2024
2 parents 6e8f81b + 458389b commit c3272cf
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 15 deletions.
26 changes: 14 additions & 12 deletions handlers/tribes.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ import (
)

type tribeHandler struct {
db db.Database
verifyTribeUUID func(uuid string, checkTimestamp bool) (string, error)
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,
verifyTribeUUID: auth.VerifyTribeUUID,
db: db,
verifyTribeUUID: auth.VerifyTribeUUID,
tribeUniqueNameFromName: TribeUniqueNameFromName,
}
}

Expand Down Expand Up @@ -189,21 +191,21 @@ func (th *tribeHandler) GetFirstTribeByFeed(w http.ResponseWriter, r *http.Reque
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)

Expand All @@ -225,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)
Expand All @@ -242,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")
Expand All @@ -259,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)
Expand Down
108 changes: 108 additions & 0 deletions handlers/tribes_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers

import (
"bytes"
"context"
"encoding/json"
"net/http"
Expand Down Expand Up @@ -363,3 +364,110 @@ func TestSetTribePreview(t *testing.T) {
assert.Equal(t, http.StatusUnauthorized, rr.Code)
})
}

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"])
})
}
4 changes: 2 additions & 2 deletions routes/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func NewRouter() *http.Server {
r.Group(func(r chi.Router) {
r.Get("/tribe_by_feed", tribeHandlers.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)
Expand All @@ -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}", tribeHandlers.DeleteTribe)
r.Put("/tribeactivity/{uuid}", handlers.PutTribeActivity)
Expand Down
2 changes: 1 addition & 1 deletion routes/tribes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit c3272cf

Please sign in to comment.