Repository navigation
|
In a more recent test helper module of mine, spacetest, I have a test helper function Now, as preparing the stage for the caller supplied func is involved and can fail in multiple ways, the helper's "guts" judiciously do a lot of Gomega assertions. Some of these are in the new go routine. How can I ensure that if an assertion in the new go routine fails, the test author sees the call site of the test helper, not a place deep in the guts of the test helper itself? |
Replies: 2 comments 5 replies
|
heyo - have you tried calling In that case I think you'll need a way (some sort of channel or synchronization mechanism) to have the spawned goroutine phone back to the test helper caller and let it know things failed. In this case you might want a custom gomega instance so you can handle the failure yourself (and either panic to exit or early... or not as the case may be) and then communicate the failure back to the test helper caller, at which point you can call Ginkgo's |
|
ah I think I'm tracking now. I cooked this up and tried it on my machine: type ResultEnum uint8
const (
Success ResultEnum = iota
InternalFailure
UserFailure
UserPanic
)
type Result struct {
Result ResultEnum
Message string
Panic any
}
func Execute(fn func(), sprocket int) {
c := make(chan Result)
go execute(c, fn, sprocket)
result := <-c
switch result.Result {
case Success:
return
case UserFailure:
return // a user failure will have already registered a failure with Ginkgo
case InternalFailure, UserPanic:
Fail(result.Message)
}
}
func execute(c chan Result, fn func(), sprocket int) {
defer func() {
if r := recover(); r != nil {
switch result := r.(type) {
case Result:
c <- result
case types.GinkgoError: // this is a ginkgo failure coming through `Fail`
c <- Result{Result: UserFailure}
default:
c <- Result{Result: UserPanic, Message: fmt.Sprintf("Your execute function panicked:\n%v\n\n%s", r, string(debug.Stack()))}
}
}
}()
g := NewGomega(func(message string, _ ...int) {
panic(Result{Result: InternalFailure, Message: message})
})
g.Ω(sprocket).Should(BeNumerically("<", 5))
fn()
g.Ω(sprocket).Should(BeNumerically(">", 0))
c <- Result{Result: Success}
}A test looks like this: var _ = Describe("helper", func() {
It("can succeed", func() {
ran := false
Execute(func() {
ran = true
}, 3)
Ω(ran).Should(BeTrue())
})
It("can handle internal failures before the function is called", func() {
Execute(func() {}, 6)
})
It("can handle internal failures after the function is called", func() {
Execute(func() {}, 0)
})
It("can handle ginkgo/gomega failures in the function", func() {
Execute(func() {
Ω("foo").Should(Equal("bar"))
}, 3)
})
It("can handle panics in the function", func() {
Execute(func() {
panic("bam")
}, 3)
})
})And the line numbers match expectations. the second and third Sorry it's so messy. The additional wrinkle of a user-induced |
ah I think I'm tracking now. I cooked this up and tried it on my machine: