Skip to content

Commit

Permalink
slices: make EqSliceFunc more flexible on types (#108)
Browse files Browse the repository at this point in the history
This PR makes EqSliceFunc accept slices of two different types that
are then compared by the supplied comparator - which accepts one of
each type.
  • Loading branch information
shoenig authored Mar 3, 2023
1 parent 23af83e commit 6667142
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 6 deletions.
4 changes: 2 additions & 2 deletions internal/assertions/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ func validJSON(input []byte) (s string) {
return
}

func EqSliceFunc[A any](exp, val []A, eq func(a, b A) bool) (s string) {
func EqSliceFunc[A, B any](exp []B, val []A, eq func(a A, b B) bool) (s string) {
lenA, lenB := len(exp), len(val)

if lenA != lenB {
Expand All @@ -277,7 +277,7 @@ func EqSliceFunc[A any](exp, val []A, eq func(a, b A) bool) (s string) {

miss := false
for i := 0; i < lenA; i++ {
if !eq(exp[i], val[i]) {
if !eq(val[i], exp[i]) {
miss = true
break
}
Expand Down
4 changes: 2 additions & 2 deletions must/must.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions must/must_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ func Lesser[L interfaces.LessFunc[L]](t T, exp, val L, settings ...Setting) {
invoke(t, assertions.Lesser(exp, val), settings...)
}

// SliceEqFunc asserts elements of exp and val are the same using eq.
func SliceEqFunc[A any](t T, exp, val []A, eq func(a, b A) bool, settings ...Setting) {
// SliceEqFunc asserts elements of val satisfy eq for the corresponding element in exp.
func SliceEqFunc[A, B any](t T, exp []B, val []A, eq func(expectation A, value B) bool, settings ...Setting) {
t.Helper()
invoke(t, assertions.EqSliceFunc(exp, val, eq), settings...)
}
Expand Down
14 changes: 14 additions & 0 deletions test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,20 @@ func TestSliceEqFunc(t *testing.T) {
return a.ID == b.ID
})
})

t.Run("translate", func(t *testing.T) {
tc := newCase(t, `expected slice equality via 'eq' function`)
t.Cleanup(tc.assert)

values := []*Person{
{ID: 100, Name: "Alice"},
{ID: 101, Name: "Bob"},
}
exp := []string{"Alice", "Carl"}
SliceEqFunc(tc, exp, values, func(a *Person, name string) bool {
return a.Name == name
})
})
}

func TestSliceEqFunc_PS(t *testing.T) {
Expand Down

0 comments on commit 6667142

Please sign in to comment.