github.com/annwntech/go-micro/v2@v2.9.5/config/reader/preprocessor_test.go (about)

     1  package reader
     2  
     3  import (
     4  	"os"
     5  	"strings"
     6  	"testing"
     7  )
     8  
     9  func TestReplaceEnvVars(t *testing.T) {
    10  	os.Setenv("myBar", "cat")
    11  	os.Setenv("MYBAR", "cat")
    12  	os.Setenv("my_Bar", "cat")
    13  	os.Setenv("myBar_", "cat")
    14  
    15  	testData := []struct {
    16  		expected string
    17  		data     []byte
    18  	}{
    19  		// Right use cases
    20  		{
    21  			`{"foo": "bar", "baz": {"bar": "cat"}}`,
    22  			[]byte(`{"foo": "bar", "baz": {"bar": "${myBar}"}}`),
    23  		},
    24  		{
    25  			`{"foo": "bar", "baz": {"bar": "cat"}}`,
    26  			[]byte(`{"foo": "bar", "baz": {"bar": "${MYBAR}"}}`),
    27  		},
    28  		{
    29  			`{"foo": "bar", "baz": {"bar": "cat"}}`,
    30  			[]byte(`{"foo": "bar", "baz": {"bar": "${my_Bar}"}}`),
    31  		},
    32  		{
    33  			`{"foo": "bar", "baz": {"bar": "cat"}}`,
    34  			[]byte(`{"foo": "bar", "baz": {"bar": "${myBar_}"}}`),
    35  		},
    36  		// Wrong use cases
    37  		{
    38  			`{"foo": "bar", "baz": {"bar": "${myBar-}"}}`,
    39  			[]byte(`{"foo": "bar", "baz": {"bar": "${myBar-}"}}`),
    40  		},
    41  		{
    42  			`{"foo": "bar", "baz": {"bar": "${}"}}`,
    43  			[]byte(`{"foo": "bar", "baz": {"bar": "${}"}}`),
    44  		},
    45  		{
    46  			`{"foo": "bar", "baz": {"bar": "$sss}"}}`,
    47  			[]byte(`{"foo": "bar", "baz": {"bar": "$sss}"}}`),
    48  		},
    49  		{
    50  			`{"foo": "bar", "baz": {"bar": "${sss"}}`,
    51  			[]byte(`{"foo": "bar", "baz": {"bar": "${sss"}}`),
    52  		},
    53  		{
    54  			`{"foo": "bar", "baz": {"bar": "{something}"}}`,
    55  			[]byte(`{"foo": "bar", "baz": {"bar": "{something}"}}`),
    56  		},
    57  		// Use cases without replace env vars
    58  		{
    59  			`{"foo": "bar", "baz": {"bar": "cat"}}`,
    60  			[]byte(`{"foo": "bar", "baz": {"bar": "cat"}}`),
    61  		},
    62  	}
    63  
    64  	for _, test := range testData {
    65  		res, err := ReplaceEnvVars(test.data)
    66  		if err != nil {
    67  			t.Fatal(err)
    68  		}
    69  		if strings.Compare(test.expected, string(res)) != 0 {
    70  			t.Fatalf("Expected %s got %s", test.expected, res)
    71  		}
    72  	}
    73  }