-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctor_test.go
1101 lines (1053 loc) · 28.8 KB
/
ctor_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 starbox_test
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"bitbucket.org/neiku/hlog"
"github.com/1set/starbox"
"github.com/1set/starlet"
"github.com/1set/starlet/dataconv"
"github.com/psanford/memfs"
"go.starlark.net/starlark"
)
var (
hereDoc = starbox.HereDocf
noopPrint = func(thread *starlark.Thread, msg string) {
return
}
)
// TestProbe is a playground for exploring the external packages.
func TestProbe(t *testing.T) {
x := starlet.GetAllBuiltinModuleNames()
xj, _ := json.Marshal(x)
t.Log(string(xj))
}
// TestNew tests the following:
// 1. Create a new Starbox instance.
// 2. Check the Stringer output.
// 3. Check the underlying starlet.Machine instance.
func TestNew(t *testing.T) {
b := starbox.New("test")
n := `🥡Box{name:test,run:0}`
if a := b.String(); a != n {
t.Errorf("expect %s, got %s", n, a)
}
m := b.GetMachine()
if m == nil {
t.Error("expect not nil, got nil")
}
}
// TestSetStructTag tests the following:
// 1. Create a new Starbox instance.
// 2. Set the struct tag.
// 3. Run a script that uses the custom struct tag.
// 4. Check the output.
func TestSetStructTag(t *testing.T) {
type testStruct struct {
Nick1 string `json:"nick"`
Nick2 string `starlark:"nick"`
}
s := testStruct{
Nick1: "Kai",
Nick2: "Kalani",
}
tests := []struct {
tag string
expected string
}{
{"json", "Kai"},
{"starlark", "Kalani"},
{"", "Kalani"},
}
for i, tt := range tests {
t.Run(tt.tag, func(t *testing.T) {
b := starbox.New(fmt.Sprintf("test_%d", i))
if tt.tag != "" {
b.SetStructTag(tt.tag)
}
b.AddKeyValue("data", s)
out, err := b.Run(hereDoc(`
s = data.nick
print(data)
`))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
return
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
return
}
if es := tt.expected; out["s"] != es {
t.Errorf("expect %q, got %v", es, out["s"])
}
})
}
}
// TestSetPrintFunc tests the following:
// 1. Create a new Starbox instance.
// 2. Set the print function to output to a buffer.
// 3. Run a script that uses the print function.
// 4. Check the output.
func TestSetPrintFunc(t *testing.T) {
var sb strings.Builder
b := starbox.New("test")
b.SetPrintFunc(func(thread *starlark.Thread, msg string) {
sb.WriteString(msg)
})
out, err := b.Run(hereDoc(`
print('Aloha!')
print('Mahalo!')
`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 0 {
t.Errorf("expect 0, got %d", len(out))
}
actual := sb.String()
expected := "Aloha!Mahalo!"
if actual != expected {
t.Errorf("expect %q, got %v", expected, actual)
}
}
// TestSetFS tests the following:
// 1. Create a virtual filesystem.
// 2. Create a new Starbox instance.
// 3. Set the virtual filesystem, and add a module script.
// 4. Run a script that uses the virtual filesystem.
// 5. Check the output -- the virtual filesystem should override the module script.
// 6. Rerun the script with the same virtual filesystem.
// 7. Check the output -- the virtual filesystem should persist.
func TestSetFS(t *testing.T) {
// create a virtual filesystem
s1 := hereDoc(`
a = 10
b = 20
`)
s2 := hereDoc(`
a = 100
b = 200
`)
mn := `test.star`
fs := memfs.New()
fs.WriteFile(mn, []byte(s1), 0644)
// create a new Starbox instance
b := starbox.New("test")
b.SetFS(fs)
b.AddModuleScript(mn, s2)
// run a script that uses the virtual filesystem
out, err := b.Run(hereDoc(`
load("test.star", "a", "b")
c = a + b
print(__modules__)
m = len(__modules__)
`))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
return
}
if len(out) != 2 {
t.Errorf("expect 2, got %d", len(out))
return
}
if es := int64(30); out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
return
}
if es := int64(0); out["m"] != es {
t.Errorf("expect %d, got %v", es, out["m"])
return
}
// rerun the script with the same virtual filesystem
out, err = b.Run(hereDoc(`
load("test.star", "a", "b")
d = a * b
`))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
return
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
return
}
if es := int64(200); out["d"] != es {
t.Errorf("expect %d, got %v", es, out["d"])
return
}
}
// TestSetModuleSet tests the following:
// 1. Create a new Starbox instance.
// 2. Set the module set.
// 3. Run a script that uses the module set.
// 4. Check the output.
func TestSetModuleSet(t *testing.T) {
tests := []struct {
setName starbox.ModuleSetName
wantErr bool
hasMod []string
nonMod []string
}{
{
setName: starbox.ModuleSetName("unknown"),
wantErr: true,
},
{
// empty module set for default
nonMod: []string{"base64", "json", "go_idiomatic"},
},
{
setName: starbox.EmptyModuleSet,
nonMod: []string{"base64", "json", "go_idiomatic"},
},
{
setName: starbox.SafeModuleSet,
hasMod: []string{"base64", "json", "sleep", "exit"},
nonMod: []string{"http", "runtime", "go_idiomatic", "file", "path"},
},
{
setName: starbox.NetworkModuleSet,
hasMod: []string{"base64", "json", "sleep", "exit", "http"},
nonMod: []string{"runtime", "go_idiomatic", "file", "path"},
},
{
setName: starbox.FullModuleSet,
hasMod: []string{"sleep", "exit", "atom", "base64", "csv", "file", "hashlib", "http", "json", "log", "math", "path", "random", "re", "runtime", "string", "time"},
nonMod: []string{"go_idiomatic"},
},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
getBox := func() *starbox.Starbox {
name := fmt.Sprintf("test_%d", i)
b := starbox.New(name)
b.SetModuleSet(tt.setName)
b.SetPrintFunc(noopPrint)
return b
}
if tt.wantErr {
b := getBox()
_, err := b.Run(hereDoc(`a = 1`))
if err == nil {
t.Error("expect error, got nil")
}
return
}
// check for existing modules
for _, m := range tt.hasMod {
b := getBox()
res, err := b.Run(hereDoc(fmt.Sprintf(`print(type(%s)); m = __modules__`, m)))
if err != nil {
t.Errorf("expect nil for existing module %q, got %v", m, err)
return
}
t.Logf("{%s} modules: %v", tt.setName, res["m"])
}
// check for non-existing modules
for _, m := range tt.nonMod {
b := getBox()
_, err := b.Run(hereDoc(fmt.Sprintf(`print(type(%s))`, m)))
if err == nil {
t.Errorf("expect error for non-existing module %q, got nil", m)
return
}
}
})
}
}
// TestAddKeyValue tests the following:
// 1. Create a new Starbox instance.
// 2. Add a key-value pair.
// 3. Run a script that uses the key-value pair.
// 4. Check the output to see if the key-value pair is present.
func TestAddKeyValue(t *testing.T) {
b := starbox.New("test")
b.AddKeyValue("a", 10)
b.AddKeyValue("b", 20)
out, err := b.Run(hereDoc(`c = a + b`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := int64(30); out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
}
// TestAddKeyStarlarkValue tests the following:
// 1. Create a new Starbox instance.
// 2. Add a key-Starlark value pair.
// 3. Run a script that uses the key-Starlark value pair.
// 4. Check the output to see if the key-Starlark value pair is present.
func TestAddKeyStarlarkValue(t *testing.T) {
b := starbox.New("test")
b.AddKeyStarlarkValue("a", starlark.MakeInt(11))
b.AddKeyStarlarkValue("b", starlark.MakeInt(22))
out, err := b.Run(hereDoc(`c = a + b`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := int64(33); out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
}
// TestAddKeyValues tests the following:
// 1. Create a new Starbox instance.
// 2. Add key-value pairs.
// 3. Run a script that uses the key-value pairs.
// 4. Check the output to see if the key-value pairs are present.
func TestAddKeyValues(t *testing.T) {
b := starbox.New("test")
b.AddKeyValues(starlet.StringAnyMap{
"a": 10,
"b": 20,
})
b.AddKeyValues(starlet.StringAnyMap{
"c": 30,
})
out, err := b.Run(hereDoc(`d = a + b + c`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := int64(60); out["d"] != es {
t.Errorf("expect %d, got %v", es, out["d"])
}
}
// TestAddStarlarkValues tests the following:
// 1. Create a new Starbox instance.
// 2. Add key-value pairs.
// 3. Run a script that uses the key-value pairs.
// 4. Check the output to see if the key-value pairs are present.
func TestAddStarlarkValues(t *testing.T) {
b := starbox.New("test")
b.AddStarlarkValues(starlark.StringDict{
"a": starlark.MakeInt(11),
"b": starlark.MakeInt(22),
})
b.AddStarlarkValues(starlark.StringDict{
"c": starlark.Float(33),
})
out, err := b.Run(hereDoc(`d = a + b + c`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := float64(66); out["d"] != es {
t.Errorf("expect %f, got %v", es, out["d"])
}
}
// TestAddBuiltin tests the following:
// 1. Create a new Starbox instance.
// 2. Add a builtin function.
// 3. Run a script that uses the builtin function.
// 4. Check the output to see if the builtin function works.
func TestAddBuiltin(t *testing.T) {
b := starbox.New("test")
b.AddBuiltin("shift", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a << b).Add(starlark.MakeInt(3)), nil
})
out, err := b.Run(hereDoc(`
c = shift(a=10, b=4)
`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := int64(163); out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
}
// TestAddNamedModules tests the following:
// 1. Create a new Starbox instance.
// 2. Add named modules.
// 3. Run a script that uses function from the named modules.
// 4. Check the output to see if the named modules are present.
func TestAddNamedModules(t *testing.T) {
b := starbox.New("test")
b.AddNamedModules("runtime")
b.AddNamedModules("base64")
b.AddNamedModules("runtime")
out, err := b.Run(hereDoc(`
s = base64.encode('Aloha!')
t = type(runtime.pid)
m = __modules__
`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 3 {
t.Errorf("expect 3, got %d", len(out))
}
if es := `QWxvaGEh`; out["s"] != es {
t.Errorf("expect %q, got %v", es, out["s"])
}
if es := `int`; out["t"] != es {
t.Errorf("expect %q, got %v", es, out["t"])
}
if es := []interface{}{"base64", "runtime"}; !reflect.DeepEqual(out["m"].([]interface{}), es) {
t.Errorf("expect %v, got %v", es, out["m"])
}
}
// TestAddModuleLoader tests the following:
// 1. Create a new Starbox instance.
// 2. Add a module loader.
// 3. Run a script that uses function from the module loader.
// 4. Check the output to see if the module loader works.
func TestAddModuleLoader(t *testing.T) {
b := starbox.New("test")
b.AddModuleLoader("mine", func() (starlark.StringDict, error) {
return starlark.StringDict{
"shift": starlark.NewBuiltin("shift", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a << b).Add(starlark.MakeInt(5)), nil
}),
"num": starlark.MakeInt(100),
}, nil
})
b.AddModuleLoader("more", dataconv.WrapModuleData("less", starlark.StringDict{
"num": starlark.MakeInt(200),
"plus": starlark.NewBuiltin("plus", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a + b), nil
}),
}))
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 2},
{`c = shift(a=10, b=4) + num`, 265},
{`load("mine", "shift", "num"); c = shift(a=10, b=5) * num`, 32500},
{`c = less.plus(a=10, b=4) + less.num + num`, 314},
{`load("more", "less"); c = less.plus(a=10, b=5) * less.num`, 3000},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddModuleData tests the following:
// 1. Create a new Starbox instance.
// 2. Add module data.
// 3. Run a script that uses function from the module data.
// 4. Check the output to see if the module data works.
func TestAddModuleData(t *testing.T) {
b := starbox.New("test")
b.AddModuleData("data", starlark.StringDict{
"a": starlark.MakeInt(10),
"b": starlark.MakeInt(20),
"c": starlark.MakeInt(300),
})
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 1},
{`c = data.a + data.b`, 30},
{`load("data", "a", "b"); c = a * b`, 200},
{`load("data", "a", "b"); c = data.c * (a+b)`, 9000},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddModuleFunctions tests the following:
// 1. Create a new Starbox instance.
// 2. Add module functions.
// 3. Run a script that uses function from the module functions.
// 4. Check the output to see if the module functions work.
func TestAddModuleFunctions(t *testing.T) {
b := starbox.New("test")
b.AddModuleFunctions("data", starbox.FuncMap{
"shift": func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a << b).Add(starlark.MakeInt(7)), nil
},
})
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 1},
{`c = data.shift(a=10, b=4) + 100`, 267},
{`load("data", "shift"); c = shift(a=10, b=5) * 10`, 3270},
{`c = int(str(data.shift) == '<built-in function data.shift>')`, 1},
{`load("data", "shift"); c = int(str(shift) == '<built-in function data.shift>')`, 1},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddStructData tests the following:
// 1. Create a new Starbox instance.
// 2. Add struct data.
// 3. Run a script that uses function from the struct data.
// 4. Check the output to see if the struct data works.
func TestAddStructData(t *testing.T) {
type dataStruct struct {
A int64
B int64
C int64
}
b := starbox.New("test")
b.AddStructData("data", starlark.StringDict{
"A": starlark.MakeInt(10),
"B": starlark.MakeInt(20),
"C": starlark.MakeInt(300),
})
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 1},
{`c = data.A + data.B`, 30},
{`c = data.A * data.B`, 200},
{`c = data.C * (data.A + data.B)`, 9000},
{`load("data", 'A', 'B'); c = A * B`, 200},
{`load("data", 'A', 'B', 'C'); c = C * (A + B)`, 9000},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddStructFunctions tests the following:
// 1. Create a new Starbox instance.
// 2. Add struct functions.
// 3. Run a script that uses function from the struct functions.
// 4. Check the output to see if the struct functions work.
func TestAddStructFunctions(t *testing.T) {
b := starbox.New("test")
b.AddStructFunctions("data", starbox.FuncMap{
"shift": func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a << b).Add(starlark.MakeInt(7)), nil
},
})
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 1},
{`c = data.shift(a=10, b=4) + 100`, 267},
{`load("data", "shift"); c = shift(a=10, b=5) * 10`, 3270},
{`c = int(str(data.shift) == '<built-in function data.shift>')`, 1},
{`load("data", "shift"); c = int(str(shift) == '<built-in function data.shift>')`, 1},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddModuleScript tests the following:
// 1. Create a new Starbox instance.
// 2. Add module script.
// 3. Run a script that uses function from the module script.
// 4. Check the output to see if the module script works.
func TestAddModuleScript(t *testing.T) {
b := starbox.New("test")
b.AddModuleScript("data", hereDoc(`
a = 10
b = 20
c = 300
def shift(a, b):
return (a << b) + 10
`))
tests := []struct {
script string
want int64
}{
{`print(__modules__); c = len(__modules__)`, 1},
{`load("data.star", "a", "b"); c = a * b`, 200},
{`load("data", "shift"); c = shift(2, 10)`, 2058},
}
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
b.Reset()
out, err := b.Run(hereDoc(tt.script))
if err != nil {
t.Error(err)
return
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 1 {
t.Errorf("expect 1, got %d", len(out))
}
if es := tt.want; out["c"] != es {
t.Errorf("expect %d, got %v", es, out["c"])
}
})
}
}
// TestAddNamedModuleAndModuleScript tests the following:
// 1. Create a new Starbox instance.
// 2. Add named modules and module script.
// 3. Run a script that uses function from the named modules and module script.
// 4. Check the output to see if the named modules and module script conflict.
func TestAddNamedModuleAndModuleScript(t *testing.T) {
b := starbox.New("test")
b.AddNamedModules("base64")
b.AddNamedModules("csv")
b.AddNamedModules("runtime")
b.AddModuleScript("runtime", hereDoc(`
pid = "ABC"
`))
out, err := b.Run(hereDoc(`
v1 = runtime.pid # builtin
print("v1[b]", type(v1), v1)
load("runtime", p2="pid") # builtin
v2 = p2
print("v2[b]", type(v2), v2)
load("runtime.star", p3="pid") # script
v3 = p3
print("v3[s]", type(v3), v3)
s = " ".join([type(v1), type(v2), type(v3)])
m = __modules__
print(__modules__)
`))
if err != nil {
t.Error(err)
}
if out == nil {
t.Error("expect not nil, got nil")
}
if len(out) != 5 {
t.Errorf("expect 5, got %d", len(out))
}
if es := `int int string`; out["s"] != es {
t.Errorf("expect %q, got %v", es, out["s"])
}
if es := []interface{}{"base64", "csv", "runtime", "runtime.star"}; !reflect.DeepEqual(out["m"].([]interface{}), es) {
t.Errorf("expect %v, got %v", es, out["m"])
}
if em := []string{"base64", "csv", "runtime", "runtime.star"}; !reflect.DeepEqual(em, b.GetModuleNames()) {
t.Errorf("expect %v, got %v", em, b.GetModuleNames())
return
}
}
// TestSetScriptCache tests the following:
// 1. Create a new Starbox instance, and cache is enabled by default.
// 2. Local script from the filesystem.
// 3. Run a script that uses the local script.
// 4. Modify the local script.
// 5. Run the script again, check if the output is the same.
// 6. Disable the cache.
// 7. Run the script again, check if the output is different.
// 8. Enable the cache with custom provider.
// 9. Run the script again, check if the output is the same.
func TestSetScriptCache(t *testing.T) {
// scripts for virtual filesystem
s1 := hereDoc(`
a = 10
b = 20
c = a + b
`)
s2 := hereDoc(`
a = 100
b = 200
c = a + b
`)
mn := `test.star`
// run a script that uses the local script
testRun := func(b *starbox.Starbox, cas int, es int64) {
out, err := b.RunFile(mn)
if err != nil {
t.Errorf("[%d] fail to run: %v", cas, err)
return
}
if out["c"] != es {
t.Errorf("[%d] expect %d, got %v", cas, es, out["c"])
return
}
}
{
// create a new Starbox instance with the default cache
b := starbox.New("test")
fs := memfs.New()
b.SetFS(fs)
// run the script with the default cache
fs.WriteFile(mn, []byte(s1), 0644)
testRun(b, 1, 30)
// modify file content, and run the script again -- dirty cache
fs.WriteFile(mn, []byte(s2), 0644)
testRun(b, 2, 30)
}
{
// create a new Starbox instance and then disable cache
b := starbox.New("test")
fs := memfs.New()
b.SetFS(fs)
b.SetScriptCache(nil) // disable cache
// run the script without cache
fs.WriteFile(mn, []byte(s1), 0644)
testRun(b, 3, 30)
// modify file content, and run the script again -- no cache
fs.WriteFile(mn, []byte(s2), 0644)
testRun(b, 4, 300)
}
{
// create a new Starbox instance
b := starbox.New("test")
fs := memfs.New()
b.SetFS(fs)
b.SetScriptCache(starlet.NewMemoryCache()) // enable cache with custom provider
// run the script with the custom cache
fs.WriteFile(mn, []byte(s1), 0644)
testRun(b, 5, 30)
// modify file content, and run the script again -- cache
fs.WriteFile(mn, []byte(s2), 0644)
testRun(b, 6, 30)
}
}
// TestDynamicModuleLoader tests the following:
// 1. Create a new Starbox instance.
// 2. Add a module loader.
// 3. Set dynamic module loader.
// 4. Run a script that uses function from the module loader.
// 5. Check the output to see if the module loader works.
func TestDynamicModuleLoader(t *testing.T) {
buildBox := func(b *starbox.Starbox) {
b.AddModuleLoader("math", func() (starlark.StringDict, error) {
return starlark.StringDict{
"num": starlark.MakeInt(100),
"shift": starlark.NewBuiltin("shift", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a << b).Add(starlark.MakeInt(5)), nil
}),
}, nil
})
b.AddModuleLoader("more", dataconv.WrapModuleData("less", starlark.StringDict{
"num": starlark.MakeInt(200),
"plus": starlark.NewBuiltin("plus", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a + b + 1000), nil
}),
}))
b.SetDynamicModuleLoader(func(s string) (starlet.ModuleLoader, error) {
if s == "aloha" || s == "atom" {
return dataconv.WrapModuleData("minus", starlark.StringDict{
"num": starlark.MakeInt(500),
"minus": starlark.NewBuiltin("minus", func(thread *starlark.Thread, bt *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var a, b int64
if err := starlark.UnpackArgs(bt.Name(), args, kwargs, "a", &a, "b", &b); err != nil {
return nil, err
}
return starlark.MakeInt64(a + b - 2000), nil
}),
}), nil
} else if s == "mistake" {
return nil, errors.New("a mistake")
} else if s == "empty" {
return nil, nil
}
return nil, errors.New("kaumaha")
})
}
tests := []struct {
builder func(*starbox.Starbox)
script string
want int64
wantErr bool
}{
{
// 0. add named module from starlet
builder: func(b *starbox.Starbox) {
b.AddNamedModules("atom")
},
script: `print(__modules__); c = int("|".join(__modules__) == 'atom|math|more')`,
want: 1,
},
{
// 1.duplicate named module from dynamic, no affect -- check load starlet
builder: func(b *starbox.Starbox) {
b.AddNamedModules("atom")
},
script: `print(dir(atom)); c = int("|".join(dir(atom)) == 'new_float|new_int|new_string')`,
want: 1,
},
{
// 2. conflict named module from custom, override starlet -- check load starlet
builder: func(b *starbox.Starbox) {
b.AddNamedModules("math")
},
script: `print(dir(math)); c = int(len(dir(math)) > 2)`,
want: 1,
},
{
// 3. duplicate named module from starlet or custom, no affect
builder: func(b *starbox.Starbox) {
b.AddNamedModules("math", "more")
},
script: `print(__modules__); c = int("|".join(__modules__) == 'math|more')`,
want: 1,
},
{
// 4. duplicate named module from starlet or custom, no affect
builder: func(b *starbox.Starbox) {
b.AddNamedModules("more")
},
script: `c = less.num`,
want: 200,
},
{
// 5. add named module from dynamic
builder: func(b *starbox.Starbox) {
b.AddNamedModules("aloha")
},
script: `c = minus.num`,
want: 500,
},
{
// 6. add named module from dynamic, and also from starlet
builder: func(b *starbox.Starbox) {
b.AddNamedModules("aloha", "atom")
},
script: `print(__modules__); c = int("|".join(__modules__) == 'aloha|atom|math|more')`,
want: 1,