github.com/oam-dev/kubevela@v1.9.11/pkg/utils/system/system_test.go (about)

     1  /*
     2  Copyright 2021 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package system
    18  
    19  import (
    20  	"os"
    21  	"path/filepath"
    22  	"testing"
    23  
    24  	"github.com/stretchr/testify/assert"
    25  )
    26  
    27  func TestCreateIfNotExist(t *testing.T) {
    28  	testDir := "TestCreateIfNotExist"
    29  	defer os.RemoveAll(testDir)
    30  
    31  	normalCreate := filepath.Join(testDir, "normalCase")
    32  	_, err := CreateIfNotExist(normalCreate)
    33  	assert.NoError(t, err)
    34  	fi, err := os.Stat(normalCreate)
    35  	assert.NoError(t, err)
    36  	assert.Equal(t, true, fi.IsDir())
    37  
    38  	normalNestCreate := filepath.Join(testDir, "nested", "normalCase")
    39  	_, err = CreateIfNotExist(normalNestCreate)
    40  	assert.NoError(t, err)
    41  	fi, err = os.Stat(normalNestCreate)
    42  	assert.NoError(t, err)
    43  	assert.Equal(t, true, fi.IsDir())
    44  }
    45  
    46  func TestGetVelaHomeDir(t *testing.T) {
    47  	tests := []struct {
    48  		name    string
    49  		want    string
    50  		preFunc func()
    51  		postFun func()
    52  		wantErr assert.ErrorAssertionFunc
    53  	}{
    54  		{
    55  			name: "test get vela home dir from env",
    56  			preFunc: func() {
    57  				_ = os.Setenv(VelaHomeEnv, "/tmp")
    58  			},
    59  			want:    "/tmp",
    60  			wantErr: assert.NoError,
    61  		},
    62  		{
    63  			name: "test use default vela home dir",
    64  			preFunc: func() {
    65  				_ = os.Unsetenv(VelaHomeEnv)
    66  			},
    67  			want:    filepath.Join(os.Getenv("HOME"), defaultVelaHome),
    68  			wantErr: assert.NoError,
    69  			postFun: func() {
    70  				_ = os.RemoveAll(filepath.Join(os.Getenv("HOME"), defaultVelaHome))
    71  			},
    72  		},
    73  	}
    74  	for _, tt := range tests {
    75  		t.Run(tt.name, func(t *testing.T) {
    76  			if tt.preFunc != nil {
    77  				tt.preFunc()
    78  			}
    79  			defer func() {
    80  				_ = os.Unsetenv(VelaHomeEnv)
    81  			}()
    82  			got, err := GetVelaHomeDir()
    83  			if !tt.wantErr(t, err, "GetVelaHomeDir()") {
    84  				return
    85  			}
    86  
    87  			assert.Equalf(t, tt.want, got, "GetVelaHomeDir()")
    88  		})
    89  	}
    90  }