testify icon indicating copy to clipboard operation
testify copied to clipboard

feat: Support `iter.Seq`s in `[Not]Contains` and `[Not]ElementsMatch`

Open misberner opened this issue 11 months ago • 5 comments
trafficstars

Summary

This PR adds support iter.Seq[...] sequences (introduced in Go 1.23, or earlier via rangefunc experiment) in the Contains and ElementsMatch (+ derived) asserters.

Changes

  • Introduced a seqToSlice helper that transparently converts an iter.Seq (which is a function of signature func(func(T) bool)) to a corresponding slice of type []T, if support for sequences is enabled. Otherwise, it does nothing. Note: this function is reflection-based and does not introduce any source dependencies on newer language features, thereby respecting the Go version constraint in the go.mod file.
  • Used the seqToSlice helper in the above-mentioned asserters to contain any inputs from sequence to slice form (this has to happen early on because of the empty check)
  • Added tests (conditional on the support for sequences) for these matchers on sequences

Motivation

Sequences are a new language feature that as of go1.23 has become standard for obtaining sequences of values w/o requiring to materialize the values into a slice (e.g., maps.Keys(...), maps.Values(...)). Currently, using these sequences in matchers requires materialization via slices.Collect. However, since ElementsMatch and Contains are conceptually applicable to sequences in addition to slices, arrays etc., this should be handled by the testify framework.

Example usage

requires go1.23

import "slices"
import "maps"
...
assert.ElementsMatch(slices.Values([]string{"hello", "world"}), []string{"world", "hello"})
assert.NotContains(maps.Values(map[int]string{1: "foo", 2: "bar"}), "baz")

## Related issues
N/A

misberner avatar Dec 12 '24 11:12 misberner