...

Source file src/k8s.io/klog/v2/format_test.go

Documentation: k8s.io/klog/v2

     1  /*
     2  Copyright 2023 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 klog_test
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"strings"
    23  	"testing"
    24  
    25  	"k8s.io/klog/v2"
    26  
    27  	"github.com/go-logr/logr"
    28  )
    29  
    30  func TestFormat(t *testing.T) {
    31  	obj := config{
    32  		TypeMeta: TypeMeta{
    33  			Kind: "config",
    34  		},
    35  		RealField: 42,
    36  	}
    37  
    38  	assertEqual(t, "kind is config", obj.String(), "config.String()")
    39  	assertEqual(t, `{
    40    "Kind": "config",
    41    "RealField": 42
    42  }
    43  `, klog.Format(obj).(fmt.Stringer).String(), "Format(config).String()")
    44  	// fmt.Sprintf would call String if it was available.
    45  	str := fmt.Sprintf("%s", klog.Format(obj).(logr.Marshaler).MarshalLog())
    46  	if strings.Contains(str, "kind is config") {
    47  		t.Errorf("fmt.Sprintf called TypeMeta.String for klog.Format(obj).MarshalLog():\n%s", str)
    48  	}
    49  
    50  	structured, err := json.Marshal(klog.Format(obj).(logr.Marshaler).MarshalLog())
    51  	if err != nil {
    52  		t.Errorf("JSON Marshal: %v", err)
    53  	} else {
    54  		assertEqual(t, `{"Kind":"config","RealField":42}`, string(structured), "json.Marshal(klog.Format(obj).MarshalLog())")
    55  	}
    56  }
    57  
    58  func assertEqual(t *testing.T, expected, actual, what string) {
    59  	if expected != actual {
    60  		t.Errorf("%s:\nExpected\n%s\nActual\n%s\n", what, expected, actual)
    61  	}
    62  }
    63  
    64  type TypeMeta struct {
    65  	Kind string
    66  }
    67  
    68  func (t TypeMeta) String() string {
    69  	return "kind is " + t.Kind
    70  }
    71  
    72  func (t TypeMeta) MarshalLog() interface{} {
    73  	return t.Kind
    74  }
    75  
    76  type config struct {
    77  	TypeMeta
    78  
    79  	RealField int
    80  }
    81  

View as plain text