Files
supermarket/internal/backup/backup_test.go
T
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -07:00

227 lines
7.1 KiB
Go

package backup
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func newDB(t *testing.T, path string) *sql.DB {
t.Helper()
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=journal_mode(WAL)")
if err != nil {
t.Fatal(err)
}
d.SetMaxOpenConns(1)
for _, q := range []string{`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)`, `INSERT INTO settings VALUES ('a', '1')`, `PRAGMA user_version = 7`} {
if _, err := d.Exec(q); err != nil {
t.Fatal(err)
}
}
return d
}
func TestMakeListFind(t *testing.T) {
dir := t.TempDir()
d := newDB(t, filepath.Join(dir, "app.db"))
defer d.Close()
bdir := Dir(dir)
now := time.Date(2026, 11, 22, 18, 30, 5, 0, time.Local)
b, err := Make(d, bdir, Manual, "Before the big import!", now)
if err != nil {
t.Fatal(err)
}
if b.Name != "app-20261122-183005-manual-before-the-big-import.db" || b.Schema != 7 || b.Size == 0 || b.Note != "before-the-big-import" {
t.Errorf("made: %+v", b)
}
if st, _ := os.Stat(b.Path); st.Mode().Perm() != 0o600 {
t.Errorf("mode: %v", st.Mode())
}
// Written after the backup: not in it.
d.Exec(`INSERT INTO settings VALUES ('b', '2')`)
cp, _ := sql.Open("sqlite", "file:"+b.Path+"?mode=ro")
var n int
cp.QueryRow(`SELECT count(*) FROM settings`).Scan(&n)
cp.Close()
if n != 1 {
t.Errorf("rows in the backup: %d", n)
}
if err := Check(b.Path); err != nil {
t.Errorf("check: %v", err)
}
// Same second: a different name.
b2, err := Make(d, bdir, Manual, "Before the big import!", now)
if err != nil || b2.Name == b.Name {
t.Errorf("second: %v %v", b2, err)
}
daily, _ := Make(d, bdir, Daily, "", now.Add(time.Hour))
os.WriteFile(filepath.Join(bdir, "notes.txt"), []byte("x"), 0o600)
os.WriteFile(filepath.Join(bdir, "app-20261101-000000-manual.db"), []byte("not a database"), 0o600)
bs, err := List(bdir)
if err != nil || len(bs) != 4 || bs[0].Name != daily.Name || bs[3].Schema != -1 || bs[3].Err == "" {
t.Fatalf("list: %+v %v", bs, err)
}
if err := Check(bs[3].Path); err == nil {
t.Error("a bad file passed the check")
}
if _, err := Find(bdir, "../app.db"); err == nil {
t.Error("found a file outside the list")
}
if err := Delete(bdir, daily.Name); err != nil {
t.Fatal(err)
}
if due, _ := DueDaily(bdir, now.Add(2*time.Hour)); !due {
t.Error("not due after deleting today's")
}
Make(d, bdir, Daily, "", now.Add(3*time.Hour))
if due, _ := DueDaily(bdir, now.Add(4*time.Hour)); due {
t.Error("due twice in a day")
}
if due, _ := DueDaily(bdir, now.Add(24*time.Hour)); !due {
t.Error("not due the next day")
}
}
func TestCheckNotSupermarket(t *testing.T) {
path := filepath.Join(t.TempDir(), "other.db")
d, _ := sql.Open("sqlite", "file:"+path)
d.Exec(`CREATE TABLE x (y)`)
d.Close()
if err := Check(path); err == nil || !strings.Contains(err.Error(), "not a Supermarket one") {
t.Errorf("check: %v", err)
}
}
func TestKeep(t *testing.T) {
var bs []Backup
start := time.Date(2026, 9, 1, 3, 0, 0, 0, time.Local)
for i := 0; i < 60; i++ { // 60 days of dailies
at := start.AddDate(0, 0, i)
bs = append(bs, Backup{Name: fileName(at, Daily, ""), At: at, Kind: Daily})
}
bs = append(bs, Backup{Name: "m", At: start, Kind: Manual}, Backup{Name: "g", At: start, Kind: Migration})
keep := Keep(bs)
var kept []string
for _, b := range bs {
if keep[b.Name] && b.Kind == Daily {
kept = append(kept, b.At.Format("01-02"))
}
}
// The newest 7 days, then the newest of each of 4 earlier weeks.
if len(kept) != 11 || !keep["m"] || !keep["g"] {
t.Errorf("kept %d dailies: %v", len(kept), kept)
}
last := start.AddDate(0, 0, 59)
for i := 0; i < 7; i++ {
if !keep[fileName(last.AddDate(0, 0, -i), Daily, "")] {
t.Errorf("day %d not kept", i)
}
}
}
func TestPrune(t *testing.T) {
dir := t.TempDir()
d := newDB(t, filepath.Join(dir, "app.db"))
defer d.Close()
bdir := Dir(dir)
start := time.Date(2026, 10, 1, 3, 0, 0, 0, time.Local)
for i := 0; i < 20; i++ {
if _, err := Make(d, bdir, Daily, "", start.AddDate(0, 0, i)); err != nil {
t.Fatal(err)
}
}
Make(d, bdir, Manual, "keep me", start)
n, err := Prune(bdir)
bs, _ := List(bdir)
if err != nil || n+len(bs) != 21 || len(bs) > 12 || !strings.Contains(bs[len(bs)-1].Name, "keep-me") {
t.Errorf("pruned %d, left %d: %v", n, len(bs), err)
}
}
func TestAdoptLegacy(t *testing.T) {
dir := t.TempDir()
// A copy taken with its -wal: its last rows are only in the -wal.
src := filepath.Join(t.TempDir(), "src.db")
d := newDB(t, src)
d.Exec(`PRAGMA wal_autocheckpoint = 0`)
d.Exec(`INSERT INTO settings VALUES ('only-in-wal', 'x')`)
for _, suffix := range []string{"", "-wal", "-shm"} {
raw, err := os.ReadFile(src + suffix)
if err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(dir, "app.db.pre-phase2-part3"+suffix), raw, 0o600)
}
d.Close()
// A broken one.
os.WriteFile(filepath.Join(dir, "app.db.pre-broken"), []byte("junk"), 0o600)
when := time.Date(2026, 11, 20, 9, 15, 0, 0, time.Local)
os.Chtimes(filepath.Join(dir, "app.db.pre-phase2-part3"), when, when)
var problems []string
n := AdoptLegacy(dir, func(name string, err error) { problems = append(problems, name+": "+err.Error()) })
if n != 1 || len(problems) != 1 || !strings.HasPrefix(problems[0], "app.db.pre-broken") {
t.Fatalf("moved %d; problems %v", n, problems)
}
bs, _ := List(Dir(dir))
if len(bs) != 1 || bs[0].Kind != Legacy || bs[0].Note != "phase2-part3" || !bs[0].At.Equal(when) {
t.Fatalf("adopted: %+v", bs)
}
cp, _ := sql.Open("sqlite", "file:"+bs[0].Path+"?mode=ro")
var v string
err := cp.QueryRow(`SELECT value FROM settings WHERE key = 'only-in-wal'`).Scan(&v)
cp.Close()
if err != nil {
t.Errorf("the -wal's rows were lost: %v", err)
}
for _, f := range []string{"app.db.pre-phase2-part3", "app.db.pre-phase2-part3-wal", "app.db.pre-phase2-part3-shm"} {
if _, err := os.Stat(filepath.Join(dir, f)); err == nil {
t.Errorf("%s is still there", f)
}
}
if _, err := os.Stat(filepath.Join(dir, "app.db.pre-broken")); err != nil {
t.Error("the broken copy was moved")
}
// Running again does nothing more.
if n := AdoptLegacy(dir, func(string, error) {}); n != 0 {
t.Errorf("second run moved %d", n)
}
}
func TestDeleteLeavesNoSidecars(t *testing.T) {
dir := t.TempDir()
name := "app-20261121-124721-legacy-phase2.db"
src := filepath.Join(t.TempDir(), "src.db")
d, err := sql.Open("sqlite", "file:"+src)
if err != nil {
t.Fatal(err)
}
d.Exec(`PRAGMA journal_mode = WAL`)
d.Exec(`CREATE TABLE settings (key TEXT, value TEXT)`)
d.Close()
raw, _ := os.ReadFile(src)
os.WriteFile(filepath.Join(dir, name), raw, 0o600)
if _, err := List(dir); err != nil { // reads each backup's schema
t.Fatal(err)
}
for _, suffix := range []string{"-wal", "-shm"} {
if _, err := os.Stat(filepath.Join(dir, name+suffix)); err == nil {
t.Errorf("listing made %s", suffix)
}
}
os.WriteFile(filepath.Join(dir, name+"-shm"), []byte("x"), 0o600)
if err := Delete(dir, name); err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(dir, "app-20261120-125700-legacy-phase1.db-wal"), nil, 0o600)
if n := RemoveOrphans(dir); n != 1 {
t.Errorf("orphans removed: %d", n)
}
if left, _ := filepath.Glob(filepath.Join(dir, "*")); len(left) != 0 {
t.Errorf("left: %v", left)
}
}