From d2c7c1f2b0c95c0c4ccfd5d0624a3d8ccf3960e5 Mon Sep 17 00:00:00 2001 From: Daniel Jaglowski Date: Tue, 13 Jun 2023 09:45:00 -0600 Subject: [PATCH] [chore][fileconsumer] Add test to validate reader encoding (#23280) --- pkg/stanza/fileconsumer/reader_test.go | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/pkg/stanza/fileconsumer/reader_test.go b/pkg/stanza/fileconsumer/reader_test.go index d33165aa3cd8..2fd341d0c2bd 100644 --- a/pkg/stanza/fileconsumer/reader_test.go +++ b/pkg/stanza/fileconsumer/reader_test.go @@ -4,7 +4,9 @@ package fileconsumer import ( + "bytes" "context" + "encoding/json" "testing" "time" @@ -239,3 +241,54 @@ func TestMapCopy(t *testing.T) { assert.Equal(t, 1, initMap["intVal"]) assert.Equal(t, "OrigStr", initMap["strVal"]) } + +func TestEncodingDecode(t *testing.T) { + testFile := openTemp(t, t.TempDir()) + testToken := tokenWithLength(2 * DefaultFingerprintSize) + _, err := testFile.Write(testToken) + require.NoError(t, err) + fp, err := NewFingerprint(testFile, DefaultFingerprintSize) + require.NoError(t, err) + + f := readerFactory{ + SugaredLogger: testutil.Logger(t), + readerConfig: &readerConfig{ + fingerprintSize: DefaultFingerprintSize, + maxLogSize: defaultMaxLogSize, + }, + splitterFactory: newMultilineSplitterFactory(helper.NewSplitterConfig()), + fromBeginning: false, + } + r, err := f.newReader(testFile, fp) + require.NoError(t, err) + + // Just faking out these properties + r.HeaderFinalized = true + r.FileAttributes.HeaderAttributes = map[string]any{"foo": "bar"} + + assert.Equal(t, testToken[:DefaultFingerprintSize], r.Fingerprint.FirstBytes) + assert.Equal(t, int64(2*DefaultFingerprintSize), r.Offset) + + // Encode + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + require.NoError(t, enc.Encode(r)) + + // Decode + dec := json.NewDecoder(bytes.NewReader(buf.Bytes())) + decodedReader, err := f.unsafeReader() + require.NoError(t, err) + require.NoError(t, dec.Decode(decodedReader)) + + // Assert decoded reader has values persisted + assert.Equal(t, testToken[:DefaultFingerprintSize], decodedReader.Fingerprint.FirstBytes) + assert.Equal(t, int64(2*DefaultFingerprintSize), decodedReader.Offset) + assert.True(t, decodedReader.HeaderFinalized) + assert.Equal(t, map[string]any{"foo": "bar"}, decodedReader.FileAttributes.HeaderAttributes) + + // These fields are intentionally excluded, as they may have changed + assert.Empty(t, decodedReader.FileAttributes.Name) + assert.Empty(t, decodedReader.FileAttributes.Path) + assert.Empty(t, decodedReader.FileAttributes.NameResolved) + assert.Empty(t, decodedReader.FileAttributes.PathResolved) +}