From 508846232fe609ae2f6430ec1fd48885a2e33a8b Mon Sep 17 00:00:00 2001 From: Adam Luzsi Date: Tue, 23 Jul 2024 21:33:58 +0200 Subject: [PATCH] add syntax sugar to run function on non ok sandbox results --- sandbox/Run.go | 11 +++++++++++ sandbox/Run_test.go | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/sandbox/Run.go b/sandbox/Run.go index b920544..2ae76a4 100644 --- a/sandbox/Run.go +++ b/sandbox/Run.go @@ -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 { diff --git a/sandbox/Run_test.go b/sandbox/Run_test.go index f06fd09..01c36e8 100644 --- a/sandbox/Run_test.go +++ b/sandbox/Run_test.go @@ -6,6 +6,7 @@ import ( "testing" "go.llib.dev/testcase" + "go.llib.dev/testcase/assert" "go.llib.dev/testcase/sandbox" ) @@ -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) + }) +}