trpc.group/trpc-go/trpc-go@v1.0.3/internal/expandenv/expand_env_test.go (about)

     1  package expandenv_test
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/require"
     9  	. "trpc.group/trpc-go/trpc-go/internal/expandenv"
    10  )
    11  
    12  func TestExpandEnv(t *testing.T) {
    13  	key := "env_key"
    14  	t.Run("no env", func(t *testing.T) {
    15  		require.Equal(t, []byte("abc"), ExpandEnv([]byte("abc")))
    16  	})
    17  	t.Run("${..} is expanded", func(t *testing.T) {
    18  		t.Setenv(key, t.Name())
    19  		require.Equal(t, fmt.Sprintf("head_%s_tail", t.Name()),
    20  			string(ExpandEnv([]byte(fmt.Sprintf("head_${%s}_tail", key)))))
    21  	})
    22  	t.Run("${ is not expanded", func(t *testing.T) {
    23  		require.Equal(t, "head_${_tail",
    24  			string(ExpandEnv([]byte(fmt.Sprintf("head_${_tail")))))
    25  	})
    26  	t.Run("${} is expanded as empty", func(t *testing.T) {
    27  		require.Equal(t, "head__tail",
    28  			string(ExpandEnv([]byte("head_${}_tail"))))
    29  	})
    30  	t.Run("${..} is not expanded if .. contains any space", func(t *testing.T) {
    31  		t.Setenv("key key", t.Name())
    32  		require.Equal(t, "head_${key key}_tail",
    33  			string(ExpandEnv([]byte("head_${key key}_tail"))))
    34  	})
    35  	t.Run("${..} is not expanded if .. contains any new line", func(t *testing.T) {
    36  		t.Setenv("key\nkey", t.Name())
    37  		require.Equal(t, t.Name(), os.Getenv("key\nkey"))
    38  		require.Equal(t, "head_${key\nkey}_tail",
    39  			string(ExpandEnv([]byte("head_${key\nkey}_tail"))))
    40  	})
    41  	t.Run(`${..} is not expanded if .. contains any "`, func(t *testing.T) {
    42  		t.Setenv(`key"key`, t.Name())
    43  		require.Equal(t, t.Name(), os.Getenv(`key"key`))
    44  		require.Equal(t, `head_${key"key}_tail`,
    45  			string(ExpandEnv([]byte(`head_${key"key}_tail`))))
    46  	})
    47  }