gopkg.in/olebedev/go-duktape.v1@v1.0.0-20151008052556-e2ae92f01e4a/duktape_test.go (about) 1 package duktape 2 3 import ( 4 "testing" 5 6 . "gopkg.in/check.v1" 7 ) 8 9 // Hook up gocheck into the "go test" runner. 10 func Test(t *testing.T) { TestingT(t) } 11 12 var _ = Suite(&DuktapeSuite{}) 13 14 type DuktapeSuite struct { 15 ctx *Context 16 } 17 18 func (s *DuktapeSuite) SetUpTest(c *C) { 19 s.ctx = New() 20 } 21 22 func (s *DuktapeSuite) TestPushGlobalGoFunction_Call(c *C) { 23 var check bool 24 idx, err := s.ctx.PushGlobalGoFunction("test", func(c *Context) int { 25 check = !check 26 return 0 27 }) 28 29 c.Assert(err, IsNil) 30 c.Assert(idx, Not(Equals), -1) 31 32 c.Assert(s.ctx.fnIndex.functions, HasLen, 1) 33 34 err = s.ctx.PevalString("test();") 35 c.Assert(err, IsNil) 36 c.Assert(check, Equals, true) 37 38 err = s.ctx.PevalString("test();") 39 c.Assert(err, IsNil) 40 c.Assert(check, Equals, false) 41 } 42 43 func (s *DuktapeSuite) TestPushGlobalGoFunction_Malformed(c *C) { 44 idx, err := s.ctx.PushGlobalGoFunction(".", func(c *Context) int { 45 return 0 46 }) 47 48 c.Assert(err, ErrorMatches, "Malformed function name '.'") 49 c.Assert(idx, Equals, -1) 50 } 51 52 func (s *DuktapeSuite) TestPushGlobalGoFunction_Finalize(c *C) { 53 s.ctx.PushGlobalGoFunction("test", func(c *Context) int { 54 return 0 55 }) 56 57 c.Assert(s.ctx.fnIndex.functions, HasLen, 1) 58 59 err := s.ctx.PevalString("test = undefined") 60 c.Assert(err, IsNil) 61 62 s.ctx.Gc(0) 63 c.Assert(s.ctx.fnIndex.functions, HasLen, 0) 64 } 65 66 func (s *DuktapeSuite) TestPushGoFunction_Call(c *C) { 67 var check bool 68 s.ctx.PushGlobalObject() 69 s.ctx.PushGoFunction(func(c *Context) int { 70 check = !check 71 return 0 72 }) 73 74 s.ctx.PutPropString(-2, "test") 75 s.ctx.Pop() 76 77 c.Assert(s.ctx.fnIndex.functions, HasLen, 1) 78 79 err := s.ctx.PevalString("test();") 80 c.Assert(err, IsNil) 81 c.Assert(check, Equals, true) 82 83 err = s.ctx.PevalString("test();") 84 c.Assert(err, IsNil) 85 c.Assert(check, Equals, false) 86 } 87 88 func goTestfunc(ctx *Context) int { 89 top := ctx.GetTop() 90 a := ctx.GetNumber(top - 2) 91 b := ctx.GetNumber(top - 1) 92 ctx.PushNumber(a + b) 93 return 1 94 } 95 96 func (s *DuktapeSuite) TestMyAddTwo(c *C) { 97 s.ctx.PushGlobalGoFunction("adder", goTestfunc) 98 err := s.ctx.PevalString(`print("2 + 3 =", adder(2,3))`) 99 c.Assert(err, IsNil) 100 101 s.ctx.Pop() 102 103 err = s.ctx.PevalString(`adder(2,3)`) 104 c.Assert(err, IsNil) 105 106 c.Assert(s.ctx.GetNumber(-1), Equals, 5.0) 107 } 108 109 func (s *DuktapeSuite) TearDownTest(c *C) { 110 s.ctx.DestroyHeap() 111 }