package test import ( "encoding/json" "net/http" "testing" "git.pengzhan.dev/noteplace-server/internal/models" "github.com/stretchr/testify/assert" "go.uber.org/zap" ) func TestPlacesAPI(t *testing.T) { logger, _ := zap.NewDevelopment() zap.ReplaceGlobals(logger) router, s := setupTestRouter(t) adminSessionID := createTestUser(t, s, adminUser) user1SessionID := createTestUser(t, s, regularUser1) t.Run("Admin can create a place", func(t *testing.T) { newPlace := models.Place{ Name: "Admin Created Place", Category: "Restaurant", Address: models.Address{ Street: "123 Admin St", City: "Adminville", }, } w := performRequest(router, "POST", "/api/places", newPlace, adminSessionID) assert.Equal(t, http.StatusCreated, w.Code) var createdPlace models.Place err := json.Unmarshal(w.Body.Bytes(), &createdPlace) assert.NoError(t, err) assert.NotEmpty(t, createdPlace.ID) assert.Equal(t, newPlace.Name, createdPlace.Name) // Verify it's in the store foundPlace, found := s.GetPlaceByID(createdPlace.ID) assert.True(t, found) assert.Equal(t, createdPlace.Name, foundPlace.Name) }) t.Run("Regular user cannot create a place", func(t *testing.T) { newPlace := models.Place{ Name: "User Created Place", Category: "Cafe", Address: models.Address{ Street: "456 User Ave", City: "Userton", }, } w := performRequest(router, "POST", "/api/places", newPlace, user1SessionID) assert.Equal(t, http.StatusUnauthorized, w.Code) // Expect 401 as per current API implementation }) t.Run("Get all places", func(t *testing.T) { // Create a few places directly in the store for testing retrieval place1 := models.Place{ID: "place-1", Name: "Place One", Category: "Bar"} place2 := models.Place{ID: "place-2", Name: "Place Two", Category: "Park"} _ = s.CreatePlace(place1) _ = s.CreatePlace(place2) w := performRequest(router, "GET", "/api/places", nil, "") // No auth needed for GET assert.Equal(t, http.StatusOK, w.Code) var placesMap map[string]models.Place err := json.Unmarshal(w.Body.Bytes(), &placesMap) assert.NoError(t, err) var places []models.Place for _, p := range placesMap { places = append(places, p) } assert.Len(t, places, 3) // Includes the one created by admin earlier assert.Contains(t, places, place1) assert.Contains(t, places, place2) }) t.Run("Get place by ID", func(t *testing.T) { place3 := models.Place{ID: "place-3", Name: "Specific Place", Category: "Museum"} _ = s.CreatePlace(place3) w := performRequest(router, "GET", "/api/places/place-3", nil, "") assert.Equal(t, http.StatusOK, w.Code) var foundPlace models.Place err := json.Unmarshal(w.Body.Bytes(), &foundPlace) assert.NoError(t, err) assert.Equal(t, place3.Name, foundPlace.Name) w = performRequest(router, "GET", "/api/places/non-existent", nil, "") assert.Equal(t, http.StatusNotFound, w.Code) }) }