...

Source file src/k8s.io/cli-runtime/pkg/printers/json_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  	"reflect"
    22  	"testing"
    23  
    24  	"github.com/google/go-cmp/cmp"
    25  	v1 "k8s.io/api/core/v1"
    26  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    27  	"k8s.io/apimachinery/pkg/runtime"
    28  	"k8s.io/apimachinery/pkg/util/json"
    29  	"k8s.io/client-go/kubernetes/scheme"
    30  )
    31  
    32  var testData = TestStruct{
    33  	TypeMeta:   metav1.TypeMeta{APIVersion: "foo/bar", Kind: "TestStruct"},
    34  	Key:        "testValue",
    35  	Map:        map[string]int{"TestSubkey": 1},
    36  	StringList: []string{"a", "b", "c"},
    37  	IntList:    []int{1, 2, 3},
    38  }
    39  
    40  type TestStruct struct {
    41  	metav1.TypeMeta   `json:",inline"`
    42  	metav1.ObjectMeta `json:"metadata,omitempty"`
    43  	Key               string         `json:"Key"`
    44  	Map               map[string]int `json:"Map"`
    45  	StringList        []string       `json:"StringList"`
    46  	IntList           []int          `json:"IntList"`
    47  }
    48  
    49  func (in *TestStruct) DeepCopyObject() runtime.Object {
    50  	panic("never called")
    51  }
    52  
    53  func TestJSONPrinter(t *testing.T) {
    54  	testPrinter(t, NewTypeSetter(scheme.Scheme).ToPrinter(&JSONPrinter{}), json.Unmarshal)
    55  }
    56  
    57  func testPrinter(t *testing.T, printer ResourcePrinter, unmarshalFunc func(data []byte, v interface{}) error) {
    58  	buf := bytes.NewBuffer([]byte{})
    59  
    60  	err := printer.PrintObj(&testData, buf)
    61  	if err != nil {
    62  		t.Fatal(err)
    63  	}
    64  	var poutput TestStruct
    65  	// Verify that given function runs without error.
    66  	err = unmarshalFunc(buf.Bytes(), &poutput)
    67  	if err != nil {
    68  		t.Fatal(err)
    69  	}
    70  	// Use real decode function to undo the versioning process.
    71  	poutput = TestStruct{}
    72  	s := scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...)
    73  	if err := runtime.DecodeInto(s, buf.Bytes(), &poutput); err != nil {
    74  		t.Fatal(err)
    75  	}
    76  	if !reflect.DeepEqual(testData, poutput) {
    77  		t.Errorf("Test data and unmarshaled data are not equal: %v", cmp.Diff(poutput, testData))
    78  	}
    79  
    80  	obj := &v1.Pod{
    81  		TypeMeta:   metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"},
    82  		ObjectMeta: metav1.ObjectMeta{Name: "foo"},
    83  	}
    84  	// our decoder defaults, so we should default our expected object as well
    85  	scheme.Scheme.Default(obj)
    86  	buf.Reset()
    87  	printer.PrintObj(obj, buf)
    88  	var objOut v1.Pod
    89  	// Verify that given function runs without error.
    90  	err = unmarshalFunc(buf.Bytes(), &objOut)
    91  	if err != nil {
    92  		t.Fatalf("unexpected error: %#v", err)
    93  	}
    94  	// Use real decode function to undo the versioning process.
    95  	objOut = v1.Pod{}
    96  	if err := runtime.DecodeInto(s, buf.Bytes(), &objOut); err != nil {
    97  		t.Fatal(err)
    98  	}
    99  	if !reflect.DeepEqual(obj, &objOut) {
   100  		t.Errorf("Unexpected inequality:\n%v", cmp.Diff(obj, &objOut))
   101  	}
   102  }
   103  
   104  func TestPrintersSuccess(t *testing.T) {
   105  	om := func(name string) metav1.ObjectMeta { return metav1.ObjectMeta{Name: name} }
   106  
   107  	genericPrinters := map[string]ResourcePrinter{
   108  		"json": NewTypeSetter(scheme.Scheme).ToPrinter(&JSONPrinter{}),
   109  		"yaml": NewTypeSetter(scheme.Scheme).ToPrinter(&YAMLPrinter{}),
   110  	}
   111  	objects := map[string]runtime.Object{
   112  		"pod":             &v1.Pod{ObjectMeta: om("pod")},
   113  		"emptyPodList":    &v1.PodList{},
   114  		"nonEmptyPodList": &v1.PodList{Items: []v1.Pod{{}}},
   115  		"endpoints": &v1.Endpoints{
   116  			Subsets: []v1.EndpointSubset{{
   117  				Addresses: []v1.EndpointAddress{{IP: "127.0.0.1"}, {IP: "localhost"}},
   118  				Ports:     []v1.EndpointPort{{Port: 8080}},
   119  			}}},
   120  	}
   121  
   122  	// Test PrintObj() success.
   123  	for pName, p := range genericPrinters {
   124  		for oName, obj := range objects {
   125  			b := &bytes.Buffer{}
   126  			if err := p.PrintObj(obj, b); err != nil {
   127  				t.Errorf("printer '%v', object '%v'; error: '%v'", pName, oName, err)
   128  			}
   129  		}
   130  	}
   131  }
   132  

View as plain text