github.com/oam-dev/kubevela@v1.9.11/pkg/utils/file_test.go (about) 1 /* 2 Copyright 2022 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 utils 18 19 import ( 20 "os" 21 "path/filepath" 22 "testing" 23 24 "github.com/stretchr/testify/assert" 25 ) 26 27 func TestIsEmptyDir(t *testing.T) { 28 // Test with an empty dir 29 err := os.Mkdir("testdir", 0750) 30 assert.NoError(t, err) 31 defer func() { 32 _ = os.RemoveAll("testdir") 33 }() 34 isEmptyDir, err := IsEmptyDir("testdir") 35 assert.Equal(t, isEmptyDir, true) 36 assert.NoError(t, err) 37 // Test with a file 38 err = os.WriteFile(filepath.Join("testdir", "testfile"), []byte("test"), 0644) 39 assert.NoError(t, err) 40 isEmptyDir, err = IsEmptyDir(filepath.Join("testdir", "testfile")) 41 assert.Equal(t, isEmptyDir, false) 42 assert.Equal(t, err != nil, true) 43 // Test with a non-empty dir 44 isEmptyDir, err = IsEmptyDir("testdir") 45 assert.Equal(t, isEmptyDir, false) 46 assert.NoError(t, err) 47 } 48 49 func TestGetFilenameFromLocalOrRemote(t *testing.T) { 50 cases := []struct { 51 path string 52 filename string 53 }{ 54 { 55 path: "./name", 56 filename: "name", 57 }, 58 { 59 path: "name", 60 filename: "name", 61 }, 62 { 63 path: "../name.js", 64 filename: "name", 65 }, 66 { 67 path: "../name.tar.zst", 68 filename: "name.tar", 69 }, 70 { 71 path: "https://some.com/file.js", 72 filename: "file", 73 }, 74 { 75 path: "https://some.com/file", 76 filename: "file", 77 }, 78 } 79 80 for _, c := range cases { 81 n, _ := GetFilenameFromLocalOrRemote(c.path) 82 assert.Equal(t, c.filename, n) 83 } 84 } 85 86 func TestIsJSONYAMLorCUEFile(t *testing.T) { 87 type args struct { 88 path string 89 } 90 tests := []struct { 91 name string 92 args args 93 want bool 94 }{ 95 { 96 name: "test is json file", 97 args: args{ 98 path: "test.json", 99 }, 100 want: true, 101 }, 102 { 103 name: "test is yaml file", 104 args: args{ 105 path: "test.yaml", 106 }, 107 want: true, 108 }, 109 { 110 name: "test is cue file", 111 args: args{ 112 path: "test.cue", 113 }, 114 want: true, 115 }, 116 { 117 name: "test is not json/yaml/cue file", 118 args: args{ 119 path: "test.txt", 120 }, 121 want: false, 122 }, 123 } 124 for _, tt := range tests { 125 t.Run(tt.name, func(t *testing.T) { 126 assert.Equal(t, tt.want, IsJSONYAMLorCUEFile(tt.args.path), "IsJSONYAMLorCUEFile(%v)", tt.args.path) 127 }) 128 } 129 }