// SPDX-License-Identifier: AGPL-3.0-or-later package pocketbase import ( "context" "encoding/json" "net/http" "net/http/httptest" "sync/atomic" "testing" ) type record struct { ID string `json:"id"` Name string `json:"name"` } func fakePocketBase(t *testing.T, authCalls *atomic.Int32) *httptest.Server { t.Helper() mux := http.NewServeMux() mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"code":200}`)) }) mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) { n := authCalls.Add(1) json.NewEncoder(w).Encode(map[string]string{"token": "tok" + string(rune('0')+n)}) }) mux.HandleFunc("GET /api/collections/workspaces/records", func(w http.ResponseWriter, r *http.Request) { // The first token is treated as expired to exercise the retry path. if r.Header.Get("Authorization") != "tok2" { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(`{"status":401,"message":"expired"}`)) return } if got := r.URL.Query().Get("filter"); got != "slug='acme'" { t.Errorf("filter = %q", got) } w.Write([]byte(`{"page":1,"perPage":30,"totalItems":1,"totalPages":1,"items":[{"id":"w1","name":"Acme"}]}`)) }) mux.HandleFunc("GET /api/collections/workspaces/records/missing", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"status":404,"message":"not found"}`)) }) srv := httptest.NewServer(mux) t.Cleanup(srv.Close) return srv } func TestHealth(t *testing.T) { var calls atomic.Int32 srv := fakePocketBase(t, &calls) if err := New(srv.URL, "a", "b").Health(context.Background()); err != nil { t.Fatal(err) } if calls.Load() != 0 { t.Error("health check should not authenticate") } } func TestListReauthenticatesOn401(t *testing.T) { var calls atomic.Int32 srv := fakePocketBase(t, &calls) c := New(srv.URL, "a", "b") res, err := List[record](context.Background(), c, "workspaces", ListOptions{Filter: "slug='acme'"}) if err != nil { t.Fatal(err) } if len(res.Items) != 1 || res.Items[0].Name != "Acme" { t.Errorf("items = %+v", res.Items) } if calls.Load() != 2 { t.Errorf("auth calls = %d, want 2", calls.Load()) } } func TestNotFound(t *testing.T) { var calls atomic.Int32 srv := fakePocketBase(t, &calls) _, err := Get[record](context.Background(), New(srv.URL, "a", "b"), "workspaces", "missing") if !IsNotFound(err) { t.Fatalf("err = %v, want not found", err) } }