package operator_test import ( "context" "net/http/httptest" "testing" "testing/synctest" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/dataplane" "tangled.org/guid.foo/simmer/internal/world" ) // reviewer answers the caller of each token, as the API server's // TokenReview of a pod's projected token does. The fake API server // serves no TokenReviews, so this is the one piece of the data plane // that the tests replace. type reviewer map[string]dataplane.Caller func (r reviewer) Review(_ context.Context, token string) (dataplane.Caller, error) { caller, ok := r[token] if !ok { return dataplane.Caller{}, dataplane.ErrUnauthenticated } return caller, nil } // podOf runs a pod of a Job as the Job controller would: the labels // and the ServiceAccount of the Job's template, and the Job as its // controller. It names the pod for the Job and suffix, and answers the // pod's token. func (r *running) podOf(t *testing.T, tokens reviewer, job cluster.Job, suffix string) string { t.Helper() name := job.Name + "-" + suffix controller := true // The pods collection is ConsolePods' in the fake API server. Its // watch selects only Consoles' pods, so this pod reaches only the // data plane's read. r.w.Put(cluster.ConsolePods, &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: job.Namespace, Labels: job.Spec.Template.Labels, OwnerReferences: []metav1.OwnerReference{{APIVersion: "batch/v1", Kind: "Job", Name: job.Name, UID: job.UID, Controller: &controller}}, }, Spec: corev1.PodSpec{ServiceAccountName: job.Spec.Template.Spec.ServiceAccountName}, Status: corev1.PodStatus{Phase: corev1.PodRunning}, }) synctest.Wait() tokens[name] = dataplane.Caller{Namespace: job.Namespace, ServiceAccount: job.Spec.Template.Spec.ServiceAccountName, Pod: name} return name } // call sends one request to the data plane that serves the operator, // with the token of a pod, through the operator's metrics as Run // serves it. func (r *running) call(tokens reviewer, method, path, token string) *httptest.ResponseRecorder { server := r.o.ObserveDataPlane(dataplane.NewServer(r.store, r.o, tokens, dataplane.NewPodGetter(r.w.API.Client()), world.Namespace)) request := httptest.NewRequest(method, path, nil) request.Header.Set("Authorization", "Bearer "+token) recorder := httptest.NewRecorder() server.ServeHTTP(recorder, request) return recorder } // sessionJob answers the Job of a Session's turn. func (r *running) sessionJob(t *testing.T, name string) cluster.Job { t.Helper() job, ok := world.Get[cluster.Job](r.w, cluster.Jobs, "telemetry", name) if !ok { t.Fatalf("the Job %s does not exist", name) } return job }