-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnative_test.go
577 lines (496 loc) · 15 KB
/
native_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
package gojs
import (
"log"
"syscall"
"testing"
"unsafe"
)
// t.Log doesn't print things immediately, this does if TESTING_DEBUG_LOG is set to true. Useful when you have pointer crashes and faults such as are common with cgo code.
const TESTING_DEBUG_LOG = false
func tlog(t *testing.T, v ...interface{}) {
if TESTING_DEBUG_LOG {
log.Println(v...)
} else {
t.Log(v...)
}
return
}
func terrf(t *testing.T, format string, v ...interface{}) {
if TESTING_DEBUG_LOG {
log.Printf(format, v...)
t.Fail()
} else {
t.Errorf(format, v...)
}
}
func init() {
log.SetFlags(log.Ltime | log.Lshortfile)
}
type reflect_object struct {
I int
U uint
F float64
S string
}
func (o *reflect_object) String() string {
return o.S
}
func (o *reflect_object) Add() float64 {
return float64(o.I) + o.F
}
func (o *reflect_object) AddWith(op float64) float64 {
return float64(o.I) + o.F + op
}
func (o *reflect_object) Self() *reflect_object {
return o
}
func (o *reflect_object) Null() *reflect_object {
return nil
}
func PrettyPrintValArr(t *testing.T, values []*Value) {
for _, val := range values {
tlog(t, val)
}
}
func ValArrToStrings(t *testing.T, values []*Value) {
for _, val := range values {
tlog(t, val.ToStringOrDie())
}
}
func checkExpected(t *testing.T, val *Value, str string) {
str2 := val.ToStringOrDie()
if str2 != str {
t.Fatalf("Got %s, expected %s", str2, str)
}
}
func checkArrsEqual(t *testing.T, vals []*Value, expectedVals []*Value) {
for i, _ := range vals {
valstr := vals[i].ToStringOrDie()
expvalstr := expectedVals[i].ToStringOrDie()
if valstr != expvalstr {
t.Fatalf("Got %s, expected %s", valstr, expvalstr)
}
}
}
func TestNewCValueArray(t *testing.T) {
ctx := NewContext()
defer ctx.Release()
valarr := make([]*Value, 5)
valstrs := make([]string, 5)
valarr[0] = ctx.NewValue(0)
valstrs[0] = "0"
valarr[1] = ctx.NewNumberValue(1.3)
valstrs[1] = "1.3"
valarr[2] = ctx.NewValue(nil)
valstrs[2] = "null"
valarr[3] = ctx.NewValue(2309240)
valstrs[3] = "2309240"
valarr[4] = ctx.NewValue(0x934)
valstrs[4] = "2356"
cptr, size := ctx.newCValueArray(valarr)
// Make sure the C array is correct
ptrs := unsafe.Sizeof(uintptr(0))
uptr := uintptr(unsafe.Pointer(cptr))
ptr0 := unsafe.Pointer(uptr + 0)
val0 := ctx.ptrValue(ptr0)
ptr1 := unsafe.Pointer(uptr + (ptrs * 1))
val1 := ctx.ptrValue(ptr1)
ptr2 := unsafe.Pointer(uptr + (ptrs * 2))
val2 := ctx.ptrValue(ptr2)
ptr3 := unsafe.Pointer(uptr + (ptrs * 3))
val3 := ctx.ptrValue(ptr3)
ptr4 := unsafe.Pointer(uptr + (ptrs * 4))
val4 := ctx.ptrValue(ptr4)
checkExpected(t, val0, valstrs[0])
checkExpected(t, val1, valstrs[1])
checkExpected(t, val2, valstrs[2])
checkExpected(t, val3, valstrs[3])
checkExpected(t, val4, valstrs[4])
origarray := ctx.newGoValueArray(unsafe.Pointer(cptr), uint(size))
checkArrsEqual(t, valarr, origarray)
}
func TestNewFunctionWithCallback(t *testing.T) {
var flag bool
callback := func(ctx *Context, obj *Object, thisObject *Object, _ []*Value) *Value {
tlog(t, "In callback function!")
flag = true
return nil
}
ctx := NewContext()
defer ctx.Release()
fn := ctx.NewFunctionWithCallback(callback)
if fn == nil {
t.Errorf("ctx.NewFunctionWithCallback failed")
return
}
tlog(t, "Made new function with callback")
if !fn.IsFunction() {
t.Errorf("ctx.NewFunctionWithCallback returned value that is not a function")
}
tlog(t, "Function is a callback function")
if fn.ToValue().ToStringOrDie() != "nativecallback" {
t.Errorf("ctx.NewFunctionWithCallback returned value that does not convert to property string")
}
tlog(t, "Successfully converted to property string")
tlog(t, "Calling as function...")
fn.CallAsFunction(nil, []*Value{})
if !flag {
t.Errorf("Native function did not execute")
}
tlog(t, "Called as function.")
}
func TestNewFunctionWithCallback2(t *testing.T) {
callback := func(ctx *Context, obj *Object, thisObject *Object, args []*Value) *Value {
tlog(t, "In callback function!")
if len(args) != 2 {
return nil
}
tlog(t, "Attempting to convert args to numbers...", args)
tlog(t, ctx)
tlog(t, args[0], args[1])
tlog(t, args[0].ctx, args[1].ctx)
tlog(t, args[0].ref, args[1].ref)
//a, err := args[0].ctx.ToNumber(args[0])
//tlog(t, a, err)
//return ctx.NewNumberValue(2)
a, err := args[0].ToNumber()
tlog(t, err)
tlog(t, "Converted first arg...")
b := args[1].ToNumberOrDie()
return ctx.NewNumberValue(a + b)
return ctx.NewNumberValue(1)
return ctx.newValue(nil)
}
tlog(t, "Acquiring context!")
ctx := NewContext()
defer ctx.Release()
tlog(t, "Creating a new function with callback")
fn := ctx.NewFunctionWithCallback(callback)
tlog(t, "Ceating new number values")
numarr := make([]*Value, 2)
numarr[0] = ctx.NewNumberValue(1.5)
numarr[1] = ctx.NewNumberValue(3.0)
tlog(t, "Calling callback as function")
val, err := fn.CallAsFunction(nil, numarr)
tlog(t, "Called callback as function!")
tlog(t, err, val)
if err != nil || val == nil {
t.Fatalf("Error executing native callback")
}
if val.ToNumberOrDie() != 4.5 {
t.Fatalf("Native callback did not return the correct value")
}
}
func TestNewFunctionWithCallbackPanic(t *testing.T) {
var callbacks = []GoFunctionCallback{}
var error_msgs = []string{"error from go!", syscall.ENOMEM.Error()}
callbacks = append(callbacks,
func(ctx *Context, obj *Object, thisObject *Object, _ []*Value) *Value {
panic("error from go!")
return nil
},
)
callbacks = append(callbacks,
func(ctx *Context, obj *Object, thisObject *Object, _ []*Value) *Value {
panic(syscall.ENOMEM)
return nil
},
)
ctx := NewContext()
defer ctx.Release()
for index, callback := range callbacks {
fn := ctx.NewFunctionWithCallback(callback)
if fn == nil {
t.Fatalf("ctx.NewFunctionWithCallback failed")
return
}
if !fn.IsFunction() {
t.Fatalf("ctx.NewFunctionWithCallback returned value that is not a function")
}
if fn.ToValue().ToStringOrDie() != "nativecallback" {
t.Fatalf("ctx.NewFunctionWithCallback returned value that does not convert to property string")
}
val, err := fn.CallAsFunction(nil, nil)
if val != nil {
t.Fatalf("ctx.NewFunctionWithCallback that panicked returned a value")
}
if err == nil {
t.Fatalf("want err != nil for function that panicked")
}
if err.Error() != error_msgs[index] {
t.Fatalf("want exception message %q, got %q", err, error_msgs[index])
}
}
}
func TestNativeFunction(t *testing.T) {
var flag bool
callback := func() {
flag = true
}
ctx := NewContext()
defer ctx.Release()
fn := ctx.NewFunctionWithNative(callback)
if fn == nil {
t.Errorf("ctx.NewFunctionWithNative failed")
return
}
if !fn.IsFunction() {
t.Errorf("ctx.NewFunctionWithNative returned value that is not a function")
}
if fn.ToValue().ToStringOrDie() != "nativefunction" {
t.Errorf("ctx.nativefunction returned value that does not convert to property string")
}
fn.CallAsFunction(nil, nil)
if !flag {
t.Errorf("Native function did not execute")
}
}
func TestNativeFunction2(t *testing.T) {
callback := func(a float64, b float64) float64 {
return a + float64(b)
}
ctx := NewContext()
defer ctx.Release()
fn := ctx.NewFunctionWithNative(callback)
if fn == nil {
t.Errorf("ctx.NewFunctionWithNative failed")
return
}
if !fn.IsFunction() {
t.Errorf("ctx.NewFunctionWithNative returned value that is not a function")
}
args := make([]*Value, 2)
args[0] = ctx.NewNumberValue(1.5)
args[1] = ctx.NewNumberValue(3.0)
val, err := fn.CallAsFunction(nil, args)
tlog(t, "Called as function")
if err != nil || val == nil {
t.Errorf("Error executing native function (%v)", err)
}
wantNum := 4.5
gotNum, err := val.ToNumber()
if err != nil {
t.Error("ToNumber", err)
} else if wantNum != gotNum {
t.Errorf("want return value %v, got %v", wantNum, gotNum)
}
}
func TestNativeFunction3(t *testing.T) {
ctx := NewContext()
defer ctx.Release()
callback := func(a float64, b float64) *Value {
ret := a + float64(b)
return ctx.NewNumberValue(ret)
}
fn := ctx.NewFunctionWithNative(callback)
if fn == nil {
t.Errorf("ctx.NewFunctionWithNative failed")
return
}
if !fn.IsFunction() {
t.Errorf("ctx.NewFunctionWithNative returned value that is not a function")
}
a := ctx.NewNumberValue(1.5)
b := ctx.NewNumberValue(3.0)
val, err := fn.CallAsFunction(nil, []*Value{a, b})
if err != nil || val == nil {
t.Errorf("Error executing native function (%v)", err)
}
if val.ToNumberOrDie() != 4.5 {
t.Errorf("Native function did not return the correct value")
}
}
func TestNativeFunctionPanic(t *testing.T) {
ctx := NewContext()
defer ctx.Release()
callbacks := []func(){
func() { panic("Panic!") }, func() { panic(syscall.ENOMEM) }}
for _, callback := range callbacks {
fn := ctx.NewFunctionWithNative(callback)
if fn == nil {
t.Errorf("ctx.NewFunctionWithNative failed")
return
}
if !fn.IsFunction() {
t.Errorf("ctx.NewFunctionWithNative returned value that is not a function")
}
val, err := fn.CallAsFunction(nil, nil)
tlog(t, "Called as function")
tlog(t, val, err)
if err == nil || val != nil {
t.Fatalf("ctx.CallAsFunction did not panic as expected")
}
tlog(t, "About to convert to string!")
if err.Error() == "" {
t.Errorf("want non-empty error message, got %q", err)
} else {
t.Logf("ctx.CallAsFunction paniced as expected (%v)", err)
}
}
}
func TestNewNativeObject(t *testing.T) {
obj := &reflect_object{-1, 2, 3.0, "four"}
ctx := NewContext()
defer ctx.Release()
v := ctx.NewNativeObject(obj)
ctx.GlobalObject().SetProperty("n", v.ToValue(), 0)
// Following script access should be successful
ret, err := ctx.EvaluateScript("n.F", nil, "./testing.go", 1)
if err != nil {
t.Errorf("ctx.EvaluateScript returned an error: %#v", err)
return
}
if ret == nil {
t.Errorf("ctx.EvaluateScript did not return a result (no error specified)!")
return
}
if !ret.IsNumber() {
t.Errorf("ctx.EvaluateScript did not return 'number' result when accessing native object's non-existent field.")
}
num := ret.ToNumberOrDie()
if num != 3.0 {
t.Errorf("ctx.EvaluateScript incorrect value when accessing native object's field.")
}
// following script access should fail
ret, err = ctx.EvaluateScript("n.noexist", nil, "./testing.go", 1)
if err != nil || ret == nil {
t.Errorf("ctx.EvaluateScript returned an error (or did not return a result)")
}
if !ret.IsUndefined() {
t.Errorf("ctx.EvaluateScript did not return 'undefined' result when accessing native object's non-existent field.")
}
// following script access should succeed
ret, err = ctx.EvaluateScript("n.S", nil, "./testing.go", 1)
if err != nil || ret == nil {
t.Errorf("ctx.EvaluateScript returned an error (or did not return a result)")
}
if !ret.IsString() {
t.Errorf("ctx.EvaluateScript did not return 'string' result when accessing native object's non-existent field.")
}
str := ret.ToStringOrDie()
if str != "four" {
t.Errorf("ctx.EvaluateScript incorrect value when accessing native object's field.")
}
}
func TestNewNativeObjectSet(t *testing.T) {
obj := &reflect_object{-1, 2, 3.0, "four"}
ctx := NewContext()
defer ctx.Release()
tlog(t, "Creating new native object from", obj)
v := ctx.NewNativeObject(obj)
tlog(t, "Setting property n")
ctx.GlobalObject().SetProperty("n", v.ToValue(), 0)
tlog(t, "Creating value for property I")
// Set the integer property
i := ctx.NewNumberValue(-2)
tlog(t, "Setting property I", i)
tlog(t, i.ToStringOrDie())
v.SetProperty("I", i, 0)
tlog(t, "Set property I, checking for errors.")
if obj.I != -2 {
t.Errorf("ctx.SetProperty did not set integer field correctly")
}
tlog(t, "Setting property U")
// Set the unsigned integer property
u := ctx.NewNumberValue(3)
v.SetProperty("U", u, 0)
if obj.U != 3 {
t.Fatalf("ctx.SetProperty did not set unsigned integer field correctly")
}
// t.Error("Skipping setting property U to invalid value, it currently causes a fault.")
// Set the unsigned integer property
u = ctx.NewNumberValue(-3)
tlog(t, "Setting property U to invalid value")
err := v.SetProperty("U", u, 0)
tlog(t, "Set property, checking for correctness...")
if err == nil {
t.Errorf("ctx.SetProperty did not set unsigned integer field correctly: No error was returned")
} else {
t.Logf("%v", err)
}
if obj.U != 3 {
t.Errorf("ctx.SetProperty did not set unsigned integer field correctly: Incorrect value")
}
// Set the float property
n := ctx.NewNumberValue(4.0)
v.SetProperty("F", n, 0)
if obj.F != 4.0 {
t.Errorf("ctx.SetProperty did not set float field correctly")
}
s := ctx.NewStringValue("five")
v.SetProperty("S", s, 0)
if obj.S != "five" {
t.Errorf("ctx.SetProperty did not set string field correctly")
}
}
func TestNewNativeObjectConvert(t *testing.T) {
obj := &reflect_object{-1, 2, 3.0, "four"}
ctx := NewContext()
defer ctx.Release()
v := ctx.NewNativeObject(obj)
if v.ToValue().ToStringOrDie() != "four" {
t.Errorf("ctx.ToStringOrDie for native object did not return correct value.")
}
}
func TestNewNativeObjectMethod(t *testing.T) {
obj := &reflect_object{-1, 2, 3.0, "four"}
ctx := NewContext()
defer ctx.Release()
v := ctx.NewNativeObject(obj)
ctx.GlobalObject().SetProperty("n", v.ToValue(), 0)
tlog(t, "Testing n.Add()")
// Following script access should be successful
ret, err := ctx.EvaluateScript("n.Add()", nil, "./testing.go", 1)
tlog(t, "Evaluated Script")
if err != nil {
t.Errorf("ctx.EvaluateScript returned an error: %#v", err)
return
}
tlog(t, "No error")
if ret == nil {
t.Errorf("ctx.EvaluateScript did not return a result! (no error)")
return
}
tlog(t, "Result was returned")
if !ret.IsNumber() {
t.Errorf("ctx.EvaluateScript did not return 'number' result when calling method 'Add'.")
}
tlog(t, "sucessfully checked that value was a number")
num := ret.ToNumberOrDie()
if num != 2.0 {
t.Errorf("ctx.EvaluateScript incorrect value when accessing native object's field.")
}
tlog(t, "Testing n.AddWith()")
// Following script access should be successful
ret, err = ctx.EvaluateScript("n.AddWith(0.5)", nil, "./testing.go", 1)
if err != nil || ret == nil {
t.Errorf("ctx.EvaluateScript returned an error (or did not return a result)")
return
}
if !ret.IsNumber() {
t.Errorf("ctx.EvaluateScript did not return 'number' result when calling method 'AddWith'.")
}
num = ret.ToNumberOrDie()
if num != 2.5 {
t.Errorf("ctx.EvaluateScript incorrect value when accessing native object's field.")
}
// Following script access should be successful
ret, err = ctx.EvaluateScript("n.Self()", nil, "./testing.go", 1)
if err != nil || ret == nil {
t.Errorf("ctx.EvaluateScript returned an error (or did not return a result)")
return
}
if !ret.IsObject() {
t.Errorf("ctx.EvaluateScript did not return 'object' result when calling method 'Self'.")
}
// Following script access should be successful
ret, err = ctx.EvaluateScript("n.Null()", nil, "./testing.go", 1)
if err != nil || ret == nil {
t.Errorf("ctx.EvaluateScript 'n.Null()' returned an error (or did not return a result)")
t.Logf("Error: %s", err)
return
}
if !ret.IsNull() {
t.Errorf("ctx.EvaluateScript 'n.Null()'did not return a javascript null value.")
}
}