2015-03-15 08:13:39 +02:00
|
|
|
package jsre
|
|
|
|
|
|
|
|
import (
|
2015-03-20 14:22:01 +02:00
|
|
|
"github.com/robertkrimen/otto"
|
2015-03-15 08:13:39 +02:00
|
|
|
"testing"
|
|
|
|
|
2015-03-16 17:48:54 +02:00
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2015-03-15 08:13:39 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type testNativeObjectBinding struct {
|
|
|
|
toVal func(interface{}) otto.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
type msg struct {
|
|
|
|
Msg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
|
|
|
|
m, err := call.Argument(0).ToString()
|
|
|
|
if err != nil {
|
|
|
|
return otto.UndefinedValue()
|
|
|
|
}
|
|
|
|
return no.toVal(&msg{m})
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestExec(t *testing.T) {
|
|
|
|
jsre := New("/tmp")
|
|
|
|
|
2015-03-16 17:48:54 +02:00
|
|
|
common.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`))
|
2015-03-15 08:13:39 +02:00
|
|
|
err := jsre.Exec("test.js")
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
|
|
|
}
|
|
|
|
val, err := jsre.Run("msg")
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
|
|
|
}
|
|
|
|
if !val.IsString() {
|
|
|
|
t.Errorf("expected string value, got %v", val)
|
|
|
|
}
|
2015-03-15 13:42:17 +02:00
|
|
|
exp := "testMsg"
|
|
|
|
got, _ := val.ToString()
|
|
|
|
if exp != got {
|
|
|
|
t.Errorf("expected '%v', got '%v'", exp, got)
|
2015-03-15 08:13:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestBind(t *testing.T) {
|
2015-03-15 13:42:17 +02:00
|
|
|
jsre := New("/tmp")
|
2015-03-15 08:13:39 +02:00
|
|
|
|
|
|
|
jsre.Bind("no", &testNativeObjectBinding{jsre.ToVal})
|
|
|
|
|
2015-03-20 14:48:23 +02:00
|
|
|
val, err := jsre.Run(`no.TestMethod("testMsg")`)
|
2015-03-15 08:13:39 +02:00
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
|
|
|
}
|
|
|
|
pp, err := jsre.PrettyPrint(val)
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
|
|
|
}
|
|
|
|
t.Logf("no: %v", pp)
|
|
|
|
}
|
|
|
|
|
2015-03-15 13:42:17 +02:00
|
|
|
func TestLoadScript(t *testing.T) {
|
|
|
|
jsre := New("/tmp")
|
2015-03-15 08:13:39 +02:00
|
|
|
|
2015-03-16 17:48:54 +02:00
|
|
|
common.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`))
|
2015-03-15 13:42:17 +02:00
|
|
|
_, err := jsre.Run(`loadScript("test.js")`)
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
2015-03-15 08:13:39 +02:00
|
|
|
}
|
2015-03-15 13:42:17 +02:00
|
|
|
val, err := jsre.Run("msg")
|
2015-03-15 08:13:39 +02:00
|
|
|
if err != nil {
|
|
|
|
t.Errorf("expected no error, got %v", err)
|
|
|
|
}
|
2015-03-15 13:42:17 +02:00
|
|
|
if !val.IsString() {
|
|
|
|
t.Errorf("expected string value, got %v", val)
|
|
|
|
}
|
|
|
|
exp := "testMsg"
|
|
|
|
got, _ := val.ToString()
|
|
|
|
if exp != got {
|
|
|
|
t.Errorf("expected '%v', got '%v'", exp, got)
|
|
|
|
}
|
2015-03-15 08:13:39 +02:00
|
|
|
}
|