github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/logcli/output/jsonl_test.go (about)

     1  package output
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  
    11  	"github.com/grafana/loki/pkg/loghttp"
    12  )
    13  
    14  func TestJSONLOutput_Format(t *testing.T) {
    15  	t.Parallel()
    16  
    17  	timestamp, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
    18  	emptyLabels := loghttp.LabelSet{}
    19  	someLabels := loghttp.LabelSet(map[string]string{
    20  		"type": "test",
    21  	})
    22  
    23  	tests := map[string]struct {
    24  		options      *LogOutputOptions
    25  		timestamp    time.Time
    26  		lbls         loghttp.LabelSet
    27  		maxLabelsLen int
    28  		line         string
    29  		expected     string
    30  	}{
    31  		"empty line with no labels": {
    32  			&LogOutputOptions{Timezone: time.UTC, NoLabels: false},
    33  			timestamp,
    34  			emptyLabels,
    35  			0,
    36  			"",
    37  			`{"labels":{},"line":"","timestamp":"2006-01-02T08:04:05Z"}` + "\n",
    38  		},
    39  		"empty line with labels": {
    40  			&LogOutputOptions{Timezone: time.UTC, NoLabels: false},
    41  			timestamp,
    42  			someLabels,
    43  			len(someLabels.String()),
    44  			"",
    45  			`{"labels":{"type":"test"},"line":"","timestamp":"2006-01-02T08:04:05Z"}` + "\n",
    46  		},
    47  		"timezone option set to a Local one": {
    48  			&LogOutputOptions{Timezone: time.FixedZone("test", 2*60*60), NoLabels: false},
    49  			timestamp,
    50  			someLabels,
    51  			0,
    52  			"Hello",
    53  			`{"labels":{"type":"test"},"line":"Hello","timestamp":"2006-01-02T10:04:05+02:00"}` + "\n",
    54  		},
    55  		"labels output disabled": {
    56  			&LogOutputOptions{Timezone: time.UTC, NoLabels: true},
    57  			timestamp,
    58  			someLabels,
    59  			0,
    60  			"Hello",
    61  			`{"line":"Hello","timestamp":"2006-01-02T08:04:05Z"}` + "\n",
    62  		},
    63  	}
    64  
    65  	for testName, testData := range tests {
    66  		testData := testData
    67  
    68  		t.Run(testName, func(t *testing.T) {
    69  			t.Parallel()
    70  			writer := &bytes.Buffer{}
    71  			out := &JSONLOutput{writer, testData.options}
    72  			out.FormatAndPrintln(testData.timestamp, testData.lbls, testData.maxLabelsLen, testData.line)
    73  
    74  			actual := writer.String()
    75  			assert.Equal(t, testData.expected, actual)
    76  			assert.NoError(t, isValidJSON(actual))
    77  		})
    78  	}
    79  }
    80  
    81  func isValidJSON(s string) error {
    82  	var data map[string]interface{}
    83  
    84  	return json.Unmarshal([]byte(s), &data)
    85  }