...

Source file src/github.com/cybertec-postgresql/pgwatch/v5/internal/sinks/json_test.go

Documentation: github.com/cybertec-postgresql/pgwatch/v5/internal/sinks

     1  package sinks_test
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"testing"
     7  
     8  	jsoniter "github.com/json-iterator/go"
     9  
    10  	"github.com/cybertec-postgresql/pgwatch/v5/internal/metrics"
    11  	"github.com/cybertec-postgresql/pgwatch/v5/internal/sinks"
    12  	"github.com/cybertec-postgresql/pgwatch/v5/internal/testutil"
    13  	"github.com/stretchr/testify/assert"
    14  	"github.com/stretchr/testify/require"
    15  )
    16  
    17  func TestJSONWriter_Write(t *testing.T) {
    18  	a := assert.New(t)
    19  	r := require.New(t)
    20  	// Define test data
    21  	msg := metrics.MeasurementEnvelope{
    22  		MetricName: "test_metric",
    23  		Data: metrics.Measurements{
    24  			{"number": 1, "string": "test_data"},
    25  		},
    26  		DBName:     "test_db",
    27  		CustomTags: map[string]string{"foo": "boo"},
    28  	}
    29  
    30  	tempFile := t.TempDir() + "/test.json"
    31  	ctx, cancel := context.WithCancel(testutil.TestContext)
    32  	jw, err := sinks.NewJSONWriter(ctx, tempFile)
    33  	r.NoError(err)
    34  
    35  	err = jw.Write(msg)
    36  	a.NoError(err, "write successful")
    37  	err = jw.Write(metrics.MeasurementEnvelope{})
    38  	r.NoError(err, "empty write successful")
    39  
    40  	cancel()
    41  	err = jw.Write(msg)
    42  	a.Error(err, "context canceled")
    43  
    44  	// Read the contents of the file
    45  	var data map[string]any
    46  	file, err := os.ReadFile(tempFile)
    47  	r.NoError(err)
    48  	err = jsoniter.ConfigFastest.Unmarshal(file, &data)
    49  	r.NoError(err)
    50  	a.Equal(msg.MetricName, data["metric"])
    51  	a.Equal(len(msg.Data), len(data["data"].([]any)))
    52  	a.Equal(msg.DBName, data["dbname"])
    53  	a.Equal(len(msg.CustomTags), len(data["custom_tags"].(map[string]any)))
    54  }
    55  
    56  func TestJSONWriter_SyncMetric(t *testing.T) {
    57  	// Create a temporary file for testing
    58  	tempFile := t.TempDir() + "/test.json"
    59  
    60  	ctx, cancel := context.WithCancel(testutil.TestContext)
    61  	jw, err := sinks.NewJSONWriter(ctx, tempFile)
    62  	assert.NoError(t, err)
    63  
    64  	// Call the function being tested
    65  	err = jw.SyncMetric("", "", sinks.InvalidOp)
    66  	assert.NoError(t, err)
    67  
    68  	cancel()
    69  	err = jw.SyncMetric("", "", sinks.InvalidOp)
    70  	assert.Error(t, err, "context canceled")
    71  
    72  }
    73