Files
ilkerandClaude Opus 5 d67af5d6c3 hpcod: projects, and what a cluster cost
"How much did the protein run use" is a question about a piece of
work, not about c003-15. A tenant asks for clusters over months;
individually each one is an address, some hardware and a lease, and
nothing joined them up.

A project groups them, and is optional throughout. Somebody who wants
one cluster for an afternoon should not have to invent a project to
get it, and requiring one would mean every tenant carrying a
"default" that means nothing. The form does not even ask when there
are none: a field whose only option is "none" is a question with one
answer.

The cost side needed no new columns. The cluster record already said
when it was created and destroyed, and cluster_vm said how many cores
and how much memory it held; what was missing was anything that read
them. cluster_usage is that, and it is a view rather than a table
because a derived number stored is a number that can disagree with
what it was derived from. It works retroactively - every cluster this
estate has ever built now has a line.

Core-hours are reserved, not executed, and the view says so. That is
the honest unit for an on-demand cluster: the hardware was yours and
nobody else could have it, whether or not a job ran. What was
actually executed is a Slurm accounting question and there is no
slurmdbd.

The project is attached inside the allocating transaction, for the
same reason the placement and the applications are, and it is checked
there to be the tenant's own and still open - a cluster filed against
somebody else's project leaks what they are working on. Closing keeps
history and stops it being offered. There is no delete: the reference
from cluster is RESTRICT, because a project removed from under its
clusters leaves their cost attributed to nothing, and afterwards is
when the question gets asked.

A release now writes manifest.json beside home.tgz: the nodes, the
wall time, the core-hours. The database knows all of it and outlives
the cluster, but the tarball can be moved off this host and the
description travels with it. Not fatal if it fails - the data is
already safe by then, and holding hardware because a note could not
be written is the wrong trade.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 13:05:35 +02:00

668 lines
23 KiB
Go

package httpapi
import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/ilkermanap/hpcod/internal/catalog"
"github.com/ilkermanap/hpcod/internal/model"
"github.com/ilkermanap/hpcod/internal/provision"
"github.com/ilkermanap/hpcod/internal/spec"
"github.com/ilkermanap/hpcod/internal/store"
)
const planRequest = `
name: sim
head: { cores: 2, memory_gb: 4 }
compute: { count: 1, cores: 4, memory_gb: 8 }
`
func planServer(t *testing.T, f *fakeStore) *Server {
t.Helper()
s := testServerWithPages(t, f)
s.cache.set([]model.Site{{
ID: "hv01", Reachable: true, Healthy: true,
Nodes: []model.Node{{Name: "hv01", Online: true, Cores: 64, MemBytes: 256 << 30}},
}})
return s
}
func planPost(t *testing.T, s *Server, form url.Values, user string, admin bool) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(http.MethodPost, "/clusters/new", strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if user != "" {
r = r.WithContext(withUser(r.Context(), user, admin))
}
w := httptest.NewRecorder()
s.pagePlan(w, r)
return w
}
// The gap this closes: the page worked out that a cluster was possible and
// offered no way to have one.
func TestAFeasiblePlanOffersToCreateIt(t *testing.T) {
s := planServer(t, &fakeStore{})
w := planPost(t, s, url.Values{"request": {planRequest}}, "ilker", false)
if w.Code != http.StatusOK {
t.Fatalf("status %d", w.Code)
}
if !strings.Contains(w.Body.String(), "Build this cluster") {
t.Error("a feasible plan does not offer to build the cluster")
}
}
func TestAVisitorIsToldToSignInRatherThanShownAButton(t *testing.T) {
s := planServer(t, &fakeStore{})
w := planPost(t, s, url.Values{"request": {planRequest}}, "", false)
body := w.Body.String()
if strings.Contains(body, `name="do" value="create"`) {
t.Error("someone with no session was shown the create button")
}
if !strings.Contains(body, "Sign in to create") {
t.Error("the page does not say why there is no button")
}
}
func TestCreatingFromThePlanRecordsIt(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 3, ClusterID: 5, AccountingName: "c005-3", TenantName: "ilker", State: "requested",
}}
s := planServer(t, f)
w := planPost(t, s, url.Values{"request": {planRequest}, "do": {"create"}}, "ilker", false)
if w.Code != http.StatusSeeOther {
t.Fatalf("status %d, want 303; body %s", w.Code, w.Body)
}
if w.Header().Get("Location") != "/clusters" {
t.Errorf("redirected to %q", w.Header().Get("Location"))
}
// The tenant defaults to whoever asked: nobody should have to name
// themselves to get their own cluster.
if f.gotTenant != "ilker" || f.gotOwner != "ilker" {
t.Errorf("recorded tenant %q owner %q", f.gotTenant, f.gotOwner)
}
if f.gotPlacement.Site != "hv01" || len(f.gotPlacement.VMs) != 2 {
t.Errorf("placement %+v", f.gotPlacement)
}
}
// Naming someone else's tenant would be a way to spend their quota.
func TestOnlyAnAdminCreatesForSomebodyElse(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{SerialID: 1, AccountingName: "c001-1"}}
s := planServer(t, f)
req := planRequest + "tenant: someone-else\n"
w := planPost(t, s, url.Values{"request": {req}, "do": {"create"}}, "ilker", false)
if w.Code == http.StatusSeeOther {
t.Fatal("a non-admin created a cluster for another tenant")
}
if !strings.Contains(w.Body.String(), "cannot create a cluster for") {
t.Errorf("the refusal does not say why: %s", w.Body)
}
if f.gotTenant != "" {
t.Errorf("it was recorded anyway, for %q", f.gotTenant)
}
// An administrator may.
w = planPost(t, s, url.Values{"request": {req}, "do": {"create"}}, "theboss", true)
if w.Code != http.StatusSeeOther {
t.Fatalf("an admin got %d; body %s", w.Code, w.Body)
}
if f.gotTenant != "someone-else" {
t.Errorf("recorded tenant %q", f.gotTenant)
}
}
// An infeasible plan must not have a create button at all, and asking for
// one anyway must not produce a cluster.
func TestAnInfeasiblePlanCannotBeCreated(t *testing.T) {
f := &fakeStore{}
s := planServer(t, f)
req := planRequest + " require: [{capability: gpu}]\n"
// A request the fixture site cannot satisfy: no GPU anywhere.
bad := "name: sim\nhead: { cores: 2, memory_gb: 4 }\ncompute:\n count: 1\n cores: 4\n memory_gb: 8\n require:\n - capability: gpu\n"
_ = req
w := planPost(t, s, url.Values{"request": {bad}}, "ilker", false)
if strings.Contains(w.Body.String(), `name="do" value="create"`) {
t.Error("an infeasible plan offered a create button")
}
w = planPost(t, s, url.Values{"request": {bad}, "do": {"create"}}, "ilker", false)
if w.Code == http.StatusSeeOther {
t.Error("an infeasible plan was created anyway")
}
if f.gotTenant != "" {
t.Errorf("something was recorded: %q", f.gotTenant)
}
}
// The HTML page used to call placement directly, so it planned against
// hardware that was already promised to a cluster nobody had built yet.
func TestThePlanPageSubtractsReservations(t *testing.T) {
f := &fakeStore{reservations: []model.Reservation{
{Site: "hv01", HostNode: "hv01", NativeID: "0000:01:00.0", HeldBy: "c001-1"},
}}
s := testServerWithPages(t, f)
s.cache.set([]model.Site{{
ID: "hv01", Reachable: true, Healthy: true,
Nodes: []model.Node{{
Name: "hv01", Online: true, Cores: 64, MemBytes: 256 << 30,
Devices: []model.Device{{
NativeID: "0000:01:00.0", Capability: model.CapGPU,
Confidence: model.ConfClass, Passthrough: true,
}},
}},
}})
gpu := "name: sim\nhead: { cores: 2, memory_gb: 4 }\ncompute:\n count: 1\n cores: 4\n memory_gb: 8\n require:\n - capability: gpu\n"
w := planPost(t, s, url.Values{"request": {gpu}}, "ilker", false)
if strings.Contains(w.Body.String(), `name="do" value="create"`) {
t.Error("the page offered the only GPU, which is already reserved")
}
}
// The page used to ask for YAML. These are about the form that replaced
// it: what someone ticks and types has to arrive as the same request the
// document would have produced.
// planFields is a filled-in form, as the browser would send it.
func planFields() url.Values {
return url.Values{
"name": {"sim"},
"head_cores": {"2"},
"head_memory": {"4"},
"compute_count": {"1"},
"compute_cores": {"4"},
"compute_memory": {"8"},
}
}
func TestTheFormBuildsTheSameRequestTheDocumentDid(t *testing.T) {
s := planServer(t, &fakeStore{})
w := planPost(t, s, planFields(), "acme", false)
body := w.Body.String()
for _, want := range []string{"name: sim", "cores: 2", "count: 1", "memory_gb: 8"} {
if !strings.Contains(body, want) {
t.Errorf("the planned request does not carry %q:\n%s", want, body)
}
}
if !strings.Contains(body, "Build this cluster") {
t.Error("a feasible request built from the form was not offered")
}
}
// Required and preferred are different questions, and the row asks them
// separately: one refuses the request, the other is taken where it exists.
// Tested on the mapping itself rather than through the page, because a
// request naming hardware the fixture does not have is refused before it
// is ever rendered.
func TestCapabilityRowsBecomeRequireAndPrefer(t *testing.T) {
f := planForm{values: map[string]string{
"name": "sim", "head_cores": "2", "head_memory": "4",
"compute_count": "1", "compute_cores": "4", "compute_memory": "8",
"gpu_count": "2", "gpu_vendor": "nvidia", "gpu_how": "prefer",
"nvme_count": "1", "nvme_how": "require",
"infiniband_count": "1", "infiniband_speed": "200",
}}
req, err := f.request()
if err != nil {
t.Fatal(err)
}
if len(req.Compute.Prefer) != 1 {
t.Fatalf("prefer = %+v, want one entry", req.Compute.Prefer)
}
if g := req.Compute.Prefer[0]; g.Capability != model.CapGPU || g.Count != 2 || g.Vendor != "nvidia" {
t.Errorf("the preferred GPU came through as %+v", g)
}
got := map[model.Capability]spec.Constraint{}
for _, c := range req.Compute.Require {
got[c.Capability] = c
}
if c, ok := got[model.CapNVMe]; !ok || c.Count != 1 {
t.Errorf("required NVMe came through as %+v", c)
}
if c, ok := got[model.CapInfiniBand]; !ok || c.MinSpeedGb != 200 {
t.Errorf("the InfiniBand speed came through as %+v", c)
}
// A vendor on a fabric and a speed on a drive are questions with no
// useful answer, and the form does not ask them.
if c := got[model.CapNVMe]; c.Vendor != "" || c.MinSpeedGb != 0 {
t.Errorf("NVMe picked up a detail the form does not offer: %+v", c)
}
}
// A capability left at zero is not a constraint for zero of it.
func TestZeroMeansNotAsked(t *testing.T) {
f := planForm{values: map[string]string{
"name": "sim", "head_cores": "2", "head_memory": "4",
"compute_count": "1", "compute_cores": "4", "compute_memory": "8",
"gpu_count": "0", "gpu_vendor": "nvidia",
}}
req, err := f.request()
if err != nil {
t.Fatal(err)
}
if len(req.Compute.Require)+len(req.Compute.Prefer) != 0 {
t.Errorf("a capability nobody asked for became a constraint: %+v %+v",
req.Compute.Require, req.Compute.Prefer)
}
}
// Naming software is the point of the catalogue: the hardware it needs is
// added by the planner, not restated by the person asking.
func TestTickedApplicationsReachTheRequest(t *testing.T) {
f := planForm{values: map[string]string{
"name": "sim", "head_cores": "2", "head_memory": "4",
"compute_count": "1", "compute_cores": "4", "compute_memory": "8",
"apps": "gromacs:2024, openfoam",
}}
req, err := f.request()
if err != nil {
t.Fatal(err)
}
if len(req.Stack.Apps) != 2 || req.Stack.Apps[0] != "gromacs:2024" || req.Stack.Apps[1] != "openfoam" {
t.Errorf("apps came through as %q", req.Stack.Apps)
}
}
// A form that is refused comes back with what was typed in it. Re-rendering
// defaults after eleven fields is its own kind of refusal.
func TestARejectedFormKeepsWhatWasTyped(t *testing.T) {
s := planServer(t, &fakeStore{})
f := planFields()
f.Set("name", "") // required
f.Set("compute_cores", "16") // and not a default
w := planPost(t, s, f, "acme", false)
body := w.Body.String()
if !strings.Contains(body, "name is required") {
t.Errorf("the reason was not shown:\n%s", body)
}
if !strings.Contains(body, `value="16"`) {
t.Errorf("the typed value was thrown away:\n%s", body)
}
}
// Only an administrator may hold a cluster for somebody else, so only an
// administrator is asked who it is for.
func TestTheTenantFieldIsOfferedToAdminsOnly(t *testing.T) {
s := planServer(t, &fakeStore{})
r := httptest.NewRequest(http.MethodGet, "/clusters/new", nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w := httptest.NewRecorder()
s.pagePlan(w, r)
if strings.Contains(w.Body.String(), `name="tenant"`) {
t.Error("a tenant was asked who the cluster is for")
}
r = httptest.NewRequest(http.MethodGet, "/clusters/new", nil)
r = r.WithContext(withUser(r.Context(), "ilker", true))
w = httptest.NewRecorder()
s.pagePlan(w, r)
if !strings.Contains(w.Body.String(), `name="tenant"`) {
t.Error("an administrator was not")
}
}
// Every input the mapping reads has to exist on the page. The mapping
// tests pass without it: they build a request from values nobody could
// have typed, because the field was never rendered. That is exactly what
// happened - a bool flag named Speed beside a string named Speed, and the
// embedded one loses in a template, so neither InfiniBand nor RoCE was
// ever offered a link speed.
func TestEveryFieldTheFormReadsIsOnThePage(t *testing.T) {
s := planServer(t, &fakeStore{})
r := httptest.NewRequest(http.MethodGet, "/clusters/new", nil)
r = r.WithContext(withUser(r.Context(), "ilker", true))
w := httptest.NewRecorder()
s.pagePlan(w, r)
body := w.Body.String()
want := []string{
"name", "tenant", "lease",
"head_cores", "head_memory", "head_disk",
"compute_count", "compute_cores", "compute_memory",
}
for _, c := range capabilityFields() {
k := string(c.Cap)
want = append(want, k+"_count", k+"_how")
if c.AsksVendor {
want = append(want, k+"_vendor")
}
if c.AsksSpeed {
want = append(want, k+"_speed")
}
}
for _, f := range want {
if !strings.Contains(body, `name="`+f+`"`) {
t.Errorf("the form reads %q but never asks for it", f)
}
}
}
// waitFor spins until a condition holds, for the things that happen in a
// goroutine: a build is started by the request and finishes after it.
func waitFor(t *testing.T, cond func() bool, what string) {
t.Helper()
for i := 0; i < 200; i++ {
if cond() {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
// A fake tofu that succeeds and records that it ran.
func fakeTofu(t *testing.T, dir string) string {
t.Helper()
path := filepath.Join(dir, "fake-tofu")
if err := os.WriteFile(path,
[]byte("#!/bin/sh\necho \"called: $*\"\nsleep 0.2\n"), 0o755); err != nil {
t.Fatal(err)
}
return path
}
// withBuilder gives the test server a provisioner whose Terraform is a
// shell script, so the build path runs without touching a hypervisor.
func withBuilder(t *testing.T, s *Server, f *fakeStore) *Server {
t.Helper()
root := t.TempDir()
tmpl := filepath.Join(root, "template")
if err := os.MkdirAll(tmpl, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpl, "main.tf"), []byte("# wiring\n"), 0o640); err != nil {
t.Fatal(err)
}
s.builder = provision.NewRunner(f, provision.Options{
EnvRoot: filepath.Join(root, "envs"), Template: tmpl,
Binary: fakeTofu(t, root), MgmtCount: 40,
Timeout: 30 * time.Second,
// TEST-NET-1, which is guaranteed to route nowhere, and a wait
// measured in milliseconds. The build reaches the point where it
// waits for a head node; there is no head node here, and dialling
// a real management address from a unit test would reach whatever
// happens to be at it.
MgmtFirst: "192.0.2.10",
PortalWait: 200 * time.Millisecond,
})
return s
}
// Asking for a cluster and building it were two clicks on two pages, with
// the record sitting at "requested" in between. Nobody wants the record.
func TestCreatingAlsoBuildsAndOpensTheLog(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 3, ClusterID: 5, AccountingName: "c005-3", TenantName: "acme", State: "requested",
}}
s := withBuilder(t, planServer(t, f), f)
form := planFields()
form.Set("do", "create")
w := planPost(t, s, form, "acme", false)
if w.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want 303:\n%s", w.Code, w.Body)
}
loc := w.Header().Get("Location")
if !strings.HasPrefix(loc, "/clusters/watch?cluster=") {
t.Errorf("landed on %q, want the build log", loc)
}
waitFor(t, func() bool {
for _, st := range f.seenStates() {
if st == "provisioning" {
return true
}
}
return false
}, "the build to start")
// And let it finish before the temporary directory goes away, or the
// cleanup races a process still writing into it.
waitFor(t, func() bool { return !s.builder.Running(3) }, "the build to finish")
}
// Without a provisioner the record is all there is, and the list is where
// it makes sense to land.
func TestWithNoProvisionerCreatingStillJustRecords(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 3, ClusterID: 5, AccountingName: "c005-3", TenantName: "acme", State: "requested",
}}
s := planServer(t, f)
form := planFields()
form.Set("do", "create")
w := planPost(t, s, form, "acme", false)
if got := w.Header().Get("Location"); got != "/clusters" {
t.Errorf("landed on %q, want /clusters", got)
}
}
// The window follows the log by asking for the bytes it does not have.
// Re-sending a few hundred kilobytes every two seconds to append one line
// is most of a megabyte a minute for nothing.
func TestTheLogIsServedFromWhereTheReaderStopped(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 3, ClusterID: 5, AccountingName: "c005-3", TenantName: "acme", State: "provisioning",
}}
s := withBuilder(t, planServer(t, f), f)
dir := s.builder.Dir(3)
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(s.builder.LogPath(3), []byte("one\ntwo\n"), 0o640); err != nil {
t.Fatal(err)
}
get := func(from string, user string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodGet, "/clusters/log?cluster=3&from="+from, nil)
r = r.WithContext(withUser(r.Context(), user, false))
w := httptest.NewRecorder()
s.pageClusterLog(w, r)
return w
}
w := get("0", "acme")
if w.Body.String() != "one\ntwo\n" {
t.Errorf("from=0 gave %q", w.Body.String())
}
if got := w.Header().Get("X-Log-Size"); got != "8" {
t.Errorf("X-Log-Size = %q, want 8", got)
}
if got := w.Header().Get("X-Cluster-State"); got != "provisioning" {
t.Errorf("X-Cluster-State = %q", got)
}
// Caught up: nothing to send, and the size says so.
if w := get("8", "acme"); w.Body.Len() != 0 {
t.Errorf("from=8 gave %q, want nothing", w.Body.String())
}
// The build appends.
fh, err := os.OpenFile(s.builder.LogPath(3), os.O_APPEND|os.O_WRONLY, 0o640)
if err != nil {
t.Fatal(err)
}
_, _ = fh.WriteString("three\n")
fh.Close()
if w := get("8", "acme"); w.Body.String() != "three\n" {
t.Errorf("from=8 after an append gave %q, want just the new line", w.Body.String())
}
// A rebuild truncates the file, so an offset past the end is from a
// run that no longer exists: start again rather than serve nothing.
if w := get("9999", "acme"); w.Body.String() != "one\ntwo\nthree\n" {
t.Errorf("a stale offset gave %q, want the whole log", w.Body.String())
}
// Somebody else's log names their hypervisors and their addresses.
if w := get("0", "ilkermanap"); w.Code != http.StatusNotFound {
t.Errorf("a stranger got %d, want 404", w.Code)
}
}
// A build that has not written anything yet is not an error: the page is
// often opened in the same second the build starts.
func TestAnEmptyLogIsNotAnError(t *testing.T) {
f := &fakeStore{allocated: &store.Cluster{
SerialID: 3, ClusterID: 5, AccountingName: "c005-3", TenantName: "acme", State: "provisioning",
}}
s := withBuilder(t, planServer(t, f), f)
r := httptest.NewRequest(http.MethodGet, "/clusters/log?cluster=3", nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w := httptest.NewRecorder()
s.pageClusterLog(w, r)
if w.Code != http.StatusOK || w.Body.Len() != 0 || w.Header().Get("X-Log-Size") != "0" {
t.Errorf("code=%d body=%q size=%q", w.Code, w.Body.String(), w.Header().Get("X-Log-Size"))
}
}
// The claim this is all for, tested where a person would see it: publish an
// application while the portal is running and it appears on the page that
// offers them. Nothing here restarts anything.
func TestTheCreatePageShowsAnApplicationPublishedWhileRunning(t *testing.T) {
path := filepath.Join(t.TempDir(), "apps.yaml")
writeCatalogue := func(body string) {
t.Helper()
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
// mtime is second-granular on some filesystems, so a rewrite inside
// one second would look unchanged. Aged rather than slept for.
old := time.Now().Add(-2 * time.Second)
if err := os.Chtimes(path, old, old); err != nil {
t.Fatal(err)
}
}
writeCatalogue("apps:\n - name: busybox\n image: oras://r/busybox:musl\n")
s := planServer(t, &fakeStore{})
s.catalog = catalog.FromFile(path)
page := func() string {
t.Helper()
w := planPost(t, s, planFields(), "op", false)
if w.Code != http.StatusOK {
t.Fatalf("status = %d", w.Code)
}
return w.Body.String()
}
first := page()
if !strings.Contains(first, "busybox") {
t.Fatal("busybox is not on the page to begin with")
}
if strings.Contains(first, "stress-ng") {
t.Fatal("stress-ng is on the page before it was published")
}
writeCatalogue("apps:\n - name: busybox\n image: oras://r/busybox:musl\n" +
" - name: stress-ng\n version: 0.18.07\n image: oras://r/stress-ng:0.18.07\n")
second := page()
if !strings.Contains(second, "stress-ng") {
t.Errorf("an application published while the portal was running does not appear:\n%s", second)
}
if !strings.Contains(second, "busybox") {
t.Error("the application that was already there disappeared")
}
}
// A withdrawn version is in the catalogue file because that file is the
// record of what has been published. It must not be on the form: Resolve
// would refuse it anyway, at the end of a form the person had already
// filled in.
func TestTheCreatePageDoesNotOfferAWithdrawnVersion(t *testing.T) {
c := &catalog.Catalog{Apps: []catalog.App{
{Name: "gromacs", Version: "2024.4", Image: "oras://r/g:2024.4"},
{Name: "gromacs", Version: "2024.9", Image: "oras://r/g:2024.9",
StatusField: "withdrawn", StatusNote: "CVE-2025-0001"},
{Name: "lammps", Version: "2024", Image: "oras://r/l:2024",
StatusField: "deprecated", StatusNote: "superseded by 2025"},
}}
s := planServer(t, &fakeStore{})
s.catalog = catalog.Static(c)
body := planPost(t, s, planFields(), "op", false).Body.String()
if strings.Contains(body, "gromacs:2024.9") {
t.Error("a withdrawn version is on the form")
}
if !strings.Contains(body, "gromacs:2024.4") {
t.Error("the version that is still available vanished with it")
}
// Deprecated is offered, and says so. Hiding it would break the pin of
// everyone who named it deliberately.
if !strings.Contains(body, "lammps:2024") {
t.Error("a deprecated version is not offered")
}
if !strings.Contains(body, "deprecated") || !strings.Contains(body, "superseded by 2025") {
t.Error("a deprecated version is offered with nothing to say it is deprecated")
}
}
// A project is optional and a tenant sees only their own. Filing a cluster
// against somebody else's project would leak what they are working on.
func TestTheFormOffersOnlyYourOwnOpenProjects(t *testing.T) {
closed := time.Now()
f := &fakeStore{projects: []store.Project{
{ID: 1, TenantName: "acme", Name: "protein-folding"},
{ID: 2, TenantName: "acme", Name: "last-quarter", ClosedAt: &closed},
{ID: 3, TenantName: "someone-else", Name: "not-yours"},
}}
s := planServer(t, f)
r := httptest.NewRequest(http.MethodGet, "/clusters/new", nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w := httptest.NewRecorder()
s.pagePlan(w, r)
body := w.Body.String()
if !strings.Contains(body, "protein-folding") {
t.Error("the tenant's own open project was not offered")
}
if strings.Contains(body, "last-quarter") {
t.Error("a closed project was offered for new work")
}
if strings.Contains(body, "not-yours") {
t.Error("somebody else's project was offered")
}
if !strings.Contains(body, "— none —") {
t.Error("there is no way to file a cluster against no project")
}
}
// And with no projects at all the form does not ask: a field whose only
// option is "none" is a question with one answer.
func TestWithNoProjectsTheFormDoesNotAsk(t *testing.T) {
s := planServer(t, &fakeStore{})
r := httptest.NewRequest(http.MethodGet, "/clusters/new", nil)
r = r.WithContext(withUser(r.Context(), "acme", false))
w := httptest.NewRecorder()
s.pagePlan(w, r)
if strings.Contains(w.Body.String(), `name="project"`) {
t.Error("the form asked about projects when there are none")
}
}