This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
mruby_test.go
664 lines (549 loc) · 13.3 KB
/
mruby_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
package mruby
import (
"fmt"
"reflect"
"testing"
)
func TestNewMrb(t *testing.T) {
mrb := NewMrb()
mrb.Close()
}
func TestMrbArena(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
idx := mrb.ArenaSave()
mrb.ArenaRestore(idx)
}
func TestMrbModule(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
module := mrb.Module("Kernel")
if module == nil {
t.Fatal("module was nil and should not be")
}
}
func TestMrbClass(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
class := mrb.Class("Object", nil)
if class == nil {
t.Fatal("class should not be nil")
}
mrb.DefineClass("Hello", mrb.ObjectClass())
class = mrb.Class("Hello", mrb.ObjectClass())
if class == nil {
t.Fatal("class should not be nil")
}
}
func TestMrbConstDefined(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
if !mrb.ConstDefined("Object", mrb.ObjectClass()) {
t.Fatal("Object should be defined")
}
mrb.DefineClass("Hello", mrb.ObjectClass())
if !mrb.ConstDefined("Hello", mrb.ObjectClass()) {
t.Fatal("Hello should be defined")
}
}
func TestMrbDefineClass(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
mrb.DefineClass("Hello", mrb.ObjectClass())
_, err := mrb.LoadString("Hello")
if err != nil {
t.Fatalf("err: %s", err)
}
mrb.DefineClass("World", nil)
_, err = mrb.LoadString("World")
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMrbDefineClass_methodException(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
cb := func(m *Mrb, self *MrbValue) (Value, Value) {
v, err := m.LoadString(`raise "exception"`)
if err != nil {
exc := err.(*Exception)
return nil, exc.MrbValue
}
return v, nil
}
class := mrb.DefineClass("Hello", mrb.ObjectClass())
class.DefineClassMethod("foo", cb, ArgsNone())
_, err := mrb.LoadString(`Hello.foo`)
if err == nil {
t.Fatal("should error")
}
}
func TestMrbDefineClassUnder(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
// Define an outer
hello := mrb.DefineClass("Hello", mrb.ObjectClass())
_, err := mrb.LoadString("Hello")
if err != nil {
t.Fatalf("err: %s", err)
}
// Inner
mrb.DefineClassUnder("World", nil, hello)
_, err = mrb.LoadString("Hello::World")
if err != nil {
t.Fatalf("err: %s", err)
}
// Inner defaults
mrb.DefineClassUnder("Another", nil, nil)
_, err = mrb.LoadString("Another")
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMrbDefineModule(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
mrb.DefineModule("Hello")
_, err := mrb.LoadString("Hello")
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMrbDefineModuleUnder(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
// Define an outer
hello := mrb.DefineModule("Hello")
_, err := mrb.LoadString("Hello")
if err != nil {
t.Fatalf("err: %s", err)
}
// Inner
mrb.DefineModuleUnder("World", hello)
_, err = mrb.LoadString("Hello::World")
if err != nil {
t.Fatalf("err: %s", err)
}
// Inner defaults
mrb.DefineModuleUnder("Another", nil)
_, err = mrb.LoadString("Another")
if err != nil {
t.Fatalf("err: %s", err)
}
}
func TestMrbFixnumValue(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
value := mrb.FixnumValue(42)
if value.Type() != TypeFixnum {
t.Fatalf("should be fixnum")
}
}
func TestMrbFullGC(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
ai := mrb.ArenaSave()
value := mrb.StringValue("foo")
if value.IsDead() {
t.Fatal("should not be dead")
}
mrb.ArenaRestore(ai)
mrb.FullGC()
if !value.IsDead() {
t.Fatal("should be dead")
}
}
type testcase struct {
args string
types []ValueType
result []string
}
func TestMrbGetArgs(t *testing.T) {
cases := []testcase{
{
`("foo")`,
[]ValueType{TypeString},
[]string{`"foo"`},
},
{
`(true)`,
[]ValueType{TypeTrue},
[]string{`true`},
},
{
`(Hello)`,
[]ValueType{TypeClass},
[]string{`Hello`},
},
{
`() { }`,
[]ValueType{TypeProc},
nil,
},
{
`(Hello, "bar", true)`,
[]ValueType{TypeClass, TypeString, TypeTrue},
[]string{`Hello`, `"bar"`, "true"},
},
{
`("bar", true) {}`,
[]ValueType{TypeString, TypeTrue, TypeProc},
nil,
},
}
// lots of this effort is centered around testing multithreaded behavior.
for i := 0; i < 1000; i++ {
errChan := make(chan error, len(cases))
for _, tc := range cases {
go func(tc testcase) {
var actual []*MrbValue
testFunc := func(m *Mrb, self *MrbValue) (Value, Value) {
actual = m.GetArgs()
return self, nil
}
mrb := NewMrb()
defer mrb.Close()
class := mrb.DefineClass("Hello", mrb.ObjectClass())
class.DefineClassMethod("test", testFunc, ArgsAny())
_, err := mrb.LoadString(fmt.Sprintf("Hello.test%s", tc.args))
if err != nil {
errChan <- fmt.Errorf("err: %s", err)
return
}
if tc.result != nil {
if len(actual) != len(tc.result) {
errChan <- fmt.Errorf("%s: expected %d, got %d",
tc.args, len(tc.result), len(actual))
return
}
}
actualStrings := make([]string, len(actual))
actualTypes := make([]ValueType, len(actual))
for i, v := range actual {
str, err := v.Call("inspect")
if err != nil {
errChan <- err
}
actualStrings[i] = str.String()
actualTypes[i] = v.Type()
}
if !reflect.DeepEqual(actualTypes, tc.types) {
errChan <- fmt.Errorf("code: %s\nexpected: %#v\nactual: %#v",
tc.args, tc.types, actualTypes)
return
}
if tc.result != nil {
if !reflect.DeepEqual(actualStrings, tc.result) {
errChan <- fmt.Errorf("expected: %#v\nactual: %#v",
tc.result, actualStrings)
return
}
}
errChan <- nil
}(tc)
}
for range cases {
if err := <-errChan; err != nil {
t.Fatal(err)
}
}
}
}
func TestMrbGlobalVariable(t *testing.T) {
const (
TestValue = "HELLO"
)
mrb := NewMrb()
defer mrb.Close()
if _, err := mrb.LoadString(fmt.Sprintf(`$a = "%s"`, TestValue)); err != nil {
t.Fatalf("err: %s", err)
}
value := mrb.GetGlobalVariable("$a")
if value.String() != TestValue {
t.Fatalf("wrong value for $a: expected '%s', found '%s'", TestValue, value.String())
}
mrb.SetGlobalVariable("$b", mrb.StringValue(TestValue))
value, err := mrb.LoadString(`$b`)
if err != nil {
t.Fatalf("err: %s", err)
}
if value.String() != TestValue {
t.Fatalf("wrong value for $b: expected '%s', found '%s'", TestValue, value.String())
}
}
func TestMrbInstanceVariable(t *testing.T) {
const (
GoldenRetriever = "golden retriever"
Husky = "Husky"
)
mrb := NewMrb()
defer mrb.Close()
_, err := mrb.LoadString(`
class Dog
def initialize(breed)
@breed = breed
end
def breed
"cocker spaniel" # this line exists to ensure that it's not invoking the accessor method
end
def real_breed
@breed
end
end
`)
if err != nil {
t.Fatalf("err: %s", err)
}
dogClass := mrb.Class("Dog", nil)
if dogClass == nil {
t.Fatalf("dog class not found")
}
inst, err := dogClass.New(mrb.StringValue(GoldenRetriever))
if err != nil {
t.Fatalf("err: %s", err)
}
value := inst.GetInstanceVariable("@breed")
if value.String() != GoldenRetriever {
t.Fatalf("wrong value for Dog.@breed. expected: '%s', found: '%s'", GoldenRetriever, value.String())
}
inst.SetInstanceVariable("@breed", mrb.StringValue(Husky))
value = inst.GetInstanceVariable("@breed")
if value.String() != Husky {
t.Fatalf("wrong value for Dog.@breed. expected: '%s', found: '%s'", Husky, value.String())
}
}
func TestMrbLoadString(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
value, err := mrb.LoadString(`"HELLO"`)
if err != nil {
t.Fatalf("err: %s", err)
}
if value == nil {
t.Fatalf("should have value")
}
}
func TestMrbLoadString_twice(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
value, err := mrb.LoadString(`"HELLO"`)
if err != nil {
t.Fatalf("err: %s", err)
}
if value == nil {
t.Fatalf("should have value")
}
value, err = mrb.LoadString(`"WORLD"`)
if err != nil {
t.Fatalf("err: %s", err)
}
if value.String() != "WORLD" {
t.Fatalf("bad: %s", value)
}
}
func TestMrbLoadStringException(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
_, err := mrb.LoadString(`raise "An exception"`)
if err == nil {
t.Fatal("exception expected")
}
value, err := mrb.LoadString(`"test"`)
if err != nil {
t.Fatal("exception should have been cleared")
}
if value.String() != "test" {
t.Fatal("bad test value returned")
}
}
func TestMrbRaise(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
cb := func(m *Mrb, self *MrbValue) (Value, Value) {
return nil, m.GetArgs()[0]
}
class := mrb.DefineClass("Hello", mrb.ObjectClass())
class.DefineClassMethod("foo", cb, ArgsReq(1))
_, err := mrb.LoadString(`Hello.foo(ArgumentError.new("ouch"))`)
if err == nil {
t.Fatal("should have error")
}
if err.Error() != "ouch" {
t.Fatalf("bad: %s", err)
}
}
func TestMrbYield(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
cb := func(m *Mrb, self *MrbValue) (Value, Value) {
result, err := m.Yield(m.GetArgs()[0], Int(12), Int(30))
if err != nil {
t.Fatalf("err: %s", err)
}
return result, nil
}
class := mrb.DefineClass("Hello", mrb.ObjectClass())
class.DefineClassMethod("foo", cb, ArgsBlock())
value, err := mrb.LoadString(`Hello.foo { |a, b| a + b }`)
if err != nil {
t.Fatalf("err: %s", err)
}
if value.Fixnum() != 42 {
t.Fatalf("bad: %s", value)
}
}
func TestMrbYieldException(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
cb := func(m *Mrb, self *MrbValue) (Value, Value) {
result, err := m.Yield(m.GetArgs()[0])
if err != nil {
exc := err.(*Exception)
return nil, exc.MrbValue
}
return result, nil
}
class := mrb.DefineClass("Hello", mrb.ObjectClass())
class.DefineClassMethod("foo", cb, ArgsBlock())
_, err := mrb.LoadString(`Hello.foo { raise "exception" }`)
if err == nil {
t.Fatal("should error")
}
_, err = mrb.LoadString(`Hello.foo { 1 }`)
if err != nil {
t.Fatal("exception should have been cleared")
}
}
func TestMrbRun(t *testing.T) {
mrb := NewMrb()
defer mrb.Close()
parser := NewParser(mrb)
defer parser.Close()
context := NewCompileContext(mrb)
defer context.Close()
parser.Parse(`
if $do_raise
raise "exception"
else
"rval"
end`,
context,
)
proc := parser.GenerateCode()
// Enable proc exception raising & verify
mrb.LoadString(`$do_raise = true`)
_, err := mrb.Run(proc, nil)
if err == nil {
t.Fatalf("expected exception, %#v", err)
}
// Disable proc exception raising
// If we still have an exception, it wasn't cleared from the previous invocation.
mrb.LoadString(`$do_raise = false`)
rval, err := mrb.Run(proc, nil)
if err != nil {
t.Fatalf("unexpected exception, %#v", err)
}
if rval.String() != "rval" {
t.Fatalf("expected return value 'rval', got %#v", rval)
}
parser.Parse(`a = 10`, context)
proc = parser.GenerateCode()
stackKeep, _, err := mrb.RunWithContext(proc, nil, 0)
if err != nil {
t.Fatal(err)
}
if stackKeep != 2 {
t.Fatalf("stack value was %d not 2; some variables may not have been captured", stackKeep)
}
parser.Parse(`a`, context)
proc = parser.GenerateCode()
var ret *MrbValue
_, ret, err = mrb.RunWithContext(proc, nil, stackKeep)
if err != nil {
t.Fatal(err)
}
if ret.String() != "10" {
t.Fatalf("Captured variable was not expected value: was %q", ret.String())
}
}
func TestMrbDefineMethodConcurrent(t *testing.T) {
concurrency := 100
numFuncs := 100
cb := func(m *Mrb, self *MrbValue) (Value, Value) {
return m.GetArgs()[0], nil
}
syncChan := make(chan struct{}, concurrency)
for i := 0; i < concurrency; i++ {
go func() {
mrb := NewMrb()
defer mrb.Close()
for i := 0; i < numFuncs; i++ {
mrb.TopSelf().SingletonClass().DefineMethod(fmt.Sprintf("test%d", i), cb, ArgsAny())
}
syncChan <- struct{}{}
}()
}
for i := 0; i < concurrency; i++ {
<-syncChan
}
}
func TestMrbStackedException(t *testing.T) {
var testClass *Class
createException := func(m *Mrb, msg string) Value {
val, err := m.Class("Exception", nil).New(String(msg))
if err != nil {
panic(fmt.Sprintf("could not construct exception for return: %v", err))
}
return val
}
testFunc := func(m *Mrb, self *MrbValue) (Value, Value) {
args := m.GetArgs()
t, err := testClass.New()
if err != nil {
return nil, createException(m, err.Error())
}
argv := []Value{}
for _, arg := range args {
argv = append(argv, Value(arg))
}
v, err := t.Call("dotest!", argv...)
if err != nil {
return nil, createException(m, err.Error())
}
return v, nil
}
doTestFunc := func(m *Mrb, self *MrbValue) (Value, Value) {
err := createException(m, "Fail us!")
return nil, err
}
mrb := NewMrb()
testClass = mrb.DefineClass("TestClass", nil)
testClass.DefineMethod("dotest!", doTestFunc, ArgsReq(0)|ArgsOpt(3))
mrb.TopSelf().SingletonClass().DefineMethod("test", testFunc, ArgsReq(0)|ArgsOpt(3))
_, err := mrb.LoadString("test")
if err == nil {
t.Fatal("No exception when one was expected")
return
}
mrb.Close()
mrb = NewMrb()
evalFunc := func(m *Mrb, self *MrbValue) (Value, Value) {
arg := m.GetArgs()[0]
result, err := self.CallBlock("instance_eval", arg)
if err != nil {
return result, createException(m, err.Error())
}
return result, nil
}
mrb.TopSelf().SingletonClass().DefineMethod("myeval", evalFunc, ArgsBlock())
result, err := mrb.LoadString("myeval { raise 'foo' }")
if err == nil {
t.Fatal("did not error")
return
}
if result != nil {
t.Fatal("result was not cleared")
return
}
mrb.Close()
}