Skip to content

Commit

Permalink
Add timeout per it block
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosnils committed Nov 1, 2016
1 parent efa9910 commit b504046
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
12 changes: 10 additions & 2 deletions goblin.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ func (g *G) Describe(name string, h func()) {
g.reporter.end()
}
}
func (g *G) Timeout(time time.Duration) {
g.timeout = time
g.timer.Reset(time)
}

type Describe struct {
name string
Expand Down Expand Up @@ -180,6 +184,7 @@ func runIt(g *G, h interface{}) {
g.mutex.Lock()
g.timedOut = false
g.mutex.Unlock()
g.timer = time.NewTimer(g.timeout)
g.shouldContinue = make(chan bool)
if call, ok := h.(func()); ok {
// the test is synchronous
Expand All @@ -204,12 +209,14 @@ func runIt(g *G, h interface{}) {
}
select {
case <-g.shouldContinue:
case <-time.After(g.timeout):
case <-g.timer.C:
//Set to nil as it shouldn't continue
g.shouldContinue = nil
g.timedOut = true
g.Fail("Test exceeded " + fmt.Sprintf("%s", g.timeout))
}
// Reset timeout value
g.timeout = *timeout
}

type G struct {
Expand All @@ -221,6 +228,7 @@ type G struct {
timedOut bool
shouldContinue chan bool
mutex sync.Mutex
timer *time.Timer
}

func (g *G) SetReporter(r Reporter) {
Expand Down Expand Up @@ -278,7 +286,7 @@ func timeTrack(start time.Time, g *G) {

func (g *G) Fail(error interface{}) {
//Skips 7 stacks due to the functions between the stack and the test
stack := ResolveStack(4)
stack := ResolveStack(7)
message := fmt.Sprintf("%v", error)
g.currentIt.failed(message, stack)
if g.shouldContinue != nil {
Expand Down
22 changes: 22 additions & 0 deletions goblin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,25 @@ func TestTimeout(t *testing.T) {
t.Fatal("Failed")
}
}

func TestItTimeout(t *testing.T) {
fakeTest := testing.T{}
os.Args = append(os.Args, "-goblin.timeout=10ms")
parseFlags()
g := Goblin(&fakeTest)

g.Describe("Test", func() {
g.It("Should override default timeout", func() {
g.Timeout(20 * time.Millisecond)
time.Sleep(15 * time.Millisecond)
})

g.It("Should revert for different it", func() {
g.Assert(g.timeout).Equal(10 * time.Millisecond)
})

})
if fakeTest.Failed() {
t.Fatal("Failed")
}
}
8 changes: 3 additions & 5 deletions resolver_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package goblin

import (
"testing"
)
import "testing"

func TestResolver(t *testing.T) {
g := Goblin(t)
Expand All @@ -15,6 +13,6 @@ func TestResolver(t *testing.T) {
}

func dummyFunc(g *G) {
stack := ResolveStack(1)
g.Assert(len(stack)).Equal(3)
stack := ResolveStack(3)
g.Assert(len(stack)).Equal(5)
}

0 comments on commit b504046

Please sign in to comment.