package plan3test import ( "encoding/json" "io" "log/slog" "path/filepath" "reflect" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/taskplan" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" ) func TestPlanMigrationUpgrade(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) path := filepath.Join(t.TempDir(), "upgrade.db") d, err := db.Open(path, logger) must(t, err) t.Cleanup(func() { must(t, d.Close()) }) old := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if m.ID != "equipo/0020_plans" && m.ID != "equipo/0032_plan_defaults" && m.ID != "equipo/0033_plan_notifications" { old.Add(m) } } _, err = migrate.Apply(ctx, d, old) must(t, err) f := &fixture{DB: d, Store: equipo.NewStore(d)} must(t, f.Store.Bootstrap(ctx, []string{owner.Address})) must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&f.TeamID)) f.exec(t, "INSERT INTO tasks(id,requester,request_id,project_id,revision,job_id,state,description,team_id,merge_owner) VALUES('historical',?,'request',4,7,0,'merged','old bug',?,?)", owner.Address, f.TeamID, owner.Address) audits := f.count(t, "SELECT count(*) FROM audit_events") result, err := migrate.Apply(ctx, d, equipo.BootSchema) must(t, err) if !reflect.DeepEqual(result.Applied, []string{"equipo/0020_plans", "equipo/0032_plan_defaults", "equipo/0033_plan_notifications"}) { t.Fatal("wrong migration", result.Applied) } var task equipo.Task must(t, d.G.First(&task, "id='historical'").Error) if task.Revision != 7 || task.State != "merged" || task.Description != "old bug" || task.Kind != taskplan.Bug || task.PlanRevision != 1 || task.ApprovalRevision != 0 || f.count(t, "SELECT count(*) FROM audit_events") != audits { t.Fatal("upgrade lost history", task) } var raw string must(t, d.Writer().QueryRow("SELECT plan FROM plan_revisions WHERE task_id='historical' AND revision=1").Scan(&raw)) var seeded taskplan.Plan must(t, json.Unmarshal([]byte(raw), &seeded)) if !reflect.DeepEqual(seeded, taskplan.BugPlan(task.ID, task.ProjectID)) { t.Fatal("migration did not seed BugPlan", seeded) } for i, st := range equipo.BugPlan(task) { if seeded.Steps[i].Key != st.Key { t.Fatal("seed changed legacy step identity") } } _, err = migrate.Apply(ctx, d, equipo.BootSchema) must(t, err) if f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id='historical'") != 1 { t.Fatal("history seeded twice") } for range 2 { x, err := team.OpenShared(ctx, d.Writer(), path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) must(t, err) must(t, x.Close()) } fresh := newFixture(t) upgraded, err := migrate.Read(ctx, d.Writer()) must(t, err) baseline, err := migrate.Read(ctx, fresh.DB.Writer()) must(t, err) if !upgraded.Equal(baseline) { t.Fatal("upgraded schema differs from fresh", upgraded.Diff(baseline)) } }