...

Source file src/k8s.io/cli-runtime/pkg/printers/jsonpath_test.go

Documentation: k8s.io/cli-runtime/pkg/printers

     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 printers
    18  
    19  import (
    20  	"bytes"
    21  	"testing"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  	"k8s.io/apimachinery/pkg/runtime"
    26  	"k8s.io/apimachinery/pkg/util/sets"
    27  )
    28  
    29  func TestPrinters(t *testing.T) {
    30  	om := func(name string) metav1.ObjectMeta { return metav1.ObjectMeta{Name: name} }
    31  
    32  	jsonpathPrinter, err := NewJSONPathPrinter("{.metadata.name}")
    33  	if err != nil {
    34  		t.Fatal(err)
    35  	}
    36  
    37  	objects := map[string]runtime.Object{
    38  		"pod":             &v1.Pod{ObjectMeta: om("pod")},
    39  		"emptyPodList":    &v1.PodList{},
    40  		"nonEmptyPodList": &v1.PodList{Items: []v1.Pod{{}}},
    41  		"endpoints": &v1.Endpoints{
    42  			Subsets: []v1.EndpointSubset{{
    43  				Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}, {IP: "localhost"}},
    44  				Ports:     []v1.EndpointPort{{Port: 8080}},
    45  			}}},
    46  	}
    47  
    48  	// Set of strings representing objects that should produce an error.
    49  	expectedErrors := sets.NewString("emptyPodList", "nonEmptyPodList", "endpoints")
    50  
    51  	for oName, obj := range objects {
    52  		b := &bytes.Buffer{}
    53  		if err := jsonpathPrinter.PrintObj(obj, b); err != nil {
    54  			if expectedErrors.Has(oName) {
    55  				// expected error
    56  				continue
    57  			}
    58  			t.Errorf("JSONPathPrinter error object '%v'; error: '%v'", oName, err)
    59  		}
    60  	}
    61  
    62  	// rerun tests with JSONOutput enabled
    63  	jsonpathPrinter.EnableJSONOutput(true)
    64  
    65  	for oName, obj := range objects {
    66  		b := &bytes.Buffer{}
    67  		if err := jsonpathPrinter.PrintObj(obj, b); err != nil {
    68  			if expectedErrors.Has(oName) {
    69  				// expected error
    70  				continue
    71  			}
    72  			t.Errorf("JSONPathPrinter jsonOutput error object '%v'; error: '%v'", oName, err)
    73  		}
    74  	}
    75  }
    76  

View as plain text