...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/pkg/test/unstructured.go

Documentation: github.com/GoogleCloudPlatform/k8s-config-connector/pkg/test

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package test
    16  
    17  import (
    18  	"testing"
    19  
    20  	"github.com/ghodss/yaml"
    21  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    22  )
    23  
    24  // addTestLabels adds labels to indicate the resource
    25  // was created for testing purposes. These labels enable
    26  // tools like cleanup utilities.
    27  func addTestLabels(u *unstructured.Unstructured) {
    28  	labels := u.GetLabels()
    29  	if labels == nil {
    30  		labels = map[string]string{}
    31  	}
    32  	AddTestLabelsToMap(labels)
    33  	u.SetLabels(labels)
    34  }
    35  
    36  // AddTestLabelsToMap adds test labels to a
    37  // map directly.
    38  func AddTestLabelsToMap(m map[string]string) {
    39  	m["cnrm-test"] = "true"
    40  }
    41  
    42  func ToUnstruct(t *testing.T, bytes []byte) *unstructured.Unstructured {
    43  	u := &unstructured.Unstructured{}
    44  	err := yaml.Unmarshal(bytes, u)
    45  	if err != nil {
    46  		t.Fatalf("error unmarshalling bytes to unstruct: %v", err)
    47  	}
    48  	addTestLabels(u)
    49  	return u
    50  }
    51  
    52  func ToUnstructWithNamespace(t *testing.T, b []byte, namespace string) *unstructured.Unstructured {
    53  	u := ToUnstruct(t, b)
    54  	if u.GetNamespace() == "" {
    55  		u.SetNamespace(namespace)
    56  	}
    57  	return u
    58  }
    59  

View as plain text