Files
steve e22bdd6cab
Build image / build-and-push (push) Successful in 16s
Copy a garden (deep duplicate) from the gardens list (#46)
Co-authored-by: Steve Dudenhoeffer <[email protected]>
2026-07-21 03:58:39 +00:00

282 lines
10 KiB
Go

package api
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// registerAndCookie creates a user via the API and returns its session cookie.
func registerAndCookie(t *testing.T, r *gin.Engine, email string) *http.Cookie {
t.Helper()
w := doJSON(t, r, http.MethodPost, "/api/v1/auth/register",
map[string]string{"email": email, "displayName": email, "password": "password123"}, nil)
if w.Code != http.StatusOK {
t.Fatalf("register %s: status %d, body %s", email, w.Code, w.Body.String())
}
return sessionCookieFrom(t, w)
}
// decodeMap unmarshals any JSON object response into a generic map.
func decodeMap(t *testing.T, body []byte) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(body, &m); err != nil {
t.Fatalf("decode json object: %v (body %s)", err, body)
}
return m
}
func TestGardenCRUDFlow(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
// Create (defaults applied) → 201.
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Backyard"}, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
}
created := decodeMap(t, w.Body.Bytes())
id := int64(created["id"].(float64))
if created["widthCm"].(float64) != 1000 || created["unitPref"].(string) != "metric" {
t.Errorf("defaults not applied: %+v", created)
}
// List → array with one garden.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, cookie)
if w.Code != http.StatusOK {
t.Fatalf("list status = %d", w.Code)
}
var list []map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("decode list: %v (body %s)", err, w.Body.String())
}
if len(list) != 1 {
t.Errorf("list len = %d, want 1", len(list))
}
// Get → 200.
w = doJSON(t, r, http.MethodGet, gardenPath(id), nil, cookie)
if w.Code != http.StatusOK {
t.Fatalf("get status = %d", w.Code)
}
// Patch with the current version → 200, version bumped.
w = doJSON(t, r, http.MethodPatch, gardenPath(id),
map[string]any{"name": "Front", "widthCm": 200, "heightCm": 400, "unitPref": "imperial", "version": 1}, cookie)
if w.Code != http.StatusOK {
t.Fatalf("patch status = %d, body %s", w.Code, w.Body.String())
}
patched := decodeMap(t, w.Body.Bytes())
if patched["name"].(string) != "Front" || patched["version"].(float64) != 2 {
t.Errorf("patch didn't persist/bump: %+v", patched)
}
// Delete → 204, then get → 404.
w = doJSON(t, r, http.MethodDelete, gardenPath(id), nil, cookie)
if w.Code != http.StatusNoContent {
t.Fatalf("delete status = %d", w.Code)
}
w = doJSON(t, r, http.MethodGet, gardenPath(id), nil, cookie)
if w.Code != http.StatusNotFound {
t.Errorf("get after delete = %d, want 404", w.Code)
}
}
func TestGardenVersionConflictEnvelope(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
body := map[string]any{"name": "Yard2", "widthCm": 1000, "heightCm": 1000, "unitPref": "metric", "version": 1}
// First patch at version 1 succeeds (→ version 2).
if w := doJSON(t, r, http.MethodPatch, gardenPath(id), body, cookie); w.Code != http.StatusOK {
t.Fatalf("first patch status = %d", w.Code)
}
// Second patch still at version 1 conflicts.
w = doJSON(t, r, http.MethodPatch, gardenPath(id), body, cookie)
if w.Code != http.StatusConflict {
t.Fatalf("stale patch status = %d, want 409", w.Code)
}
var env struct {
Error struct{ Code string } `json:"error"`
Current map[string]any `json:"current"`
}
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode conflict envelope: %v (body %s)", err, w.Body.String())
}
if env.Error.Code != "VERSION_CONFLICT" {
t.Errorf("error code = %q, want VERSION_CONFLICT", env.Error.Code)
}
if env.Current == nil || env.Current["version"].(float64) != 2 {
t.Errorf("conflict body missing current row at version 2: %+v", env.Current)
}
}
func TestGardenCrossUserIsNotFound(t *testing.T) {
r := authEngine(t, localCfg())
alice := registerAndCookie(t, r, "[email protected]")
bob := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Alice's"}, alice)
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
// Bob sees a 404 (existence masked), not a 403.
if w := doJSON(t, r, http.MethodGet, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
t.Errorf("bob get = %d, want 404", w.Code)
}
if w := doJSON(t, r, http.MethodDelete, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
t.Errorf("bob delete = %d, want 404", w.Code)
}
// Bob's own list is empty.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, bob)
if w.Body.String() != "[]" {
t.Errorf("bob list = %s, want []", w.Body.String())
}
}
func TestGardenRequiresAuth(t *testing.T) {
r := authEngine(t, localCfg())
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated list = %d, want 401", w.Code)
}
if w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "X"}, nil); w.Code != http.StatusUnauthorized {
t.Errorf("unauthenticated create = %d, want 401", w.Code)
}
}
func TestGardenCreateValidation(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
// Missing name → 400.
if w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"widthCm": 100}, cookie); w.Code != http.StatusBadRequest {
t.Errorf("no-name create = %d, want 400", w.Code)
}
// Bad id path → 400.
if w := doJSON(t, r, http.MethodGet, "/api/v1/gardens/not-a-number", nil, cookie); w.Code != http.StatusBadRequest {
t.Errorf("bad id get = %d, want 400", w.Code)
}
}
func TestGardenUpdateRejectsBadVersion(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
// A negative (or zero) version is invalid input (400), not a version conflict.
for _, v := range []int{0, -1} {
body := map[string]any{"name": "x", "widthCm": 100, "heightCm": 100, "unitPref": "metric", "version": v}
if w := doJSON(t, r, http.MethodPatch, gardenPath(id), body, cookie); w.Code != http.StatusBadRequest {
t.Errorf("version %d patch = %d, want 400", v, w.Code)
}
}
}
func gardenPath(id int64) string {
return "/api/v1/gardens/" + strconv.FormatInt(id, 10)
}
func TestCopyGardenEndpoint(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens",
map[string]any{"name": "Home", "widthCm": 400, "heightCm": 400}, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
}
src := decodeMap(t, w.Body.Bytes())
id := int64(src["id"].(float64))
path := "/api/v1/gardens/" + strconv.FormatInt(id, 10) + "/copy"
// No body at all → 201 with the derived name.
w = doJSON(t, r, http.MethodPost, path, nil, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("copy status = %d, body %s", w.Code, w.Body.String())
}
dup := decodeMap(t, w.Body.Bytes())
if dup["name"] != "Home (copy)" {
t.Errorf("name = %v, want 'Home (copy)'", dup["name"])
}
if int64(dup["id"].(float64)) == id {
t.Error("copy reused the source id")
}
if dup["myRole"] != "owner" {
t.Errorf("myRole = %v, want owner", dup["myRole"])
}
// An explicit name is honored.
w = doJSON(t, r, http.MethodPost, path, map[string]any{"name": "Plan B"}, cookie)
if w.Code != http.StatusCreated {
t.Fatalf("named copy status = %d, body %s", w.Code, w.Body.String())
}
if got := decodeMap(t, w.Body.Bytes())["name"]; got != "Plan B" {
t.Errorf("name = %v, want 'Plan B'", got)
}
// Both copies plus the source show up in the list.
w = doJSON(t, r, http.MethodGet, "/api/v1/gardens", nil, cookie)
var list []map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("decode list: %v", err)
}
if len(list) != 3 {
t.Errorf("list has %d gardens, want 3", len(list))
}
// Unauthenticated → 401; someone else's garden → 404.
if w := doJSON(t, r, http.MethodPost, path, nil, nil); w.Code != http.StatusUnauthorized {
t.Errorf("anon copy status = %d, want 401", w.Code)
}
other := registerAndCookie(t, r, "[email protected]")
if w := doJSON(t, r, http.MethodPost, path, nil, other); w.Code != http.StatusNotFound {
t.Errorf("stranger copy status = %d, want 404", w.Code)
}
// A non-numeric id is a 400, and a malformed body is rejected.
if w := doJSON(t, r, http.MethodPost, "/api/v1/gardens/not-a-number/copy", nil, cookie); w.Code != http.StatusBadRequest {
t.Errorf("bad id status = %d, want 400", w.Code)
}
if w := doJSON(t, r, http.MethodPost, path, map[string]any{"name": 42}, cookie); w.Code != http.StatusBadRequest {
t.Errorf("bad body status = %d, want 400", w.Code)
}
}
// A body of unknown length (chunked transfer, Content-Length -1) that turns out
// to be empty must take the default-name path, not fail as malformed.
func TestCopyGardenEmptyChunkedBody(t *testing.T) {
r := authEngine(t, localCfg())
cookie := registerAndCookie(t, r, "[email protected]")
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Home"}, cookie)
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
// A plain io.Reader (not a *strings.Reader/*bytes.Buffer) leaves
// ContentLength at -1, which is what a chunked request looks like server-side.
req := httptest.NewRequest(http.MethodPost,
"/api/v1/gardens/"+strconv.FormatInt(id, 10)+"/copy", io.NopCloser(strings.NewReader("")))
req.Header.Set("Content-Type", "application/json")
req.AddCookie(cookie)
if req.ContentLength != -1 {
t.Fatalf("test setup: ContentLength = %d, want -1 (unknown)", req.ContentLength)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body %s", rec.Code, rec.Body.String())
}
if got := decodeMap(t, rec.Body.Bytes())["name"]; got != "Home (copy)" {
t.Errorf("name = %v, want the derived 'Home (copy)'", got)
}
}