sigs.k8s.io/cluster-api@v1.7.1/internal/controllers/machine/machine_helpers_test.go (about)

     1  /*
     2  Copyright 2019 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 machine
    18  
    19  import (
    20  	"testing"
    21  
    22  	. "github.com/onsi/gomega"
    23  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    24  )
    25  
    26  func TestHasMatchingLabels(t *testing.T) {
    27  	testCases := []struct {
    28  		name     string
    29  		selector metav1.LabelSelector
    30  		labels   map[string]string
    31  		expected bool
    32  	}{
    33  		{
    34  			name: "selector matches labels",
    35  			selector: metav1.LabelSelector{
    36  				MatchLabels: map[string]string{
    37  					"foo": "bar",
    38  				},
    39  			},
    40  			labels: map[string]string{
    41  				"foo":  "bar",
    42  				"more": "labels",
    43  			},
    44  			expected: true,
    45  		},
    46  		{
    47  			name: "selector does not match labels",
    48  			selector: metav1.LabelSelector{
    49  				MatchLabels: map[string]string{
    50  					"foo": "bar",
    51  				},
    52  			},
    53  			labels: map[string]string{
    54  				"no": "match",
    55  			},
    56  			expected: false,
    57  		},
    58  		{
    59  			name:     "selector is empty",
    60  			selector: metav1.LabelSelector{},
    61  			labels:   map[string]string{},
    62  			expected: false,
    63  		},
    64  		{
    65  			name: "selector is invalid",
    66  			selector: metav1.LabelSelector{
    67  				MatchLabels: map[string]string{
    68  					"foo": "bar",
    69  				},
    70  				MatchExpressions: []metav1.LabelSelectorRequirement{
    71  					{
    72  						Operator: "bad-operator",
    73  					},
    74  				},
    75  			},
    76  			labels: map[string]string{
    77  				"foo": "bar",
    78  			},
    79  			expected: false,
    80  		},
    81  	}
    82  
    83  	for _, tc := range testCases {
    84  		t.Run(tc.name, func(t *testing.T) {
    85  			g := NewWithT(t)
    86  
    87  			got := HasMatchingLabels(tc.selector, tc.labels)
    88  			g.Expect(got).To(Equal(tc.expected))
    89  		})
    90  	}
    91  }