Datasets:
CrossSWE-Bench / instances /cloudnative-controller-runtime-3509 /tests /native /controller-native-contract_test.go
Download instances/cloudnative-controller-runtime-3509/tests/native/controller-native-contract_test.go from CrossSWE/CrossSWE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 7.91 kB
-
https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/instances/cloudnative-controller-runtime-3509/tests/native/controller-native-contract_test.go
- Command line
-
hf download hf://datasets/CrossSWE/CrossSWE-Bench/instances/cloudnative-controller-runtime-3509/tests/native/controller-native-contract_test.go
-
curl -L -o controller-native-contract_test.go https://huggingface.co/datasets/CrossSWE/CrossSWE-Bench/resolve/main/instances/cloudnative-controller-runtime-3509/tests/native/controller-native-contract_test.go
7.91 kB
| package crossrepo_annotation_gate_test | |
| import ( | |
| "bytes" | |
| "context" | |
| "encoding/json" | |
| "fmt" | |
| "io" | |
| "net/http" | |
| "reflect" | |
| "strings" | |
| "testing" | |
| "time" | |
| "github.com/go-logr/logr" | |
| corev1 "k8s.io/api/core/v1" | |
| eventsv1 "k8s.io/api/events/v1" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| "k8s.io/apimachinery/pkg/runtime" | |
| "k8s.io/apimachinery/pkg/types" | |
| "k8s.io/client-go/kubernetes/scheme" | |
| "k8s.io/client-go/rest" | |
| "k8s.io/client-go/tools/events" | |
| "k8s.io/client-go/tools/record" | |
| internalrecorder "sigs.k8s.io/controller-runtime/pkg/internal/recorder" | |
| publicrecorder "sigs.k8s.io/controller-runtime/pkg/recorder" | |
| ) | |
| // This interface describes the public callable contract without importing a | |
| // newly added named interface. Missing support therefore fails an executed | |
| // assertion in compilable worlds, rather than being a test-only compile error. | |
| type annotatedRecorder interface { | |
| AnnotatedEventf(runtime.Object, runtime.Object, map[string]string, string, string, string, string, ...interface{}) | |
| } | |
| type eventSink struct{ received chan *eventsv1.Event } | |
| func (s *eventSink) Create(_ context.Context, event *eventsv1.Event) (*eventsv1.Event, error) { | |
| s.received <- event.DeepCopy() | |
| return event.DeepCopy(), nil | |
| } | |
| func (s *eventSink) Update(_ context.Context, event *eventsv1.Event) (*eventsv1.Event, error) { | |
| s.received <- event.DeepCopy() | |
| return event.DeepCopy(), nil | |
| } | |
| func (s *eventSink) Patch(_ context.Context, event *eventsv1.Event, _ []byte) (*eventsv1.Event, error) { | |
| s.received <- event.DeepCopy() | |
| return event.DeepCopy(), nil | |
| } | |
| type transportFunc func(*http.Request) (*http.Response, error) | |
| func (f transportFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } | |
| func newProvider(t *testing.T) (publicrecorder.Provider, *eventSink, <-chan *corev1.Event) { | |
| t.Helper() | |
| sink := &eventSink{received: make(chan *eventsv1.Event, 16)} | |
| legacy := make(chan *corev1.Event, 16) | |
| client := &http.Client{Transport: transportFunc(func(req *http.Request) (*http.Response, error) { | |
| body, err := io.ReadAll(req.Body) | |
| if err != nil { | |
| return nil, err | |
| } | |
| if req.Method != http.MethodPost || req.URL.Path != "/api/v1/namespaces/contract-ns/events" { | |
| return nil, fmt.Errorf("unexpected legacy request: %s %s", req.Method, req.URL.Path) | |
| } | |
| var event corev1.Event | |
| if err := json.Unmarshal(body, &event); err != nil { | |
| return nil, err | |
| } | |
| legacy <- event.DeepCopy() | |
| return &http.Response{StatusCode: http.StatusCreated, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(bytes.NewReader(body)), Request: req}, nil | |
| })} | |
| ctx, cancel := context.WithCancel(context.Background()) | |
| oldBroadcaster := record.NewBroadcaster(record.WithContext(ctx)) | |
| broadcaster := events.NewBroadcaster(sink) | |
| provider, err := internalrecorder.NewProvider( | |
| &rest.Config{Host: "http://contract.invalid", ContentConfig: rest.ContentConfig{ContentType: "application/json"}}, | |
| client, scheme.Scheme, logr.Discard(), | |
| func() (record.EventBroadcaster, events.EventBroadcaster, bool) { | |
| return oldBroadcaster, broadcaster, true | |
| }, | |
| ) | |
| if err != nil { | |
| cancel() | |
| t.Fatalf("create actual controller-runtime provider: %v", err) | |
| } | |
| t.Cleanup(func() { | |
| shutdown, stop := context.WithTimeout(context.Background(), 3*time.Second) | |
| defer stop() | |
| provider.Stop(shutdown) | |
| cancel() | |
| }) | |
| return provider, sink, legacy | |
| } | |
| func pod(name, uid string) *corev1.Pod { | |
| return &corev1.Pod{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"}, ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "contract-ns", UID: types.UID(uid)}} | |
| } | |
| func receive(t *testing.T, sink *eventSink) *eventsv1.Event { | |
| t.Helper() | |
| select { | |
| case event := <-sink.received: | |
| return event | |
| case <-time.After(8 * time.Second): | |
| t.Fatal("actual event broadcaster emitted no sink payload") | |
| return nil | |
| } | |
| } | |
| func checkEvent(t *testing.T, event *eventsv1.Event, reason, eventType string, annotations map[string]string, related bool) { | |
| t.Helper() | |
| if len(annotations) == 0 { | |
| if len(event.Annotations) != 0 { | |
| t.Fatalf("unexpected annotations: %#v", event.Annotations) | |
| } | |
| } else if !reflect.DeepEqual(event.Annotations, annotations) { | |
| t.Fatalf("annotations lost or changed: got %#v, want %#v", event.Annotations, annotations) | |
| } | |
| if event.Type != eventType || event.Reason != reason || event.Action != "ContractAction" || event.Note != "emitted value 17" { | |
| t.Fatalf("ordinary event fields changed: %#v", event) | |
| } | |
| if event.Namespace != "contract-ns" || event.Regarding.Kind != "Pod" || event.Regarding.APIVersion != "v1" || event.Regarding.Name != "subject" || event.Regarding.UID != "subject-uid" { | |
| t.Fatalf("regarding reference or namespace changed: %#v", event) | |
| } | |
| if event.ReportingController != "crossrepo.example/recorder" || !strings.HasPrefix(event.ReportingInstance, "crossrepo.example/recorder-") || event.EventTime.IsZero() { | |
| t.Fatalf("reporter or event timestamp missing: %#v", event) | |
| } | |
| if related { | |
| if event.Related == nil || event.Related.Name != "related" || event.Related.UID != "related-uid" || event.Related.Kind != "Pod" { | |
| t.Fatalf("related reference lost: %#v", event.Related) | |
| } | |
| } else if event.Related != nil { | |
| t.Fatalf("unexpected related reference: %#v", event.Related) | |
| } | |
| } | |
| func TestCrossRepoNativeAnnotatedProvider(t *testing.T) { | |
| for _, tc := range []struct { | |
| name string | |
| annotations map[string]string | |
| related bool | |
| }{ | |
| {"custom", map[string]string{"crossrepo.example/source": "contract", "details": "punctuation: ✓"}, true}, | |
| {"nil", nil, false}, | |
| {"empty", map[string]string{}, false}, | |
| } { | |
| t.Run(tc.name, func(t *testing.T) { | |
| provider, sink, _ := newProvider(t) | |
| // Call through the public provider surface and inspect the recorder it returns. | |
| recorder := provider.GetEventRecorder("crossrepo.example/recorder") | |
| annotated, ok := interface{}(recorder).(annotatedRecorder) | |
| if !ok { | |
| t.Fatal("returned recorder lacks callable AnnotatedEventf support") | |
| } | |
| var related runtime.Object | |
| if tc.related { | |
| related = pod("related", "related-uid") | |
| } | |
| reason := "Annotated" + tc.name | |
| annotated.AnnotatedEventf(pod("subject", "subject-uid"), related, tc.annotations, corev1.EventTypeNormal, reason, "ContractAction", "emitted %s %d", "value", 17) | |
| checkEvent(t, receive(t, sink), reason, corev1.EventTypeNormal, tc.annotations, tc.related) | |
| // The same annotated recorder must continue to accept ordinary Eventf. | |
| recorder.Eventf(pod("subject", "subject-uid"), nil, corev1.EventTypeWarning, "OrdinaryAfterAnnotated", "ContractAction", "emitted %s %d", "value", 17) | |
| checkEvent(t, receive(t, sink), "OrdinaryAfterAnnotated", corev1.EventTypeWarning, nil, false) | |
| }) | |
| } | |
| } | |
| func TestCrossRepoNativeProviderEventfP2P(t *testing.T) { | |
| provider, sink, _ := newProvider(t) | |
| recorder := provider.GetEventRecorder("crossrepo.example/recorder") | |
| recorder.Eventf(pod("subject", "subject-uid"), pod("related", "related-uid"), corev1.EventTypeNormal, "OrdinaryBaseline", "ContractAction", "emitted %s %d", "value", 17) | |
| checkEvent(t, receive(t, sink), "OrdinaryBaseline", corev1.EventTypeNormal, nil, true) | |
| } | |
| func TestCrossRepoNativeProviderLegacyP2P(t *testing.T) { | |
| provider, _, legacy := newProvider(t) | |
| recorder := provider.GetEventRecorderFor("crossrepo-legacy") | |
| recorder.Eventf(pod("subject", "subject-uid"), corev1.EventTypeNormal, "LegacyBaseline", "legacy %s %d", "value", 17) | |
| select { | |
| case event := <-legacy: | |
| if event.Reason != "LegacyBaseline" || event.Message != "legacy value 17" || event.Type != corev1.EventTypeNormal || event.InvolvedObject.Name != "subject" || event.InvolvedObject.UID != "subject-uid" || event.Source.Component != "crossrepo-legacy" || len(event.Annotations) != 0 { | |
| t.Fatalf("legacy Eventf payload changed: %#v", event) | |
| } | |
| case <-time.After(8 * time.Second): | |
| t.Fatal("legacy broadcaster emitted no serialized API request") | |
| } | |
| } | |