sigs.k8s.io/kueue@v0.6.2/pkg/util/testing/core.go (about)

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package testing
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	corev1 "k8s.io/api/core/v1"
    24  	eventsv1 "k8s.io/api/events/v1"
    25  	"k8s.io/apimachinery/pkg/api/resource"
    26  	"sigs.k8s.io/controller-runtime/pkg/client"
    27  )
    28  
    29  func PodSpecForRequest(request map[corev1.ResourceName]string) corev1.PodSpec {
    30  	return corev1.PodSpec{
    31  		Containers: SingleContainerForRequest(request),
    32  	}
    33  }
    34  
    35  func SingleContainerForRequest(request map[corev1.ResourceName]string) []corev1.Container {
    36  	rl := make(corev1.ResourceList, len(request))
    37  	for name, val := range request {
    38  		rl[name] = resource.MustParse(val)
    39  	}
    40  	return []corev1.Container{
    41  		{
    42  			Resources: corev1.ResourceRequirements{
    43  				Requests: rl,
    44  			},
    45  		},
    46  	}
    47  }
    48  
    49  // CheckLatestEvent will return true if the latest event is as you want.
    50  func CheckLatestEvent(ctx context.Context, k8sClient client.Client,
    51  	eventReason string,
    52  	eventType string, eventNote string) (bool, error) {
    53  	events := &eventsv1.EventList{}
    54  	if err := k8sClient.List(ctx, events, &client.ListOptions{}); err != nil {
    55  		return false, err
    56  	}
    57  
    58  	length := len(events.Items)
    59  	if length == 0 {
    60  		return false, fmt.Errorf("no events currently exist")
    61  	}
    62  
    63  	item := events.Items[length-1]
    64  	if item.Reason == eventReason && item.Type == eventType && item.Note == eventNote {
    65  		return true, nil
    66  	}
    67  
    68  	return false, fmt.Errorf("mismatch with the latest event: got r:%v t:%v n:%v, reg %v", item.Reason, item.Type, item.Note, item.Regarding)
    69  }