package activator import ( "context" "errors" "os/exec" "testing" "github.com/carlosframework/platform/internal/cgroup" "github.com/carlosframework/platform/internal/hostbox" "github.com/carlosframework/platform/internal/hostwrite" ) type claimSpawnWork struct { deny bool calls *int } func (w claimSpawnWork) With(_ context.Context, _ hostwrite.Identity, fn func() error) error { *w.calls++ if w.deny { return hostwrite.ErrUnavailable } return fn() } func TestClaimSpawnNeverFallsBack(t *testing.T) { calls, builds := 0, 0 build := func() *exec.Cmd { builds++; return exec.Command("must-not-execute") } for _, deny := range []bool{true, false} { cmd, prepared, err := spawnClaimed(context.Background(), true, nil, "shop.example", cgroup.TierDefault, claimSpawnWork{deny, &calls}, hostwrite.Identity{}, build) if err == nil || cmd != nil || prepared != nil { t.Fatal(cmd, prepared, err) } if !errors.Is(err, hostbox.ErrUnsupported) { t.Fatal(err) } } if builds != 0 || calls != 0 { t.Fatal(builds, calls) } } // spawnClaimedGen is closed: an invalid argument answers // hostwrite.ErrUnavailable, and every other call answers // ErrClaimIsolationUnavailable, whatever the work would decide. It never // enters the host write, never calls before and never builds the command. func TestClaimSpawnGenNeverFallsBack(t *testing.T) { calls, builds := 0, 0 beforeCalled := false build := func() *exec.Cmd { builds++; return exec.Command("must-not-execute") } before := func() error { beforeCalled = true; return nil } if _, _, err := spawnClaimedGen(context.Background(), nil, 1, cgroup.TierDefault, claimSpawnWork{false, &calls}, hostwrite.Identity{}, build, before); !errors.Is(err, hostwrite.ErrUnavailable) { t.Fatalf("nil parent: %v", err) } if _, _, err := spawnClaimedGen(context.Background(), &cgroup.Prepared{}, 0, cgroup.TierDefault, claimSpawnWork{false, &calls}, hostwrite.Identity{}, build, before); !errors.Is(err, hostwrite.ErrUnavailable) { t.Fatalf("generation 0: %v", err) } if calls != 0 { t.Fatalf("host write entered %d times for invalid arguments", calls) } for _, deny := range []bool{true, false} { beforeCalled = false cmd, child, err := spawnClaimedGen(context.Background(), &cgroup.Prepared{}, 7, cgroup.TierDefault, claimSpawnWork{deny, &calls}, hostwrite.Identity{}, build, before) if cmd != nil || child != nil { t.Fatalf("deny=%v: cmd=%v child=%v", deny, cmd, child) } if !errors.Is(err, ErrClaimIsolationUnavailable) { t.Fatalf("deny=%v: err=%v, want ErrClaimIsolationUnavailable", deny, err) } if beforeCalled { t.Fatalf("deny=%v: before was called", deny) } } if builds != 0 || calls != 0 { t.Fatalf("builds=%d calls=%d, want 0 and 0", builds, calls) } }