gopkg.in/olebedev/go-duktape.v1@v1.0.0-20151008052556-e2ae92f01e4a/timers_test.go (about) 1 package duktape 2 3 import ( 4 "time" 5 6 . "gopkg.in/check.v1" 7 ) 8 9 func (s *DuktapeSuite) TestCheckTheStack(c *C) { 10 s.ctx.PushInt(1) 11 err := s.ctx.DefineTimers() 12 c.Assert(err, IsNil) 13 c.Assert(s.ctx.GetTop(), Equals, 1) 14 err = s.ctx.DefineTimers() 15 c.Assert(err.Error(), Equals, "Timers are already defined") 16 } 17 18 func (s *DuktapeSuite) TestSetTimeOut(c *C) { 19 ch := make(chan struct{}) 20 s.ctx.DefineTimers() 21 s.ctx.PushGlobalGoFunction("test", func(ctx *Context) int { 22 ctx.PushNumber(2) 23 ch <- struct{}{} 24 return 1 25 }) 26 s.ctx.PevalString(`setTimeout(test, 0);`) 27 c.Assert(s.ctx.SafeToString(-1), Equals, "1") 28 s.ctx.Pop() 29 <-ch 30 c.Assert(s.ctx.SafeToString(-1), Equals, "2") 31 s.ctx.PopN(s.ctx.GetTop()) 32 c.Succeed() 33 } 34 35 func (s *DuktapeSuite) TestCrashProcess(c *C) { 36 s.ctx.DefineTimers() 37 s.ctx.PushGlobalGoFunction("test", func(_ *Context) int { 38 return 0 39 }) 40 s.ctx.PevalString(` 41 var id = setTimeout(test, 2); 42 `) 43 } 44 45 func (s *DuktapeSuite) TestClearTimeOut(c *C) { 46 ch := make(chan struct{}, 1) // buffered channel 47 s.ctx.DefineTimers() 48 s.ctx.PushGlobalGoFunction("test", func(_ *Context) int { 49 ch <- struct{}{} 50 return 0 51 }) 52 s.ctx.PevalString(` 53 var id = setTimeout(test, 0); 54 clearTimeout(id); 55 `) 56 <-time.After(2 * time.Millisecond) 57 select { 58 case <-ch: 59 c.Fail() 60 default: 61 c.Succeed() 62 } 63 } 64 65 func (s *DuktapeSuite) TestSetInterval(c *C) { 66 ch := make(chan struct{}, 5) 67 s.ctx.DefineTimers() 68 s.ctx.PushGlobalGoFunction("test", func(_ *Context) int { 69 ch <- struct{}{} 70 return 0 71 }) 72 73 s.ctx.PevalString(`var id = setInterval(test, 0);`) 74 s.ctx.Pop() 75 <-ch 76 <-ch 77 <-ch 78 s.ctx.PevalString(`clearInterval(id);`) 79 s.ctx.Pop() // pop undefined 80 81 <-time.After(4 * time.Millisecond) 82 select { 83 case <-ch: 84 c.Fail() 85 default: 86 c.Succeed() 87 } 88 } 89 90 func (s *DuktapeSuite) TestResetTimers(c *C) { 91 s.ctx.DefineTimers() 92 s.ctx.PevalString(`setInterval(test, 2);`) 93 id := s.ctx.GetNumber(-1) 94 s.ctx.ResetTimers() 95 s.ctx.putTimer(id) 96 97 c.Assert(s.ctx.GetType(-1).IsUndefined(), Equals, true) 98 <-time.After(3 * time.Millisecond) 99 }