...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/operator/pkg/logging/logging_test.go

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

     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 logging_test
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  	"testing"
    21  
    22  	"github.com/GoogleCloudPlatform/k8s-config-connector/operator/pkg/logging"
    23  	"github.com/google/go-cmp/cmp"
    24  )
    25  
    26  type ExampleError struct{}
    27  
    28  func (e *ExampleError) Error() string {
    29  	return "ExampleError"
    30  }
    31  
    32  // Tests that buildLogger (used by SetupLogger) sets up log entries to be in JSON and
    33  // with fields compatible with GCP Cloud Logging.
    34  func TestBuildLoggerFormat(t *testing.T) {
    35  	var buffer bytes.Buffer
    36  	logger := logging.BuildLogger(&buffer)
    37  	inputInfo := "testLoggingFormat"
    38  	logger.Info(inputInfo)
    39  	logger.Error(&ExampleError{}, "test")
    40  	wantList := [...]map[string]interface{}{
    41  		map[string]interface{}{
    42  			"msg":      inputInfo,
    43  			"severity": "info",
    44  		},
    45  		map[string]interface{}{
    46  			"error":    "ExampleError",
    47  			"msg":      "test",
    48  			"severity": "error",
    49  		},
    50  	}
    51  	for _, want := range wantList {
    52  		severity := want["severity"].(string)
    53  		t.Run(severity, func(t *testing.T) {
    54  			loggedLine, err := buffer.ReadString('\n')
    55  			if err != nil {
    56  				t.Fatalf("ReadString('\n') failed: %s", err)
    57  			}
    58  			var got map[string]interface{}
    59  			json.Unmarshal([]byte(loggedLine), &got)
    60  			if _, ok := got["timestamp"]; !ok {
    61  				t.Fatalf("the log message %v doesn't contain `timestamp`", got)
    62  			}
    63  			delete(got, "timestamp")
    64  			if diff := cmp.Diff(want, got); diff != "" {
    65  				t.Fatalf("logger %s returned unexpected diff (-want +got): \n%s", severity, diff)
    66  			}
    67  		})
    68  	}
    69  }
    70  

View as plain text