...

Source file src/k8s.io/kubernetes/test/utils/ktesting/klogcontext.go

Documentation: k8s.io/kubernetes/test/utils/ktesting

     1  /*
     2  Copyright 2024 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 ktesting
    18  
    19  import (
    20  	"fmt"
    21  	"strings"
    22  	"time"
    23  )
    24  
    25  var timeNow = time.Now // Can be stubbed out for testing.
    26  
    27  // withKlogHeader creates a TB where the same "I<date> <time>]" prefix
    28  // gets added to all log output, just as in the klog test logger.
    29  // This is used internally when constructing a TContext for unit testing.
    30  func withKlogHeader(tb TB) TB {
    31  	return klogTB{
    32  		TB: tb,
    33  	}
    34  }
    35  
    36  type klogTB struct {
    37  	TB
    38  }
    39  
    40  func (k klogTB) Log(args ...any) {
    41  	k.Helper()
    42  	k.TB.Log(header() + strings.TrimSpace(fmt.Sprintln(args...)))
    43  }
    44  
    45  func (k klogTB) Logf(format string, args ...any) {
    46  	k.Helper()
    47  	k.TB.Log(header() + strings.TrimSpace(fmt.Sprintf(format, args...)))
    48  }
    49  
    50  func (k klogTB) Error(args ...any) {
    51  	k.Helper()
    52  	k.TB.Error(header() + strings.TrimSpace(fmt.Sprintln(args...)))
    53  }
    54  
    55  func (k klogTB) Errorf(format string, args ...any) {
    56  	k.Helper()
    57  	k.TB.Error(header() + strings.TrimSpace(fmt.Sprintf(format, args...)))
    58  }
    59  
    60  func (k klogTB) Fatal(args ...any) {
    61  	k.Helper()
    62  	k.TB.Fatal(header() + strings.TrimSpace(fmt.Sprintln(args...)))
    63  }
    64  
    65  func (k klogTB) Fatalf(format string, args ...any) {
    66  	k.Helper()
    67  	k.TB.Fatal(header() + strings.TrimSpace(fmt.Sprintf(format, args...)))
    68  }
    69  
    70  func header() string {
    71  	now := timeNow()
    72  	_, month, day := now.Date()
    73  	hour, minute, second := now.Clock()
    74  	return fmt.Sprintf("I%02d%02d %02d:%02d:%02d.%06d] ",
    75  		month, day, hour, minute, second, now.Nanosecond()/1000)
    76  }
    77  

View as plain text