github.com/thanos-io/thanos@v0.32.5/pkg/receive/config_test.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package receive
     5  
     6  import (
     7  	"encoding/json"
     8  	"os"
     9  	"testing"
    10  
    11  	"github.com/pkg/errors"
    12  
    13  	"github.com/efficientgo/core/testutil"
    14  )
    15  
    16  func TestValidateConfig(t *testing.T) {
    17  	for _, tc := range []struct {
    18  		name string
    19  		cfg  interface{}
    20  		err  error
    21  	}{
    22  		{
    23  			name: "<nil> config",
    24  			cfg:  nil,
    25  			err:  errEmptyConfigurationFile,
    26  		},
    27  		{
    28  			name: "empty config",
    29  			cfg:  []HashringConfig{},
    30  			err:  errEmptyConfigurationFile,
    31  		},
    32  		{
    33  			name: "unparsable config",
    34  			cfg:  struct{}{},
    35  			err:  errParseConfigurationFile,
    36  		},
    37  		{
    38  			name: "valid config",
    39  			cfg: []HashringConfig{
    40  				{
    41  					Endpoints: []Endpoint{{Address: "node1"}},
    42  				},
    43  			},
    44  			err: nil, // means it's valid.
    45  		},
    46  	} {
    47  		t.Run(tc.name, func(t *testing.T) {
    48  			content, err := json.Marshal(tc.cfg)
    49  			testutil.Ok(t, err)
    50  
    51  			tmpfile, err := os.CreateTemp("", "configwatcher_test.*.json")
    52  			testutil.Ok(t, err)
    53  
    54  			defer func() {
    55  				testutil.Ok(t, os.Remove(tmpfile.Name()))
    56  			}()
    57  
    58  			_, err = tmpfile.Write(content)
    59  			testutil.Ok(t, err)
    60  
    61  			err = tmpfile.Close()
    62  			testutil.Ok(t, err)
    63  
    64  			cw, err := NewConfigWatcher(nil, nil, tmpfile.Name(), 1)
    65  			testutil.Ok(t, err)
    66  			defer cw.Stop()
    67  
    68  			if err := cw.ValidateConfig(); err != nil && !errors.Is(err, tc.err) {
    69  				t.Errorf("case %q: got unexpected error: %v", tc.name, err)
    70  			}
    71  		})
    72  	}
    73  }
    74  
    75  func TestUnmarshalEndpointSlice(t *testing.T) {
    76  	t.Run("Endpoints as string slice", func(t *testing.T) {
    77  		var endpoints []Endpoint
    78  		testutil.Ok(t, json.Unmarshal([]byte(`["node-1"]`), &endpoints))
    79  		testutil.Equals(t, endpoints, []Endpoint{{Address: "node-1"}})
    80  	})
    81  	t.Run("Endpoints as endpoints slice", func(t *testing.T) {
    82  		var endpoints []Endpoint
    83  		testutil.Ok(t, json.Unmarshal([]byte(`[{"address": "node-1", "az": "az-1"}]`), &endpoints))
    84  		testutil.Equals(t, endpoints, []Endpoint{{Address: "node-1", AZ: "az-1"}})
    85  	})
    86  }