| 1 | package workspacestate |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "reflect" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func TestLoadSnapshotsAreIndependentAndObserveOtherWriters(t *testing.T) { |
| 12 | path := filepath.Join(t.TempDir(), "registry.json") |
| 13 | original := []byte(`{"version":3,"generation":7,"workspaceIds":["global"],"workspaces":{"global":{"id":"global","title":"Global","sessionIds":["s"],"organization":{"revision":3,"order":["session:s"],"groups":[],"imported":{}},"futureWorkspace":{"keep":true}}},"sessionStates":{"s":{"lifecycle":"active"}},"futureRoot":{"keep":true}}`) |
| 14 | if err := os.WriteFile(path, original, 0600); err != nil { |
| 15 | t.Fatal(err) |
| 16 | } |
| 17 | store := NewStore(path) |
| 18 | first, err := store.Load(t.Context()) |
| 19 | if err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | second, err := store.Load(t.Context()) |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | // Exercise maps, slices, nested pointers and retained unknown JSON bytes. |
| 27 | first.WorkspaceIDs[0] = "changed" |
| 28 | workspace := first.Workspaces[GlobalWorkspaceID] |
| 29 | workspace.SessionIDs[0] = "changed" |
| 30 | workspace.Organization.Order[0] = "changed" |
| 31 | workspace.extra["futureWorkspace"][0] = '!' |
| 32 | first.extra["futureRoot"][0] = '!' |
| 33 | delete(first.SessionStates, "s") |
| 34 | third, err := store.Load(t.Context()) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if !reflect.DeepEqual(second, third) { |
| 39 | t.Fatal("mutating one snapshot changed another read") |
| 40 | } |
| 41 | body, err := os.ReadFile(path) |
| 42 | if err != nil || !bytes.Equal(body, original) { |
| 43 | t.Fatalf("read-only loads changed the source: %v", err) |
| 44 | } |
| 45 | // A separate Store represents another process writing the same registry. |
| 46 | if err := NewStore(path).RenameWorkspace(t.Context(), GlobalWorkspaceID, "Updated"); err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | latest, err := store.Load(t.Context()) |
| 50 | if err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | if latest.Generation != second.Generation+1 || latest.Workspaces[GlobalWorkspaceID].Title != "Updated" { |
| 54 | t.Fatal("existing reader did not observe the external write") |
| 55 | } |
| 56 | if second.Workspaces[GlobalWorkspaceID].Title != "Global" { |
| 57 | t.Fatal("external write changed a previously returned snapshot") |
| 58 | } |
| 59 | if !bytes.Equal(latest.extra["futureRoot"], second.extra["futureRoot"]) || |
| 60 | !bytes.Equal(latest.Workspaces[GlobalWorkspaceID].extra["futureWorkspace"], second.Workspaces[GlobalWorkspaceID].extra["futureWorkspace"]) { |
| 61 | t.Fatal("external mutation lost unknown fields") |
| 62 | } |
| 63 | } |
| 64 |