Files
supermarket/internal/web/backups_test.go
T
davidandClaude Opus 5.5 da16736fb4 Phase 10, part 9: the server package
compose.server.yaml runs Supermarket behind Caddy (HTTPS from Let's
Encrypt, Caddy's own CA or the team's), with Postgres on an internal
network and a nightly pg_dump kept two weeks. install-server.sh asks for
the domain, certificate and mail server, makes the secret key and database
password, starts it all and prints the setup link. Settings → Backups lists
the dumps on a server, and how the operator restores one. Checked end to
end in Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:37:34 -07:00

149 lines
5.4 KiB
Go

package web
import (
"bytes"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"supermarket/internal/db"
"sync/atomic"
"testing"
"time"
"supermarket/internal/backup"
"supermarket/internal/users"
)
func TestBackupsPage(t *testing.T) {
if db.OnPostgres() {
t.Skip("SQLite's own backups")
}
s, h := newTestServer(t, nil)
if body := do(h, http.MethodGet, "/settings/backups", nil, nil).Body.String(); !strings.Contains(body, "No backups yet") {
t.Errorf("empty: %s", body)
}
body := postForm(h, "/settings/backups/now", url.Values{"note": {"Before the import"}}).Body.String()
if !strings.Contains(body, "Backed up to app-") || !strings.Contains(body, "-manual-before-the-import.db") ||
!strings.Contains(body, "By you") || !strings.Contains(body, "before-the-import") {
t.Errorf("after backing up: %s", body)
}
bs, _ := backup.List(s.backupDir())
if len(bs) != 1 {
t.Fatalf("backups: %v", bs)
}
rec := do(h, http.MethodGet, "/settings/backups/file/"+bs[0].Name, nil, nil)
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Body.String(), "SQLite format 3") ||
!strings.Contains(rec.Header().Get("Content-Disposition"), bs[0].Name) {
t.Errorf("download: %d %v", rec.Code, rec.Header())
}
for _, bad := range []string{"..%2Fapp.db", "secrets.json", "app.db"} {
if rec := do(h, http.MethodGet, "/settings/backups/file/"+bad, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("%s: %d", bad, rec.Code)
}
}
// The daily one, once a day.
s.dailyBackup(time.Now())
s.dailyBackup(time.Now())
if bs, _ := backup.List(s.backupDir()); len(bs) != 2 {
t.Errorf("after the daily: %d", len(bs))
}
body = postForm(h, "/settings/backups/delete", url.Values{"name": {bs[0].Name}}).Body.String()
if !strings.Contains(body, "Deleted "+bs[0].Name) {
t.Errorf("delete: %s", body)
}
if _, err := os.Stat(bs[0].Path); err == nil {
t.Error("still there")
}
if body := postForm(h, "/settings/backups/delete", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There&#39;s no backup called") {
t.Errorf("bad delete: %s", body)
}
}
func TestRestoreFromThePage(t *testing.T) {
if db.OnPostgres() {
t.Skip("SQLite's own backups")
}
s, h := newTestServer(t, nil)
s.DB.PutJSON("test:value", "before")
b, err := backup.Make(s.DB.SQL, s.backupDir(), backup.Manual, "good", time.Now().Add(-time.Hour))
if err != nil {
t.Fatal(err)
}
s.DB.PutJSON("test:value", "after")
var restarts atomic.Int32
s.Restart = func() { restarts.Add(1) }
rec := postForm(h, "/settings/backups/restore", url.Values{"name": {b.Name}})
body := rec.Body.String()
if !strings.Contains(body, "Restoring "+b.Name) || !strings.Contains(body, "this page reloads by itself") ||
!strings.Contains(body, "A restore is waiting") || rec.Header().Get("Refresh") == "" {
t.Errorf("restore: %v %s", rec.Header(), body)
}
time.Sleep(700 * time.Millisecond)
if restarts.Load() != 1 || !backup.Pending(s.DataDir) {
t.Errorf("restarts %d, pending %v", restarts.Load(), backup.Pending(s.DataDir))
}
// Cancelled before the restart: nothing happens.
body = postForm(h, "/settings/backups/cancel", nil).Body.String()
if !strings.Contains(body, "The restore is cancelled") || backup.Pending(s.DataDir) {
t.Errorf("cancel: %s", body)
}
if body := postForm(h, "/settings/backups/restore", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There&#39;s no backup called") {
t.Errorf("bad name: %s", body)
}
}
func TestBackupUpload(t *testing.T) {
if db.OnPostgres() {
t.Skip("SQLite's own backups")
}
s, h := newTestServer(t, nil)
b, _ := backup.Make(s.DB.SQL, t.TempDir(), backup.Manual, "elsewhere", time.Now())
raw, _ := os.ReadFile(b.Path)
upload := func(name string, content []byte) string {
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, _ := mw.CreateFormFile("file", name)
fw.Write(content)
mw.Close()
return do(h, http.MethodPost, "/settings/backups/upload", &buf, map[string]string{"Content-Type": mw.FormDataContentType()}).Body.String()
}
body := upload("app-from-laptop.db", raw)
if !strings.Contains(body, "Uploaded as app-") || !strings.Contains(body, "-manual-uploaded-app-from-laptop.db") {
t.Errorf("upload: %s", body)
}
if body := upload("notes.txt", []byte("hello")); !strings.Contains(body, "isn&#39;t a Supermarket backup") {
t.Errorf("bad upload: %s", body)
}
if bs, _ := backup.List(s.backupDir()); len(bs) != 1 {
t.Errorf("backups: %v", bs)
}
left, _ := filepath.Glob(filepath.Join(s.backupDir(), ".upload-*"))
if len(left) != 0 {
t.Errorf("temporary files left: %v", left)
}
}
func TestServerBackupsPage(t *testing.T) {
if !db.OnPostgres() {
t.Skip("the server's backups page is Postgres's")
}
s, h := newServerEdition(t)
dir := t.TempDir()
s.Config.PGBackups = dir
os.WriteFile(filepath.Join(dir, "supermarket-2026-11-24.dump"), []byte("x"), 0o600)
os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("x"), 0o600)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, owner)
body := as(h, c, http.MethodGet, "/settings/backups", nil).Body.String()
if !strings.Contains(body, "supermarket-2026-11-24.dump") || strings.Contains(body, "notes.txt") || !strings.Contains(body, "pg_restore") {
t.Errorf("page: %s", body)
}
if rec := as(h, c, http.MethodPost, "/settings/backups/now", url.Values{}); rec.Code != http.StatusNotFound {
t.Errorf("back up now on Postgres: %d", rec.Code)
}
}