Grep

func Grep(filter, expectedValue any) TestDeep

Grep is a smuggler operator. It takes an array, a slice or a pointer on array/slice. For each item it applies filter, a TestDeep operator or a function returning a bool, and produces a slice consisting of those items for which the filter matched and compares it to expectedValue. The filter matches when it is a:

  • TestDeep operator and it matches for the item;
  • function receiving the item and it returns true.

expectedValue can be a TestDeep operator or a slice (but never an array nor a pointer on a slice/array nor any other kind).

got := []int{-3, -2, -1, 0, 1, 2, 3}
td.Cmp(t, got, td.Grep(td.Gt(0), []int{1, 2, 3})) // succeeds
td.Cmp(t, got, td.Grep(
  func(x int) bool { return x%2 == 0 },
  []int{-2, 0, 2})) // succeeds
td.Cmp(t, got, td.Grep(
  func(x int) bool { return x%2 == 0 },
  td.Set(0, 2, -2))) // succeeds

If Grep receives a nil slice or a pointer on a nil slice, it always returns a nil slice:

var got []int
td.Cmp(t, got, td.Grep(td.Gt(0), ([]int)(nil))) // succeeds
td.Cmp(t, got, td.Grep(td.Gt(0), td.Nil()))     // succeeds
td.Cmp(t, got, td.Grep(td.Gt(0), []int{}))      // fails

See also First, Last and Flatten.

See also Grep godoc.

Examples

Classic example
Nil example
Struct example
Json example

CmpGrep shortcut

func CmpGrep(t TestingT, got, filter , expectedValue any, args ...any) bool

CmpGrep is a shortcut for:

td.Cmp(t, got, td.Grep(filter, expectedValue), args...)

See above for details.

Returns true if the test is OK, false if it fails.

If t is a *T then its Config field is inherited.

args… are optional and allow to name the test. This name is used in case of failure to qualify the test. If len(args) > 1 and the first item of args is a string and contains a ‘%’ rune then fmt.Fprintf is used to compose the name, else args are passed to fmt.Fprint. Do not forget it is the name of the test, not the reason of a potential failure.

See also CmpGrep godoc.

Examples

Classic example
Nil example
Struct example

T.Grep shortcut

func (t *T) Grep(got, filter , expectedValue any, args ...any) bool

Grep is a shortcut for:

t.Cmp(got, td.Grep(filter, expectedValue), args...)

See above for details.

Returns true if the test is OK, false if it fails.

args… are optional and allow to name the test. This name is used in case of failure to qualify the test. If len(args) > 1 and the first item of args is a string and contains a ‘%’ rune then fmt.Fprintf is used to compose the name, else args are passed to fmt.Fprint. Do not forget it is the name of the test, not the reason of a potential failure.

See also T.Grep godoc.

Examples

Classic example
Nil example
Struct example