jsre_test.go 1.73 KB
Newer Older
zelig's avatar
zelig committed
1 2 3
package jsre

import (
4
	"github.com/robertkrimen/otto"
5 6
	"io/ioutil"
	"os"
zelig's avatar
zelig committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
	"testing"
)

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")

29
	ioutil.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`), os.ModePerm)
zelig's avatar
zelig committed
30 31 32 33 34 35 36 37 38 39 40
	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)
	}
41 42 43 44
	exp := "testMsg"
	got, _ := val.ToString()
	if exp != got {
		t.Errorf("expected '%v', got '%v'", exp, got)
zelig's avatar
zelig committed
45 46 47 48
	}
}

func TestBind(t *testing.T) {
49
	jsre := New("/tmp")
zelig's avatar
zelig committed
50 51 52

	jsre.Bind("no", &testNativeObjectBinding{jsre.ToVal})

zsfelfoldi's avatar
zsfelfoldi committed
53
	val, err := jsre.Run(`no.TestMethod("testMsg")`)
zelig's avatar
zelig committed
54 55 56 57 58 59 60 61 62 63
	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)
}

64 65
func TestLoadScript(t *testing.T) {
	jsre := New("/tmp")
zelig's avatar
zelig committed
66

67
	ioutil.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`), os.ModePerm)
68 69 70
	_, err := jsre.Run(`loadScript("test.js")`)
	if err != nil {
		t.Errorf("expected no error, got %v", err)
zelig's avatar
zelig committed
71
	}
72
	val, err := jsre.Run("msg")
zelig's avatar
zelig committed
73 74 75
	if err != nil {
		t.Errorf("expected no error, got %v", err)
	}
76 77 78 79 80 81 82 83
	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)
	}
zelig's avatar
zelig committed
84
}