Skip to content

Commit

Permalink
Merge pull request #47 from ccremer/if-else
Browse files Browse the repository at this point in the history
Add IfOrElse predicate
  • Loading branch information
ccremer committed Jul 4, 2022
2 parents b50d24e + d0ecb90 commit 83fd040
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
15 changes: 15 additions & 0 deletions predicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ func If(predicate Predicate, originalStep Step) Step {
return wrappedStep
}

// IfOrElse returns a new step that wraps the given steps and executes its action based on the given Predicate.
// The name of the step is taken from `trueStep`.
// The context.Context from the pipeline is passed through the given actions.
func IfOrElse(predicate Predicate, trueStep Step, falseStep Step) Step {
wrappedStep := Step{Name: trueStep.Name}
wrappedStep.F = func(ctx context.Context) Result {
if predicate(ctx) {
return trueStep.F(ctx)
} else {
return falseStep.F(ctx)
}
}
return wrappedStep
}

// Bool returns a Predicate that simply returns v when evaluated.
// Use BoolPtr() over Bool() if the value can change between setting up the pipeline and evaluating the predicate.
func Bool(v bool) Predicate {
Expand Down
35 changes: 35 additions & 0 deletions predicate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,41 @@ func TestIf(t *testing.T) {
}
}

func TestIfOrElse(t *testing.T) {
counter := 0
tests := map[string]struct {
givenPredicate Predicate
expectedCalls int
}{
"GivenWrappedStep_WhenPredicateEvalsTrue_ThenRunMainAction": {
givenPredicate: truePredicate(&counter),
expectedCalls: 2,
},
"GivenWrappedStep_WhenPredicateEvalsFalse_ThenRunAlternativeAction": {
givenPredicate: falsePredicate(&counter),
expectedCalls: -2,
},
}

for name, tt := range tests {
t.Run(name, func(t *testing.T) {
counter = 0
trueStep := NewStep("true", func(_ context.Context) Result {
counter++
return newEmptyResult("true")
})
falseStep := NewStep("false", func(ctx context.Context) Result {
counter--
return newEmptyResult("false")
})
wrapped := IfOrElse(tt.givenPredicate, trueStep, falseStep)
result := wrapped.F(nil)
require.NoError(t, result.Err())
assert.Equal(t, tt.expectedCalls, counter)
assert.Equal(t, trueStep.Name, wrapped.Name)
})
}
}
func TestBoolPtr(t *testing.T) {
called := false
b := false
Expand Down

0 comments on commit 83fd040

Please sign in to comment.