// SPDX-License-Identifier: AGPL-3.0-or-later package pbschema import ( "encoding/json" "testing" ) func TestSnapshot(t *testing.T) { cols, err := Collections() if err != nil { t.Fatal(err) } names := map[string]bool{} for _, c := range cols { name := c["name"].(string) if name[0] == '_' { t.Errorf("system collection %s in the snapshot", name) } names[name] = true if name == "users" { if _, ok := c["oauth2"]; ok { t.Error("users.oauth2 is admin-managed and must not be in the snapshot") } if _, ok := c["otp"].(map[string]any)["enabled"]; ok { t.Error("users.otp.enabled is admin-managed and must not be in the snapshot") } } } for _, want := range []string{"users", "organizations", "pages", "instance_settings"} { if !names[want] { t.Errorf("snapshot has no %s collection", want) } } // Every relation must point at a collection in the snapshot. if err := remap(cols, nil); err != nil { t.Fatal(err) } } func TestRemap(t *testing.T) { var want []map[string]any _ = json.Unmarshal([]byte(`[ {"id": "snap_orgs", "name": "organizations", "fields": [ {"id": "f_name", "name": "name", "type": "text"}, {"id": "f_new", "name": "slug", "type": "text"}]}, {"id": "snap_pages", "name": "pages", "fields": [ {"id": "f_org", "name": "organization", "type": "relation", "collectionId": "snap_orgs"}]} ]`), &want) have := []existingCollection{{ID: "live_orgs", Name: "organizations"}} have[0].Fields = append(have[0].Fields, struct { ID string `json:"id"` Name string `json:"name"` }{ID: "live_name", Name: "name"}) if err := remap(want, have); err != nil { t.Fatal(err) } orgs, pages := want[0], want[1] if orgs["id"] != "live_orgs" { t.Errorf("existing collection id = %v, want live_orgs", orgs["id"]) } fields := orgs["fields"].([]any) if id := fields[0].(map[string]any)["id"]; id != "live_name" { t.Errorf("existing field id = %v, want live_name", id) } if id := fields[1].(map[string]any)["id"]; id != "f_new" { t.Errorf("new field id = %v, want f_new", id) } if pages["id"] != "snap_pages" { t.Errorf("new collection id = %v, want snap_pages", pages["id"]) } rel := pages["fields"].([]any)[0].(map[string]any) if rel["collectionId"] != "live_orgs" { t.Errorf("relation target = %v, want live_orgs", rel["collectionId"]) } } func TestRemapUnknownRelation(t *testing.T) { var want []map[string]any _ = json.Unmarshal([]byte(`[{"id": "a", "name": "a", "fields": [ {"id": "r", "name": "r", "type": "relation", "collectionId": "missing"}]}]`), &want) if err := remap(want, nil); err == nil { t.Fatal("expected an error for a relation to an unknown collection") } }