Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
205 lines
7.8 KiB
Go
205 lines
7.8 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/images"
|
|
"git.kmalloc.org/squid/sonda/internal/jobs"
|
|
"git.kmalloc.org/squid/sonda/internal/storage"
|
|
)
|
|
|
|
type fakeJob struct {
|
|
started []bool
|
|
err error
|
|
running bool
|
|
stopped int
|
|
status jobs.Status
|
|
}
|
|
|
|
func (f *fakeJob) Start(refresh bool) error {
|
|
if f.err != nil {
|
|
return f.err
|
|
}
|
|
f.started = append(f.started, refresh)
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeJob) Stop() bool { f.stopped++; return f.running }
|
|
func (f *fakeJob) Status() jobs.Status { return f.status }
|
|
|
|
// jobCase is one of the jobs that go through the library: they all behave the same.
|
|
type jobCase struct {
|
|
name string
|
|
path string
|
|
running string // the error code when it is already running
|
|
keys []string // the counters of a summary
|
|
count string // the key of the outcomes the test fills in
|
|
outcome string // the outcome that this key counts
|
|
set func(*Deps, jobService)
|
|
}
|
|
|
|
var jobCases = []jobCase{
|
|
{"covers", "/api/v1/library/covers", "covers_job_running",
|
|
[]string{"checked", "from_files", "from_archive", "none", "skipped", "failed", "stopped"},
|
|
"from_files", images.OutcomeFromFiles, func(d *Deps, j jobService) { d.CoversJob = j }},
|
|
{"artist images", "/api/v1/library/artist-images", "artist_images_job_running",
|
|
[]string{"checked", "found", "none", "skipped", "failed", "stopped"},
|
|
"found", images.OutcomeFound, func(d *Deps, j jobService) { d.ArtistImagesJob = j }},
|
|
{"descriptions", "/api/v1/library/descriptions", "descriptions_job_running",
|
|
[]string{"checked", "found", "none", "skipped", "failed", "stopped"},
|
|
"found", images.OutcomeFound, func(d *Deps, j jobService) { d.DescriptionsJob = j }},
|
|
}
|
|
|
|
func newJobAPI(t *testing.T, jc jobCase) (http.Handler, *fakeJob, string, string) {
|
|
t.Helper()
|
|
fake := &fakeJob{}
|
|
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { jc.set(d, fake) })
|
|
admin := registerAndLogin(t, h)
|
|
// A second user who is not an admin.
|
|
cred := map[string]any{"email": "bob@example.org", "password": "longenough"}
|
|
if r := do(t, h, "POST", "/api/v1/users", admin, cred); r.Code != http.StatusCreated {
|
|
t.Fatalf("create bob: %d %v", r.Code, r.Body)
|
|
}
|
|
bob, _ := do(t, h, "POST", "/api/v1/auth/login", "", cred).Body["access_token"].(string)
|
|
return h, fake, admin, bob
|
|
}
|
|
|
|
func eachJob(t *testing.T, f func(t *testing.T, jc jobCase)) {
|
|
for _, jc := range jobCases {
|
|
t.Run(jc.name, func(t *testing.T) { f(t, jc) })
|
|
}
|
|
}
|
|
|
|
func TestOnlyAnAdminStartsOrStopsAJob(t *testing.T) {
|
|
eachJob(t, func(t *testing.T, jc jobCase) {
|
|
h, fake, admin, bob := newJobAPI(t, jc)
|
|
for _, m := range []string{"POST", "DELETE"} {
|
|
if r := do(t, h, m, jc.path, "", nil); r.Code != http.StatusUnauthorized {
|
|
t.Errorf("%s without a token: %d", m, r.Code)
|
|
}
|
|
if r := do(t, h, m, jc.path, bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
|
|
t.Errorf("%s as a user: %d %v", m, r.Code, r.Body)
|
|
}
|
|
}
|
|
if len(fake.started) != 0 || fake.stopped != 0 {
|
|
t.Error("something was started or stopped by someone who is not an admin")
|
|
}
|
|
if r := do(t, h, "GET", jc.path, "", nil); r.Code != http.StatusUnauthorized {
|
|
t.Errorf("status without a token: %d", r.Code)
|
|
}
|
|
if r := do(t, h, "GET", jc.path, bob, nil); r.Code != http.StatusOK {
|
|
t.Errorf("status for a user (like the scan status): %d", r.Code)
|
|
}
|
|
if r := do(t, h, "POST", jc.path, admin, nil); r.Code != http.StatusAccepted || r.Body["status"] != "started" {
|
|
t.Errorf("start: %d %v", r.Code, r.Body)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestAJobTakesAStrictRefreshParameter(t *testing.T) {
|
|
eachJob(t, func(t *testing.T, jc jobCase) {
|
|
h, fake, admin, _ := newJobAPI(t, jc)
|
|
for q, want := range map[string]bool{"": false, "?refresh=false": false, "?refresh=true": true} {
|
|
if r := do(t, h, "POST", jc.path+q, admin, nil); r.Code != http.StatusAccepted {
|
|
t.Fatalf("%q: %d %v", q, r.Code, r.Body)
|
|
}
|
|
if got := fake.started[len(fake.started)-1]; got != want {
|
|
t.Errorf("%q: refresh = %v, want %v", q, got, want)
|
|
}
|
|
}
|
|
n := len(fake.started)
|
|
for _, q := range []string{"?refresh=yes", "?refresh=1", "?refresh=true&refresh=false", "?refresh="} {
|
|
if r := do(t, h, "POST", jc.path+q, admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
|
|
t.Errorf("%q: %d %v, want 400", q, r.Code, r.Body)
|
|
}
|
|
}
|
|
if len(fake.started) != n {
|
|
t.Error("a request that was refused started a job")
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestAJobIsOneAtATime(t *testing.T) {
|
|
eachJob(t, func(t *testing.T, jc jobCase) {
|
|
h, fake, admin, _ := newJobAPI(t, jc)
|
|
fake.err = jobs.ErrRunning
|
|
if r := do(t, h, "POST", jc.path, admin, nil); r.Code != http.StatusConflict || errCode(r) != jc.running {
|
|
t.Errorf("%d %v, want 409 %s", r.Code, r.Body, jc.running)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestStoppingAJobIsAlwaysFine(t *testing.T) {
|
|
eachJob(t, func(t *testing.T, jc jobCase) {
|
|
h, fake, admin, _ := newJobAPI(t, jc)
|
|
for _, running := range []bool{true, false} {
|
|
fake.running = running
|
|
if r := do(t, h, "DELETE", jc.path, admin, nil); r.Code != http.StatusNoContent {
|
|
t.Errorf("running=%v: %d %v", running, r.Code, r.Body)
|
|
}
|
|
}
|
|
if fake.stopped != 2 {
|
|
t.Errorf("stopped %d times", fake.stopped)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestTheStatusOfAJobSaysWhatItIsDoingAndHowTheLastOneEnded(t *testing.T) {
|
|
eachJob(t, func(t *testing.T, jc jobCase) {
|
|
h, fake, admin, _ := newJobAPI(t, jc)
|
|
r := do(t, h, "GET", jc.path, admin, nil)
|
|
if r.Code != http.StatusOK || r.Body["running"] != false {
|
|
t.Fatalf("idle: %d %v", r.Code, r.Body)
|
|
}
|
|
sameKeys(t, "idle status", r.Body, "running")
|
|
|
|
started := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
|
|
fake.status = jobs.Status{Running: true, StartedAt: started, Progress: &jobs.Progress{Done: 3, Total: 10}}
|
|
r = do(t, h, "GET", jc.path, admin, nil)
|
|
sameKeys(t, "running status", r.Body, "running", "started_at", "progress")
|
|
p, _ := r.Body["progress"].(map[string]any)
|
|
if r.Body["running"] != true || r.Body["started_at"] != "2026-11-12T10:00:00Z" || p["done"] != float64(3) || p["total"] != float64(10) {
|
|
t.Errorf("running = %v", r.Body)
|
|
}
|
|
|
|
fake.status = jobs.Status{StartedAt: started, LastFinishedAt: started.Add(time.Minute), LastError: "gave up after 5 in a row failed",
|
|
Last: &jobs.Summary{Checked: 7, Failed: 5, Skipped: 1, Outcomes: map[string]int{jc.outcome: 1}}}
|
|
r = do(t, h, "GET", jc.path, admin, nil)
|
|
sameKeys(t, "finished status", r.Body, "running", "started_at", "last_finished_at", "last", "last_error")
|
|
last, _ := r.Body["last"].(map[string]any)
|
|
sameKeys(t, "last", last, jc.keys...)
|
|
if last["checked"] != float64(7) || last["failed"] != float64(5) || last["skipped"] != float64(1) || last["stopped"] != false ||
|
|
last[jc.count] != float64(1) || r.Body["last_error"] == "" {
|
|
t.Errorf("last = %v", r.Body)
|
|
}
|
|
})
|
|
}
|
|
|
|
// With the real job on the real stack: the albums of a library get their covers.
|
|
func TestTheCoversJobBuildsTheCoversOfTheLibrary(t *testing.T) {
|
|
e := newCoversEnv(t) // "With Art" has a cover.jpg in its folder, "Without" has nothing
|
|
repo := storage.NewImageRepo(e.db)
|
|
job := images.NewCoversJob(e.svc, repo)
|
|
if err := job.Start(t.Context(), jobs.Options{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
deadline := time.Now().Add(20 * time.Second)
|
|
for job.Status().Running {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the job did not finish")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
st := job.Status()
|
|
if st.Last == nil || st.Last.Checked != 2 || st.Last.Outcomes[images.OutcomeFromFiles] != 1 || st.Last.Outcomes[images.OutcomeNone] != 1 {
|
|
t.Errorf("last = %+v, want two albums: one cover from the files, one with none", st.Last)
|
|
}
|
|
// The cover is there without anybody having asked for it.
|
|
if rec, ok, _ := repo.Get(t.Context(), "album", e.withArt); !ok || rec.Status != images.StatusOK {
|
|
t.Errorf("record of the album with a picture: %+v ok=%v", rec, ok)
|
|
}
|
|
}
|