Skip to content

Commit

Permalink
Make most of the AssertThat logic testable and write a simple test fo…
Browse files Browse the repository at this point in the history
…r it.
  • Loading branch information
metlos committed Feb 22, 2024
1 parent 554737c commit 2c2e36e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
13 changes: 12 additions & 1 deletion pkg/test/assertions/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ import (
// the Explain function.
func AssertThat(t *testing.T, object client.Object, predicates ...Predicate[client.Object]) {
t.Helper()
message := assertThat(object, predicates...)
if message != "" {
assert.Fail(t, "some predicates failed to match", message)
}
}

// assertThat contains the actual logic of the AssertThat function. This is separated out into
// its own testable function because we cannot cannot capture the result of assert.Fail() in
// another test.
func assertThat(object client.Object, predicates ...Predicate[client.Object]) string {
results := make([]bool, len(predicates))
failure := false
for i, p := range predicates {
Expand All @@ -45,8 +55,9 @@ func AssertThat(t *testing.T, object client.Object, predicates ...Predicate[clie
sb.WriteString(Explain(p, object))
}
}
assert.Fail(t, "some predicates failed to match", sb.String())
return sb.String()
}
return ""
}

// Explain produces a textual explanation for why the provided predicate didn't match. The explanation
Expand Down
29 changes: 29 additions & 0 deletions pkg/test/assertions/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,35 @@ func TestExplain(t *testing.T) {
})
}

func TestAssertThat(t *testing.T) {
t.Run("positive case", func(t *testing.T) {
// given
actual := &corev1.ConfigMap{}
actual.SetName("actual")
actual.SetLabels(map[string]string{"k": "v"})

// when
message := assertThat(actual, Has(Name("actual")), Has(Labels(map[string]string{"k": "v"})))

// then
assert.Empty(t, message)
})

t.Run("negative case", func(t *testing.T) {
// given
actual := &corev1.ConfigMap{}
actual.SetName("actual")
actual.SetLabels(map[string]string{"k": "v"})

// when
message := assertThat(actual, Has(Name("expected")), Has(Labels(map[string]string{"k": "another value"})))

// then
assert.Contains(t, message, "predicate 'assertions.named' didn't match the object because of the following differences")
assert.Contains(t, message, "predicate 'assertions.hasLabels' didn't match the object because of the following differences")
})
}

type predicateWithoutFixing struct{}

var _ Predicate[client.Object] = (*predicateWithoutFixing)(nil)
Expand Down

0 comments on commit 2c2e36e

Please sign in to comment.