/ components / execd / pkg / util / pathutil / path_test.go
path_test.go
 1  // Copyright 2026 Alibaba Group Holding Ltd.
 2  //
 3  // Licensed under the Apache License, Version 2.0 (the "License");
 4  // you may not use this file except in compliance with the License.
 5  // You may obtain a copy of the License at
 6  //
 7  //     http://www.apache.org/licenses/LICENSE-2.0
 8  //
 9  // Unless required by applicable law or agreed to in writing, software
10  // distributed under the License is distributed on an "AS IS" BASIS,
11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  // See the License for the specific language governing permissions and
13  // limitations under the License.
14  
15  package pathutil
16  
17  import (
18  	"path/filepath"
19  	"testing"
20  
21  	"github.com/stretchr/testify/require"
22  )
23  
24  func TestExpandPath_HomeAndEnv(t *testing.T) {
25  	home := t.TempDir()
26  	t.Setenv("HOME", home)
27  	t.Setenv("USERPROFILE", home)
28  	t.Setenv("BASE_DIR", "project")
29  
30  	got, err := ExpandPath("~/docs/$BASE_DIR")
31  	require.NoError(t, err)
32  	require.Equal(t, filepath.Join(home, "docs", "project"), got)
33  }
34  
35  func TestExpandPath_Empty(t *testing.T) {
36  	got, err := ExpandPath("")
37  	require.NoError(t, err)
38  	require.Equal(t, "", got)
39  }
40  
41  func TestExpandPath_EnvVarInMiddle(t *testing.T) {
42  	t.Setenv("MID", "segment")
43  
44  	got, err := ExpandPath("prefix/$MID/suffix")
45  	require.NoError(t, err)
46  	require.Equal(t, filepath.Join("prefix", "segment", "suffix"), got)
47  }
48  
49  func TestExpandPathWithEnv_RequestOverrideHasHigherPriority(t *testing.T) {
50  	t.Setenv("WORKDIR", "from-process")
51  
52  	got, err := ExpandPathWithEnv("base/$WORKDIR", map[string]string{
53  		"WORKDIR": "from-request",
54  	})
55  	require.NoError(t, err)
56  	require.Equal(t, filepath.Join("base", "from-request"), got)
57  }
58  
59  func TestExpandPathWithEnv_CanResolveVarOnlyInOverride(t *testing.T) {
60  	got, err := ExpandPathWithEnv("$WORKDIR/tmp", map[string]string{
61  		"WORKDIR": "/tmp/ws",
62  	})
63  	require.NoError(t, err)
64  	require.Equal(t, filepath.Join("/tmp/ws", "tmp"), got)
65  }
66  
67  func TestExpandPath_UndefinedEnvVarInMiddleReturnsError(t *testing.T) {
68  	got, err := ExpandPath("prefix/$NOT_SET/suffix")
69  	require.Error(t, err)
70  	require.Contains(t, err.Error(), "NOT_SET")
71  	require.Equal(t, "", got)
72  }
73  
74  func TestExpandPath_UndefinedEnvVarReturnsError(t *testing.T) {
75  	got, err := ExpandPath("$NOT_SET/tmp")
76  	require.Error(t, err)
77  	require.Contains(t, err.Error(), "NOT_SET")
78  	require.Equal(t, "", got)
79  }
80  
81  func TestExpandPath_UndefinedEnvVarOnlyReturnsError(t *testing.T) {
82  	t.Setenv("HOME", t.TempDir())
83  	got, err := ExpandPath("$NOT_SET")
84  	require.Error(t, err)
85  	require.Contains(t, err.Error(), "NOT_SET")
86  	require.Equal(t, "", got)
87  }