github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/internal/jsre/jsre_test.go (about) 1 package jsre 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path" 7 "testing" 8 "time" 9 10 "github.com/robertkrimen/otto" 11 ) 12 13 type testNativeObjectBinding struct{} 14 15 type msg struct { 16 Msg string 17 } 18 19 func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value { 20 m, err := call.Argument(0).ToString() 21 if err != nil { 22 return otto.UndefinedValue() 23 } 24 v, _ := call.Otto.ToValue(&msg{m}) 25 return v 26 } 27 28 func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) { 29 dir, err := ioutil.TempDir("", "jsre-test") 30 if err != nil { 31 t.Fatal("cannot create temporary directory:", err) 32 } 33 if testjs != "" { 34 if err := ioutil.WriteFile(path.Join(dir, "test.js"), []byte(testjs), os.ModePerm); err != nil { 35 t.Fatal("cannot create test.js:", err) 36 } 37 } 38 return New(dir, os.Stdout), dir 39 } 40 41 func TestExec(t *testing.T) { 42 jsre, dir := newWithTestJS(t, `msg = "testMsg"`) 43 defer os.RemoveAll(dir) 44 45 err := jsre.Exec("test.js") 46 if err != nil { 47 t.Errorf("expected no error, got %v", err) 48 } 49 val, err := jsre.Run("msg") 50 if err != nil { 51 t.Errorf("expected no error, got %v", err) 52 } 53 if !val.IsString() { 54 t.Errorf("expected string value, got %v", val) 55 } 56 exp := "testMsg" 57 got, _ := val.ToString() 58 if exp != got { 59 t.Errorf("expected '%v', got '%v'", exp, got) 60 } 61 jsre.Stop(false) 62 } 63 64 func TestNatto(t *testing.T) { 65 jsre, dir := newWithTestJS(t, `setTimeout(function(){msg = "testMsg"}, 1);`) 66 defer os.RemoveAll(dir) 67 68 err := jsre.Exec("test.js") 69 if err != nil { 70 t.Errorf("expected no error, got %v", err) 71 } 72 time.Sleep(100 * time.Millisecond) 73 val, err := jsre.Run("msg") 74 if err != nil { 75 t.Errorf("expected no error, got %v", err) 76 } 77 if !val.IsString() { 78 t.Errorf("expected string value, got %v", val) 79 } 80 exp := "testMsg" 81 got, _ := val.ToString() 82 if exp != got { 83 t.Errorf("expected '%v', got '%v'", exp, got) 84 } 85 jsre.Stop(false) 86 } 87 88 func TestBind(t *testing.T) { 89 jsre := New("", os.Stdout) 90 defer jsre.Stop(false) 91 92 jsre.Bind("no", &testNativeObjectBinding{}) 93 94 _, err := jsre.Run(`no.TestMethod("testMsg")`) 95 if err != nil { 96 t.Errorf("expected no error, got %v", err) 97 } 98 } 99 100 func TestLoadScript(t *testing.T) { 101 jsre, dir := newWithTestJS(t, `msg = "testMsg"`) 102 defer os.RemoveAll(dir) 103 104 _, err := jsre.Run(`loadScript("test.js")`) 105 if err != nil { 106 t.Errorf("expected no error, got %v", err) 107 } 108 val, err := jsre.Run("msg") 109 if err != nil { 110 t.Errorf("expected no error, got %v", err) 111 } 112 if !val.IsString() { 113 t.Errorf("expected string value, got %v", val) 114 } 115 exp := "testMsg" 116 got, _ := val.ToString() 117 if exp != got { 118 t.Errorf("expected '%v', got '%v'", exp, got) 119 } 120 jsre.Stop(false) 121 }