-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_test.go
2099 lines (2006 loc) · 59.8 KB
/
run_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package starlet_test
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"reflect"
"testing"
"time"
"github.com/1set/starlet"
"github.com/1set/starlight/convert"
"go.starlark.net/starlark"
)
func Test_DefaultMachine_Run_NoCode(t *testing.T) {
m := starlet.NewDefault()
// run with empty script
_, err := m.Run()
expectErr(t, err, `starlet: run: no script to execute`)
}
func Test_DefaultMachine_Run_NoSpecificFile(t *testing.T) {
m := starlet.NewDefault()
m.SetScript("", nil, os.DirFS("testdata"))
// run with no specific file name
_, err := m.Run()
expectErr(t, err, `starlet: run: no script name`)
}
func Test_DefaultMachine_Run_APlusB(t *testing.T) {
m := starlet.NewDefault()
code := `a = 1 + 2`
m.SetScript("", []byte(code), nil)
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["a"] != int64(3) {
t.Errorf("unexpected output: %v", out)
}
}
func Test_DefaultMachine_Run_HelloWorld(t *testing.T) {
m := starlet.NewDefault()
// set print function
printFunc, cmpFunc := getPrintCompareFunc(t)
m.SetPrintFunc(printFunc)
// set code
code := `print("Aloha, Honua!")`
m.SetScript("aloha.star", []byte(code), nil)
// run
_, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// compare
cmpFunc("Aloha, Honua!\n")
}
func Test_DefaultMachine_Run_File(t *testing.T) {
m := starlet.NewDefault()
// set print function
printFunc, cmpFunc := getPrintCompareFunc(t)
m.SetPrintFunc(printFunc)
// run
_, err := m.RunFile("aloha.star", os.DirFS("testdata"), nil)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// compare
cmpFunc("Aloha, Honua!\n")
}
func Test_DefaultMachine_Run_Script(t *testing.T) {
m := starlet.NewDefault()
// set print function
printFunc, cmpFunc := getPrintCompareFunc(t)
m.SetPrintFunc(printFunc)
// run
code := `
print(text)
`
_, err := m.RunScript([]byte(code), map[string]interface{}{"text": "Hello, World!"})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// compare
cmpFunc("Hello, World!\n")
}
func Test_DefaultMachine_Run_LocalFile(t *testing.T) {
m := starlet.NewDefault()
// set print function
printFunc, cmpFunc := getPrintCompareFunc(t)
m.SetPrintFunc(printFunc)
// set code
m.SetScript("aloha.star", nil, os.DirFS("testdata"))
// run
_, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// compare
cmpFunc("Aloha, Honua!\n")
}
func Test_DefaultMachine_Run_LocalFileNonExist(t *testing.T) {
m := starlet.NewDefault()
// set code
m.SetScript("notfound.star", nil, os.DirFS("testdata"))
// run
_, err := m.Run()
if isOnWindows {
expectErr(t, err, `starlet: run: open`, `The system cannot find the file specified.`)
} else {
expectErr(t, err, `starlet: run: open`, `: no such file or directory`)
}
}
func Test_DefaultMachine_Run_FSNonExist(t *testing.T) {
m := starlet.NewDefault()
// set code
m.SetScript("aloha.star", nil, os.DirFS("not-found-dir"))
// run
_, err := m.Run()
if isOnWindows {
expectErr(t, err, `starlet: run: open`, `The system cannot find the path specified.`)
} else {
expectErr(t, err, `starlet: run: open`, `: no such file or directory`)
}
}
func Test_DefaultMachine_Run_InvalidGlobals(t *testing.T) {
m := starlet.NewDefault()
// set invalid globals
m.SetGlobals(map[string]interface{}{
"a": make(chan int),
})
// set code
m.SetScript("test.star", []byte(`a = 1`), nil)
// run
_, err := m.Run()
expectErr(t, err, `starlight: convert globals: type chan int is not a supported starlark type`)
}
func Test_DefaultMachine_Run_InvalidExtras(t *testing.T) {
m := starlet.NewDefault()
_, err := m.RunScript([]byte(`a = 1`), map[string]interface{}{
"a": make(chan int),
})
expectErr(t, err, `starlight: convert extras: type chan int is not a supported starlark type`)
}
func Test_DefaultMachine_Run_InvalidExtras2(t *testing.T) {
m := starlet.NewDefault()
if _, err := m.RunScript([]byte(`aa = a << 1`), map[string]interface{}{
"a": 100,
}); err != nil {
t.Errorf("unexpected error: %v", err)
return
}
_, err := m.RunScript([]byte(`bb = 1`), map[string]interface{}{
"b": make(chan int),
})
expectErr(t, err, `starlight: convert extras: type chan int is not a supported starlark type`)
}
func Test_DefaultMachine_Run_LoadFunc(t *testing.T) {
m := starlet.NewDefault()
// set code
code := `load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]`
m.SetScript("test.star", []byte(code), os.DirFS("testdata"))
// run
{
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if out["val"] != int64(55) {
t.Errorf("unexpected output: %v", out)
}
}
// update code only
code = `load("fibonacci.star", "fibonacci"); val = fibonacci(20)[-1]`
m.SetScriptContent([]byte(code))
// run
{
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if out["val"] != int64(6765) {
t.Errorf("unexpected output: %v", out)
}
}
}
func Test_DefaultMachine_Run_LoadNonExist(t *testing.T) {
m := starlet.NewDefault()
// set code
code := `load("nonexist.star", "a")`
m.SetScript("test.star", []byte(code), os.DirFS("testdata"))
// run
_, err := m.Run()
// check result
if isOnWindows {
expectErr(t, err, `starlark: exec: cannot load nonexist.star: open`, `The system cannot find the file specified.`)
} else {
expectErr(t, err, `starlark: exec: cannot load nonexist.star: open`, `: no such file or directory`)
}
}
func Test_Machine_Run_Globals(t *testing.T) {
type dataMore struct {
More string `json:"one"`
Extra int `json:"two"`
}
sm := starlark.NewDict(1)
_ = sm.SetKey(starlark.String("bee"), starlark.MakeInt(2))
m := starlet.NewWithNames(map[string]interface{}{
"a": 2,
"c": sm,
"d": &dataMore{More: "more", Extra: 5},
}, nil, nil)
// set code
code := `
c = 100
b = a * 10 + c
e = d.one + str(d.two)
`
m.SetCustomTag("json")
m.SetScript("test.star", []byte(code), nil)
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["b"].(int64) != int64(120) {
t.Errorf("unexpected output b: %v", out)
} else if out["e"].(string) != "more5" {
t.Errorf("unexpected output e: %v", out)
}
}
func Test_Machine_Run_Override(t *testing.T) {
getValLoadList := func(x int64) starlet.ModuleLoaderList {
return starlet.ModuleLoaderList{
starlet.MakeModuleLoaderFromMap(map[string]interface{}{
"x": x,
}),
}
}
getValLoadMap := func(x int64) starlet.ModuleLoaderMap {
return starlet.ModuleLoaderMap{
"number": starlet.MakeModuleLoaderFromMap(map[string]interface{}{
"x": x,
}),
}
}
testCases := []struct {
name string
setFunc func(m *starlet.Machine)
extras starlet.StringAnyMap
code string
expectVal int64
}{
{
name: "Runtime",
code: `val = 100`,
expectVal: 100,
},
{
name: "Globals",
setFunc: func(m *starlet.Machine) {
m.SetGlobals(map[string]interface{}{
"x": 200,
})
},
code: `val = x`,
expectVal: 200,
},
{
name: "Preload",
setFunc: func(m *starlet.Machine) {
m.SetPreloadModules(getValLoadList(300))
},
code: `val = x`,
expectVal: 300,
},
{
name: "Extras",
extras: starlet.StringAnyMap{
"x": 400,
},
code: `val = x`,
expectVal: 400,
},
{
name: "LazyLoad",
setFunc: func(m *starlet.Machine) {
m.SetLazyloadModules(getValLoadMap(500))
},
code: `load("number", "x"); val = x`,
expectVal: 500,
},
{
name: "Globals and Preload",
setFunc: func(m *starlet.Machine) {
m.SetGlobals(map[string]interface{}{
"x": 200,
})
m.SetPreloadModules(getValLoadList(300))
},
code: `val = x`,
expectVal: 300,
},
{
name: "Globals and Preload and Extras",
setFunc: func(m *starlet.Machine) {
m.SetGlobals(map[string]interface{}{
"x": 200,
})
m.SetPreloadModules(getValLoadList(300))
},
extras: map[string]interface{}{"x": 400},
code: `val = x`,
expectVal: 400,
},
{
name: "Globals and Preload and Extras and LazyLoad",
setFunc: func(m *starlet.Machine) {
m.SetGlobals(map[string]interface{}{
"x": 200,
})
m.SetPreloadModules(getValLoadList(300))
m.SetLazyloadModules(getValLoadMap(500))
},
extras: map[string]interface{}{"x": 400},
code: `load("number", "x"); val = x`,
expectVal: 500,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// prepare machine
m := starlet.NewDefault()
m.SetPrintFunc(getLogPrintFunc(t))
if tc.setFunc != nil {
tc.setFunc(m)
}
// run script
out, err := m.RunScript([]byte(tc.code), tc.extras)
// check result
if err != nil {
t.Errorf("unexpected error for %s: %v", tc.name, err)
return
}
if out == nil {
t.Errorf("unexpected nil output for %s", tc.name)
} else if out["val"].(int64) != tc.expectVal {
t.Errorf("unexpected output for %s: %v, want: %d", tc.name, out, tc.expectVal)
}
})
}
}
func Test_Machine_Run_Exit_Quit(t *testing.T) {
m := starlet.NewDefault()
m.SetPreloadModules(starlet.ModuleLoaderList{starlet.GetBuiltinModule("go_idiomatic")})
// test exit()
m.SetScript("test.star", []byte(`
a = 1
exit()
b = 2
`), nil)
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["a"].(int64) != int64(1) {
t.Errorf("unexpected output: %v", out)
} else if _, ok := out["b"]; ok {
t.Errorf("unexpected output: %v", out)
}
// test quit()
m.SetScript("test.star", []byte(`
c = 3
quit()
d = 4
`), nil)
out, err = m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["c"].(int64) != int64(3) {
t.Errorf("unexpected output: %v", out)
} else if _, ok := out["d"]; ok {
t.Errorf("unexpected output: %v", out)
}
// test exit(1)
m.SetScript("test.star", []byte(`
e = 5
exit(1)
f = 6
`), nil)
out, err = m.Run()
expectErr(t, err, `starlet: run: exit code: 1`)
if out == nil {
t.Errorf("unexpected nil output")
} else if out["e"].(int64) != int64(5) {
t.Errorf("unexpected output: %v", out)
} else if _, ok := out["f"]; ok {
t.Errorf("unexpected output: %v", out)
}
// test quit(2)
m.SetScript("test.star", []byte(`
g = 7
quit(2)
h = 8
`), nil)
out, err = m.Run()
expectErr(t, err, `starlet: run: exit code: 2`)
if out == nil {
t.Errorf("unexpected nil output")
} else if out["g"].(int64) != int64(7) {
t.Errorf("unexpected output: %v", out)
} else if _, ok := out["h"]; ok {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_Custom_Error(t *testing.T) {
customErr := fmt.Errorf("custom error")
errFunc := func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return nil, customErr
}
m := starlet.NewDefault()
out, err := m.RunScript([]byte(`x = attempt()`), starlet.StringAnyMap{
"attempt": starlark.NewBuiltin("attempt", errFunc),
})
t.Logf("out error: {%v}", err)
if err == nil {
t.Errorf("unexpected nil error")
return
}
if !errors.Is(err, customErr) {
t.Errorf("unexpected error: %v", err)
return
}
if len(out) > 0 {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_File_Globals(t *testing.T) {
m := starlet.NewWithNames(map[string]interface{}{
"magic_number": 30,
}, nil, nil)
// set code
m.SetScript("magic.star", nil, os.DirFS("testdata"))
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if f, ok := out["custom"]; !ok {
t.Errorf("got no func, unexpected output: %v", out)
} else if fn, ok := f.(*starlark.Function); !ok {
t.Errorf("unexpected output: %v", out)
} else {
res, err := starlark.Call(&starlark.Thread{Name: "afterparty"}, fn, nil, nil)
if err != nil {
t.Errorf("unexpected call error: %v", err)
} else if r, ok := res.(starlark.String); !ok {
t.Errorf("unexpected call result: %v", res)
} else if r != "Custom[30]" {
t.Errorf("unexpected call string result: %q", res)
}
}
}
func Test_Machine_Run_Load_Use_Globals(t *testing.T) {
m := starlet.NewWithNames(map[string]interface{}{
"magic_number": 50,
}, nil, nil)
// set code
code := `load("magic.star", "custom"); val = custom()`
m.SetScript("dummy.star", []byte(code), os.DirFS("testdata"))
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if f, ok := out["val"]; !ok {
t.Errorf("got no value, unexpected output: %v", out)
} else if f != "Custom[50]" {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_File_Missing_Globals(t *testing.T) {
m := starlet.NewWithNames(map[string]interface{}{
"other_number": 30,
}, nil, nil)
// set code
m.SetScript("magic.star", nil, os.DirFS("testdata"))
// run
_, err := m.Run()
expectErr(t, err, `starlark: exec: magic.star:5:32: undefined: magic_number`)
}
func Test_Machine_Run_PreloadModules(t *testing.T) {
m := starlet.NewWithNames(nil, []string{"go_idiomatic"}, nil)
// set code
code := `a = nil == None`
m.SetScript("test.star", []byte(code), nil)
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["a"].(bool) != true {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_LazyloadModules(t *testing.T) {
m := starlet.NewWithNames(nil, nil, []string{"go_idiomatic", "json"})
// set code
code := `
load("go_idiomatic", "nil")
load("json", "encode")
a = nil == None
`
m.SetScript("test.star", []byte(code), nil)
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if out == nil {
t.Errorf("unexpected nil output")
} else if out["a"].(bool) != true {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_LazyLoad_Override_Globals(t *testing.T) {
// create machine
m := starlet.NewWithNames(map[string]interface{}{"fibonacci": 123}, nil, nil)
m.EnableGlobalReassign() // enable global reassign only for this test, if it's not enabled, it will fail for: local variable fibonacci referenced before assignment
// set code
code := `
x = fibonacci * 2
load("fibonacci.star", "fibonacci")
load("fibonacci.star", fib="fibonacci")
y = fibonacci(10)[-1]
z = fib(10)[-1]
`
m.SetScript("test.star", []byte(code), os.DirFS("testdata"))
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if out["x"] != int64(246) || out["y"] != int64(55) || out["z"] != int64(55) {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_Override_Globals(t *testing.T) {
// create machine
m := starlet.NewWithNames(map[string]interface{}{"num": 10}, nil, nil)
// set code
code := `
x = num * 2
load("fibonacci.star", "fibonacci")
load("fibonacci.star", fib="fibonacci")
y = fibonacci(num)[-1]
z = fib(num)[-1]
`
m.SetScript("test.star", []byte(code), os.DirFS("testdata"))
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if out["x"] != int64(20) || out["y"] != int64(55) || out["z"] != int64(55) {
t.Errorf("unexpected output: %v", out)
}
}
func Test_Machine_Run_PreLoad_Override_Globals(t *testing.T) {
// create machine
m := starlet.NewWithLoaders(map[string]interface{}{"num": 10}, starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("coins.star", os.DirFS("testdata"), nil)}, nil)
m.EnableGlobalReassign() // enable global reassign only for this test, if it's not enabled, it will fail for: local variable coins referenced before assignment
// set code
code := `
num = 100
x = num * 5 + coins['quarter']
coins = 50
`
m.SetScript("test.star", []byte(code), os.DirFS("testdata"))
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if len(out) != 3 {
t.Errorf("unexpected output: %v", out)
} else if out["x"] != int64(525) || out["num"] != int64(100) || out["coins"] != int64(50) {
t.Errorf("unexpected output: %v", out)
}
// disable global reassign to test that it fails
m.DisableGlobalReassign()
_, err = m.Run()
expectErr(t, err, `starlark: exec: global variable coins referenced before assignment`)
}
func Test_Machine_Run_LoadCycle(t *testing.T) {
m := starlet.NewDefault()
// set code1
m.SetScript("circle1.star", nil, os.DirFS("testdata"))
_, err := m.Run()
expectErr(t, err, `starlark: exec: cannot load circle2.star: cannot load circle1.star: cannot load circle2.star: cycle in load graph`)
// set code2
m.SetScript("circle2.star", nil, os.DirFS("testdata"))
_, err = m.Run()
expectErr(t, err, `starlark: exec: cannot load circle1.star: cannot load circle2.star: cycle in load graph`)
}
func Test_Machine_Run_Recursion(t *testing.T) {
// create machine
m := starlet.NewDefault()
m.EnableRecursionSupport() // enable recursion support only for this test, if it's not enabled, it will fail for: function fib called recursively
// set code
code := `
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
x = fib(10)
`
m.SetScript("test.star", []byte(code), nil)
// run
out, err := m.Run()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// check result
if out == nil {
t.Errorf("unexpected nil output")
} else if out["x"] != int64(55) {
t.Errorf("unexpected output: %v", out)
}
// disable to test recursion error
m.DisableRecursionSupport()
_, err = m.Run()
expectErr(t, err, `starlark: exec: function fib called recursively`)
}
func Test_Machine_Run_LoadErrors(t *testing.T) {
mm := starlark.NewDict(1)
_ = mm.SetKey(starlark.String("quarter"), starlark.MakeInt(100))
_ = mm.SetKey(starlark.String("dime"), starlark.MakeInt(10))
testFS := os.DirFS("testdata")
nonExistFS := os.DirFS("nonexist")
testCases := []struct {
name string
globals map[string]interface{}
preloadMods []string
lazyMods []string
code string
modFS fs.FS
expectedErr string
expectedPanic bool
}{
// for globals
{
name: "Unsupported Globals Type",
globals: map[string]interface{}{"a": make(chan int)},
code: `b = a`,
expectedErr: `starlight: convert globals: type chan int is not a supported starlark type`,
},
{
name: "Missed Globals Variable",
globals: map[string]interface{}{"a": 2},
code: `b = c * 10`,
expectedErr: `starlark: exec: test.star:1:5: undefined: c`,
},
{
name: "Wrong Type Globals Variable",
globals: map[string]interface{}{"a": 2},
code: `b = a + "10"`,
expectedErr: `starlark: exec: unknown binary op: int + string`,
},
{
name: "Fails to Override Globals Variable",
globals: map[string]interface{}{"coins": mm},
code: `
num = 100
x = num * 5 + coins['quarter']
coins = 50
`,
expectedErr: `starlark: exec: global variable coins referenced before assignment`,
},
// for preload modules
{
name: "Missed Preload Modules",
preloadMods: []string{},
code: `a = nil == None`,
expectedErr: `starlark: exec: test.star:1:5: undefined: nil`,
},
{
name: "NonExist Preload Modules",
preloadMods: []string{"nonexist"},
code: `a = nil == None`,
expectedErr: `starlet: make: module not found: nonexist`,
expectedPanic: true,
},
// for lazyload modules
{
name: "Missed load() for LazyLoad Modules",
lazyMods: []string{"go_idiomatic"},
code: `a = nil == None`,
expectedErr: `starlark: exec: test.star:1:5: undefined: nil`,
},
{
name: "NonExist LazyLoad Modules",
lazyMods: []string{"nonexist"},
code: `load("nonexist", "nil"); a = nil == None`,
expectedErr: `starlet: make: module not found: nonexist`,
expectedPanic: true,
},
{
name: "NonExist Function in LazyLoad Modules",
lazyMods: []string{"go_idiomatic"},
code: `load("go_idiomatic", "fake"); a = fake == None`,
expectedErr: `starlark: exec: load: name fake not found in module go_idiomatic`,
},
// for load fs --- user modules
{
name: "No FS for User Modules",
code: `load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fibonacci.star: no file system given`,
},
{
name: "Missed load() for User Modules",
code: `val = fibonacci(10)[-1]`,
modFS: testFS,
expectedErr: `starlark: exec: test.star:1:7: undefined: fibonacci`,
},
{
name: "Duplicate load() for User Modules",
code: `load("fibonacci.star", "fibonacci"); load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]`,
modFS: testFS,
expectedErr: `starlark: exec: test.star:1:62: cannot reassign top-level fibonacci`,
},
{
name: "NonExist User Modules",
code: `load("nonexist.star", "fibonacci"); val = fibonacci(10)[-1]`,
modFS: testFS,
expectedErr: `starlark: exec: cannot load nonexist.star: open`,
},
{
name: "NonExist File System",
code: `load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]`,
modFS: nonExistFS,
expectedErr: `starlark: exec: cannot load fibonacci.star: open`,
},
{
name: "NonExist Function in User Modules",
code: `load("fibonacci.star", "fake"); val = fake(10)[-1]`,
modFS: testFS,
expectedErr: `starlark: exec: load: name fake not found in module fibonacci.star`,
},
{
name: "Existing and NonExist Functions in User Modules",
code: `load("fibonacci.star", "fibonacci", "fake"); val = fibonacci(10)[-1]`,
modFS: testFS,
expectedErr: `starlark: exec: load: name fake not found in module fibonacci.star`,
},
// for globals + user modules
{
name: "User Modules Override Globals",
globals: map[string]interface{}{"fibonacci": 2},
code: `load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]; print(x, val)`,
modFS: testFS,
},
{
name: "User Modules Fail to Override Globals",
globals: map[string]interface{}{"fibonacci": 2},
code: `x = fibonacci * 10; load("fibonacci.star", "fibonacci"); val = fibonacci(10)[-1]; print(x, val)`,
modFS: testFS,
expectedErr: `starlark: exec: local variable fibonacci referenced before assignment`,
// NOTE: for this behavior: read the comments before `r.useToplevel(use)` in `func (r *resolver) use(id *syntax.Ident)` in file: [email protected]/resolve/resolve.go
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
err := r.(error)
if !tc.expectedPanic {
t.Errorf("Unexpected panic: %v", err)
} else {
expectErr(t, err, tc.expectedErr)
}
} else if tc.expectedPanic {
t.Errorf("Expected panic, but got none")
}
}()
m := starlet.NewWithNames(tc.globals, tc.preloadMods, tc.lazyMods)
m.SetPrintFunc(getLogPrintFunc(t))
m.SetScript("test.star", []byte(tc.code), tc.modFS)
_, err := m.Run()
expectErr(t, err, tc.expectedErr)
})
}
}
func Test_Machine_Run_FileLoaders(t *testing.T) {
// the following tests tests the combination of preload and lazyload modules loaded via file.
var (
testFS = os.DirFS("testdata")
nonExistFS = os.DirFS("nonexist")
)
testCases := []struct {
name string
globals map[string]interface{}
preList starlet.ModuleLoaderList
lazyMap starlet.ModuleLoaderMap
code string
modFS fs.FS
expectedErr string
cmpResult func(val interface{}) bool
}{
// for preload with fs
{
name: "No FS for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("fibonacci.star", nil, nil)},
code: `val = fibonacci(10)[-1]`,
expectedErr: "starlet: load: no file system given",
},
{
name: "NonExist file system for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("fibonacci.star", nonExistFS, nil)},
code: `val = fibonacci(10)[-1]`,
expectedErr: "starlet: load: open ",
},
{
name: "NonExist file for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("nonexist.star", testFS, nil)},
code: `val = fibonacci(10)[-1]`,
expectedErr: "starlet: load: open ",
},
{
name: "Single File for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("fibonacci.star", testFS, nil)},
code: `val = fibonacci(10)[-1]`,
cmpResult: func(val interface{}) bool {
return val.(int64) == int64(55)
},
},
{
name: "Duplicate Files for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("fibonacci.star", testFS, nil), starlet.MakeModuleLoaderFromFile("fibonacci.star", testFS, nil)},
code: `val = fibonacci(10)[-1]`,
cmpResult: func(val interface{}) bool {
return val.(int64) == int64(55)
},
},
{
name: "Multiple Files for Preload Modules",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("fibonacci.star", testFS, nil), starlet.MakeModuleLoaderFromFile("factorial.star", testFS, nil)},
code: `val = fibonacci(10)[-1] + factorial(10)`,
cmpResult: func(val interface{}) bool {
return val.(int64) == int64(3628855)
},
},
{
name: "Preload Modules Requires External Value",
globals: map[string]interface{}{"input": 10},
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("one.star", testFS, nil)},
code: `val = number`,
expectedErr: `starlet: load: one.star:1:10: undefined: input`,
},
{
name: "Preload Modules With External Value",
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("one.star", testFS, map[string]starlark.Value{"input": starlark.MakeInt(5)})},
code: `val = number`,
cmpResult: func(val interface{}) bool { return val.(int64) == int64(500) },
},
{
name: "Override Global Variables",
globals: map[string]interface{}{"num": 10},
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("coins.star", testFS, nil)},
code: `
num = 100
val = num * 5 + coins['quarter']
`,
cmpResult: func(val interface{}) bool {
return val.(int64) == int64(525)
},
},
{
name: "Fails to Override Preload Modules",
globals: map[string]interface{}{"num": 10},
preList: starlet.ModuleLoaderList{starlet.MakeModuleLoaderFromFile("coins.star", testFS, nil)},
code: `
num = 100
x = num * 5 + coins['quarter']
coins = 50
`,
expectedErr: `starlark: exec: global variable coins referenced before assignment`,
},
// for lazyload with fs
{
name: "Missing Lazyload Modules",
lazyMap: starlet.ModuleLoaderMap{},
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: no file system given`,
},
{
name: "Missing Lazyload Modules with Invalid FS",
lazyMap: starlet.ModuleLoaderMap{},
modFS: nonExistFS,
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: open `,
},
{
name: "Missing Lazyload Modules with Valid FS",
lazyMap: starlet.ModuleLoaderMap{},
modFS: testFS,
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: open `,
},
{
name: "No FS for Lazyload Modules",
lazyMap: starlet.ModuleLoaderMap{"fib": starlet.MakeModuleLoaderFromFile("fibonacci.star", nil, nil)},
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: no file system given`,
},
{
name: "NonExist file system for Lazyload Modules",
lazyMap: starlet.ModuleLoaderMap{"fib": starlet.MakeModuleLoaderFromFile("fibonacci.star", nonExistFS, nil)},
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: open `,
},
{
name: "NonExist file for Lazyload Modules",
lazyMap: starlet.ModuleLoaderMap{"fib": starlet.MakeModuleLoaderFromFile("nonexist.star", testFS, nil)},
code: `load("fib", "fibonacci"); val = fibonacci(10)[-1]`,
expectedErr: `starlark: exec: cannot load fib: open `,
},
{