Files
pages/internal/store/path_snapshot_test.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

250 lines
8.9 KiB
Go

package store_test
import (
"errors"
"fmt"
"reflect"
"testing"
"pageswiki/internal/db"
"pageswiki/internal/store"
)
func pathSnapshotFixture(t *testing.T) (*store.Store, string, string) {
t.Helper()
filename := t.TempDir() + "/paths.db"
database, err := db.Open(filename)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := db.Migrate(database); err != nil {
t.Fatal(err)
}
st := store.NewWithDocumentRoot(database, t.TempDir()+"/documents")
return st, mustDefaultDomainUUID(t, st), filename
}
func makeSnapshotPage(t *testing.T, st *store.Store, domain, path string) string {
t.Helper()
object, err := st.CreatePageAtPathInDomain(domain, path)
if err != nil {
t.Fatal(err)
}
return object
}
func requirePathSnapshot(t *testing.T, st *store.Store, domain, root string, recursive bool) *store.PathMutationSnapshot {
t.Helper()
snapshot, err := st.SnapshotPathsInDomain(domain, root, recursive)
if err != nil {
t.Fatal(err)
}
return snapshot
}
func runCheckedMutation(st *store.Store, domain, action string, snapshot *store.PathMutationSnapshot) (int, error) {
switch action {
case "rename":
return st.RenamePathsInDomainChecked(domain, snapshot.Root(), "/target", true, snapshot)
case "copy":
return st.CopyPathsInDomainChecked(domain, snapshot.Root(), "/target", true, snapshot)
default:
return st.RemovePathsInDomainChecked(domain, []*store.PathMutationSnapshot{snapshot})
}
}
func TestPathMutationPrefixesAreLiteralCaseSensitiveAndNormalized(t *testing.T) {
for _, action := range []string{"rename", "copy", "remove"} {
t.Run(action, func(t *testing.T) {
st, domain, _ := pathSnapshotFixture(t)
root := `/Case%_\`
expected := []string{root, root + "/child", root + "/child/deeper"}
outside := []string{`/case%_\/child`, `/CaseXY\/child`, `/Case%_\-neighbor/child`, `/Case%_\0/child`, "/elsewhere"}
bindings := map[string]string{}
for _, path := range append(append([]string{}, expected...), outside...) {
bindings[path] = makeSnapshotPage(t, st, domain, path)
}
snapshot := requirePathSnapshot(t, st, domain, " "+root+"/// ", true)
if !reflect.DeepEqual(snapshot.Paths(), expected) {
t.Fatalf("snapshot = %#v, want %#v", snapshot.Paths(), expected)
}
// The caller cannot mutate the store-issued snapshot through Paths().
paths := snapshot.Paths()
paths[0] = "/elsewhere"
count, err := runCheckedMutation(st, domain, action, snapshot)
if err != nil || count != len(expected) {
t.Fatalf("%s = %d, %v", action, count, err)
}
for _, path := range outside {
if object, err := st.ResolvePathInDomain(domain, path); err != nil || object != bindings[path] {
t.Fatalf("unrelated %q changed: %q, %v", path, object, err)
}
}
for _, path := range expected {
if action != "copy" && st.PathExistsInDomain(domain, path) {
t.Fatalf("source still present: %s", path)
}
if action != "remove" {
destination := "/target" + path[len(root):]
object, err := st.ResolvePathInDomain(domain, destination)
if err != nil || (action == "rename" && object != bindings[path]) || (action == "copy" && object == bindings[path]) {
t.Fatalf("destination %q = %q, %v", destination, object, err)
}
}
}
})
}
}
func TestCheckedPathMutationRejectsConcurrentNamespaceChange(t *testing.T) {
for _, action := range []string{"rename", "copy", "remove"} {
for _, change := range []string{"added", "removed", "rebound"} {
t.Run(action+"/"+change, func(t *testing.T) {
st, domain, filename := pathSnapshotFixture(t)
makeSnapshotPage(t, st, domain, "/source/checked")
snapshot := requirePathSnapshot(t, st, domain, "/source", true)
// A second connection represents a different request committing
// after enumeration/authorization but before the mutation begins.
other, err := db.Open(filename)
if err != nil {
t.Fatal(err)
}
defer other.Close()
writer := store.New(other)
done := make(chan error, 1)
go func() {
switch change {
case "added":
_, err := writer.CreatePageAtPathInDomain(domain, "/source/unchecked")
done <- err
case "removed":
done <- writer.RemovePathInDomain(domain, "/source/checked")
case "rebound":
object, err := writer.CreateObject("page")
if err == nil {
err = writer.BindPathInDomain(domain, "/source/checked", object)
}
done <- err
}
}()
if err := <-done; err != nil {
t.Fatal(err)
}
before := pathMutationState(t, st)
count, err := runCheckedMutation(st, domain, action, snapshot)
if !errors.Is(err, store.ErrPathSnapshotChanged) || count != 0 {
t.Fatalf("stale snapshot accepted: %d, %v", count, err)
}
if after := pathMutationState(t, st); !reflect.DeepEqual(before, after) {
t.Fatalf("rejected %s changed state: before %#v, after %#v", action, before, after)
}
})
}
}
}
func pathMutationState(t *testing.T, st *store.Store) []string {
t.Helper()
rows, err := st.DB.Query(`SELECT 'path:'||domain_uuid||':'||path||':'||object_uuid FROM paths
UNION ALL SELECT 'object:'||uuid FROM objects
UNION ALL SELECT 'revision:'||uuid||':'||object_uuid FROM revisions ORDER BY 1`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
var state []string
for rows.Next() {
var item string
if err := rows.Scan(&item); err != nil {
t.Fatal(err)
}
state = append(state, item)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return state
}
func TestCheckedPathMutationsRollbackAfterPartialWrites(t *testing.T) {
for _, action := range []string{"rename", "copy", "remove"} {
t.Run(action, func(t *testing.T) {
st, domain, _ := pathSnapshotFixture(t)
for _, path := range []string{"/source/one.txt", "/source/two.txt"} {
object := makeSnapshotPage(t, st, domain, path)
if _, err := st.SaveRevision(object, "test", "initial"); err != nil {
t.Fatal(err)
}
}
snapshot := requirePathSnapshot(t, st, domain, "/source", true)
before := pathMutationState(t, st)
if _, err := st.DB.Exec(`CREATE TABLE path_test_writes(value INTEGER)`); err != nil {
t.Fatal(err)
}
verb := "INSERT"
if action == "remove" {
verb = "DELETE"
}
// Abort the second write, proving the first write and cloned Object/
// Revision rows are not leaked by a failed multi-Path operation.
trigger := fmt.Sprintf(`CREATE TRIGGER fail_path_write BEFORE %s ON paths BEGIN
INSERT INTO path_test_writes(value) VALUES(1);
SELECT CASE WHEN (SELECT COUNT(*) FROM path_test_writes)=2 THEN RAISE(ABORT,'injected failure') END;
END`, verb)
if _, err := st.DB.Exec(trigger); err != nil {
t.Fatal(err)
}
if _, err := runCheckedMutation(st, domain, action, snapshot); err == nil {
t.Fatal("injected write failure was ignored")
}
if after := pathMutationState(t, st); !reflect.DeepEqual(before, after) {
t.Fatalf("rollback failed: before %#v, after %#v", before, after)
}
var writes int
if err := st.DB.QueryRow(`SELECT COUNT(*) FROM path_test_writes`).Scan(&writes); err != nil || writes != 0 {
t.Fatalf("trigger side effects survived rollback: %d, %v", writes, err)
}
})
}
}
func TestCheckedPathSnapshotsCannotChangeScope(t *testing.T) {
st, domain, _ := pathSnapshotFixture(t)
makeSnapshotPage(t, st, domain, "/source")
makeSnapshotPage(t, st, domain, "/source/child")
snapshot := requirePathSnapshot(t, st, domain, "/source", false)
for _, action := range []string{"rename", "copy"} {
if _, err := runCheckedMutation(st, domain, action, snapshot); !errors.Is(err, store.ErrPathSnapshotChanged) {
t.Fatalf("non-recursive snapshot expanded by %s: %v", action, err)
}
}
for _, snapshot := range []*store.PathMutationSnapshot{nil, {}} {
if _, err := st.RenamePathsInDomainChecked(domain, "/source", "/target", false, snapshot); !errors.Is(err, store.ErrPathSnapshotChanged) {
t.Fatalf("missing or forged snapshot accepted: %v", err)
}
}
child := requirePathSnapshot(t, st, domain, "/source/child", false)
parent := requirePathSnapshot(t, st, domain, "/source", true)
count, err := st.RemovePathsInDomainChecked(domain, []*store.PathMutationSnapshot{child, parent})
if err != nil || count != 2 {
t.Fatalf("overlapping selection = %d, %v", count, err)
}
}
func TestPathMutationSnapshotBound(t *testing.T) {
st, domain, _ := pathSnapshotFixture(t)
object := makeSnapshotPage(t, st, domain, "/root")
if _, err := st.DB.Exec(`WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<?)
INSERT INTO paths(domain_uuid,path,object_uuid,created_at)
SELECT ?, '/root/'||n, ?, 1 FROM numbers`, store.MaxPathMutationPaths, domain, object); err != nil {
t.Fatal(err)
}
if _, err := st.SnapshotPathsInDomain(domain, "/root", true); !errors.Is(err, store.ErrPathMutationTooLarge) {
t.Fatalf("oversized snapshot accepted: %v", err)
}
if _, err := st.RenamePathsInDomain(domain, "/root", "/target", true); !errors.Is(err, store.ErrPathMutationTooLarge) {
t.Fatalf("oversized trusted mutation accepted: %v", err)
}
}