@@ -3,8 +3,11 @@ package native
3
3
import (
4
4
"encoding/json"
5
5
"fmt"
6
+ "os"
7
+ "path/filepath"
6
8
"testing"
7
9
10
+ jsonnet "github.com/google/go-jsonnet"
8
11
"github.com/stretchr/testify/assert"
9
12
)
10
13
@@ -21,6 +24,20 @@ func callNative(name string, data []interface{}) (res interface{}, err error, ca
21
24
return nil , nil , fmt .Errorf ("could not find native function %s" , name )
22
25
}
23
26
27
+ // callVMNative calls a native function used by jsonnet VM that requires access to the VM resource
28
+ func callVMNative (name string , data []interface {}) (res interface {}, err error , callerr error ) {
29
+ vm := jsonnet .MakeVM ()
30
+ for _ , fun := range VMFuncs (vm ) {
31
+ if fun .Name == name {
32
+ // Call the function
33
+ ret , err := fun .Func (data )
34
+ return ret , err , nil
35
+ }
36
+ }
37
+
38
+ return nil , nil , fmt .Errorf ("could not find VM native function %s" , name )
39
+ }
40
+
24
41
func TestSha256 (t * testing.T ) {
25
42
ret , err , callerr := callNative ("sha256" , []interface {}{"foo" })
26
43
@@ -208,3 +225,40 @@ func TestRegexSubstInvalid(t *testing.T) {
208
225
assert .Empty (t , ret )
209
226
assert .NotEmpty (t , err )
210
227
}
228
+
229
+ func TestImportFiles (t * testing.T ) {
230
+ tempDir , err := os .MkdirTemp ("" , "importFilesTest" )
231
+ assert .Nil (t , err )
232
+ defer os .RemoveAll (tempDir )
233
+ importDirName := "imports"
234
+ importDir := filepath .Join (tempDir , importDirName )
235
+ err = os .Mkdir (importDir , 0750 )
236
+ assert .Nil (t , err )
237
+ importFiles := []string {"test1.libsonnet" , "test2.libsonnet" }
238
+ skipFiles := []string {"skip1.libsonnet" , "skip2.libsonnet" }
239
+ for i , fName := range append (importFiles , skipFiles ... ) {
240
+ fPath := filepath .Join (importDir , fName )
241
+ content := fmt .Sprintf ("{ test: %d }" , i )
242
+ err = os .WriteFile (fPath , []byte (content ), 0644 )
243
+ assert .Nil (t , err )
244
+ }
245
+ opts := make (map [string ]interface {})
246
+ opts ["calledFrom" ] = filepath .Join (tempDir , "main.jsonnet" )
247
+ opts ["exclude" ] = skipFiles
248
+ ret , err , callerr := callVMNative ("importFiles" , []interface {}{importDirName , opts })
249
+ assert .Nil (t , err )
250
+ assert .Nil (t , callerr )
251
+ importMap , ok := ret .(map [string ]interface {})
252
+ assert .True (t , ok )
253
+ for i , fName := range importFiles {
254
+ content , ok := importMap [fName ]
255
+ assert .True (t , ok )
256
+ cMap , ok := content .(map [string ]interface {})
257
+ assert .True (t , ok )
258
+ assert .Equal (t , cMap ["test" ], float64 (i ))
259
+ }
260
+ for _ , fName := range skipFiles {
261
+ _ , ok = importMap [fName ]
262
+ assert .False (t , ok )
263
+ }
264
+ }
0 commit comments