Skip to content

Commit

Permalink
add syntax sugar to run function on non ok sandbox results
Browse files Browse the repository at this point in the history
  • Loading branch information
adamluzsi committed Jul 23, 2024
1 parent 800c383 commit 5088462
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions sandbox/Run.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ func (ro RunOutcome) Trace() string {
return buf.String()
}

// OnNotOK will execute the argument block when the OK state is false.
func (ro RunOutcome) OnNotOK(blk func()) {
if ro.OK {
return
}
if blk == nil {
return
}
blk()
}

func stackHasGoexit() bool {
const goexitFuncName = "runtime.Goexit"
return caller.Until(func(frame runtime.Frame) bool {
Expand Down
20 changes: 20 additions & 0 deletions sandbox/Run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"go.llib.dev/testcase"
"go.llib.dev/testcase/assert"
"go.llib.dev/testcase/sandbox"
)

Expand Down Expand Up @@ -72,3 +73,22 @@ func TestRun(t *testing.T) {
})
})
}

func TestRunOutcome_OnNotOK(t *testing.T) {
t.Run("happy", func(t *testing.T) {
var ran bool
sandbox.Run(func() {}).
OnNotOK(func() { ran = true })
assert.False(t, ran)
})
t.Run("rainy", func(t *testing.T) {
var ran bool
sandbox.Run(func() { panic("boom") }).
OnNotOK(func() { ran = true })
assert.True(t, ran)
})
t.Run("rainy plus nil block", func(t *testing.T) {
sandbox.Run(func() { panic("boom") }).
OnNotOK(nil)
})
}

0 comments on commit 5088462

Please sign in to comment.