jsre_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package jsre
  2. import (
  3. "github.com/robertkrimen/otto"
  4. "io/ioutil"
  5. "os"
  6. "testing"
  7. )
  8. type testNativeObjectBinding struct {
  9. toVal func(interface{}) otto.Value
  10. }
  11. type msg struct {
  12. Msg string
  13. }
  14. func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
  15. m, err := call.Argument(0).ToString()
  16. if err != nil {
  17. return otto.UndefinedValue()
  18. }
  19. return no.toVal(&msg{m})
  20. }
  21. func TestExec(t *testing.T) {
  22. jsre := New("/tmp")
  23. ioutil.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`), os.ModePerm)
  24. err := jsre.Exec("test.js")
  25. if err != nil {
  26. t.Errorf("expected no error, got %v", err)
  27. }
  28. val, err := jsre.Run("msg")
  29. if err != nil {
  30. t.Errorf("expected no error, got %v", err)
  31. }
  32. if !val.IsString() {
  33. t.Errorf("expected string value, got %v", val)
  34. }
  35. exp := "testMsg"
  36. got, _ := val.ToString()
  37. if exp != got {
  38. t.Errorf("expected '%v', got '%v'", exp, got)
  39. }
  40. }
  41. func TestBind(t *testing.T) {
  42. jsre := New("/tmp")
  43. jsre.Bind("no", &testNativeObjectBinding{jsre.ToVal})
  44. val, err := jsre.Run(`no.TestMethod("testMsg")`)
  45. if err != nil {
  46. t.Errorf("expected no error, got %v", err)
  47. }
  48. pp, err := jsre.PrettyPrint(val)
  49. if err != nil {
  50. t.Errorf("expected no error, got %v", err)
  51. }
  52. t.Logf("no: %v", pp)
  53. }
  54. func TestLoadScript(t *testing.T) {
  55. jsre := New("/tmp")
  56. ioutil.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`), os.ModePerm)
  57. _, err := jsre.Run(`loadScript("test.js")`)
  58. if err != nil {
  59. t.Errorf("expected no error, got %v", err)
  60. }
  61. val, err := jsre.Run("msg")
  62. if err != nil {
  63. t.Errorf("expected no error, got %v", err)
  64. }
  65. if !val.IsString() {
  66. t.Errorf("expected string value, got %v", val)
  67. }
  68. exp := "testMsg"
  69. got, _ := val.ToString()
  70. if exp != got {
  71. t.Errorf("expected '%v', got '%v'", exp, got)
  72. }
  73. }