package fleet import ( "context" "errors" "testing" "time" ) func TestHostAuto(t *testing.T) { hostPoll = 5 * time.Millisecond dir := t.TempDir() ctx, cancel := context.WithCancel(context.Background()) defer cancel() m, err := Open(ctx, dir, exclTestRunner{}, 1) if err != nil { t.Fatal(err) } srv, err := m.Add(Server{Name: "s1", Host: "h1", Enabled: true, Targets: []Target{{User: "root"}}}) if err != nil { t.Fatal(err) } tid := srv.Targets[0].ID m.scans[Key(srv.ID, tid)] = &Scan{Stacks: []Stack{ {Dir: "/home/a", Name: "a", Status: StatusUpdates}, {Dir: "/home/b", Name: "b", Status: StatusUpToDate}, {Dir: "/home/c", Name: "c", Status: StatusUpdates}, {Dir: "/home/d", Name: "d", Status: StatusStopped}, }} if err := m.SetExcluded(srv.ID, tid, "/home/b", true); err != nil { t.Fatal(err) } if err := m.SetAuto(srv.ID, tid, "/home/c", "0 0 1 1 *", "test"); err != nil { t.Fatal(err) } if err := m.SetHostAuto(srv.ID, "* 25 * * *", "test"); !errors.Is(err, ErrInvalid) { t.Fatalf("planification invalide : %v", err) } if err := m.SetHostAuto("inconnu", "@daily", "test"); !errors.Is(err, ErrNotFound) { t.Fatalf("serveur inconnu : %v", err) } if err := m.SetHostAuto(srv.ID, "0 3 * * *", "test"); err != nil { t.Fatal(err) } if v := m.Snapshot()[0]; v.Auto == nil || v.Auto.Schedule != "0 3 * * *" || v.Auto.Next.IsZero() { t.Fatalf("planification non affichee : %+v", v.Auto) } // Echeance : seule /home/a est traitee (b exclue, c planifiee a part, d arretee). m.hostTick(time.Date(2026, 1, 1, 3, 0, 0, 0, time.Local)) deadline := time.Now().Add(5 * time.Second) var h HostAuto for { m.mu.Lock() h = *m.hostAuto[srv.ID] m.mu.Unlock() if !h.running { break } if time.Now().After(deadline) { t.Fatal("execution non terminee") } time.Sleep(5 * time.Millisecond) } if len(h.Results) != 1 || h.Results[0].Dir != "/home/a" || h.LastRun.IsZero() { t.Fatalf("resultats : %+v", h) } if h.LastOK || h.Results[0].OK { // exclTestRunner ne repond rien t.Fatalf("echec attendu : %+v", h) } // Persistance. m2, err := Open(ctx, dir, exclTestRunner{}, 1) if err != nil { t.Fatal(err) } if e := m2.hostAuto[srv.ID]; e == nil || e.Schedule != "0 3 * * *" || len(e.Results) != 1 { t.Fatal("planification non relue") } // Desactivation, puis suppression du serveur. if err := m.SetHostAuto(srv.ID, "", "test"); err != nil || m.hostAuto[srv.ID] != nil { t.Fatalf("desactivation : %v", err) } if err := m.SetHostAuto(srv.ID, "@daily", "test"); err != nil { t.Fatal(err) } if err := m.Delete(srv.ID); err != nil { t.Fatal(err) } if len(m.hostAuto) != 0 { t.Fatalf("planifications restantes : %v", m.hostAuto) } }