Skip to content

Commit

Permalink
fixup! Add Fuzz.filterMap
Browse files Browse the repository at this point in the history
  • Loading branch information
mbaechler committed Jan 12, 2024
1 parent fc66bf7 commit 55c4cd2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
18 changes: 17 additions & 1 deletion src/Fuzz.elm
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ can usually find the simplest input that reproduces a bug.
## Working with Fuzzers
@docs constant, invalid, filter
@docs constant, invalid, filter, filterMap
@docs map, map2, map3, map4, map5, map6, map7, map8, andMap
@docs andThen, lazy, sequence, traverse
Expand Down Expand Up @@ -1341,6 +1341,22 @@ filter predicate = filterMap (\a -> if predicate a then Just a else Nothing)
{-| A fuzzer that applies a function returning a Maybe on a given fuzzer and
output values, as List.filterMap does.
Example usage:
type UnicodeNonLetter = UnicodeNonLetter Char
fromChar : Char -> Maybe UnicodeNonLetter
fromChar c =
if (c |> Unicode.isLower |> not) && (c |> Unicode.isUpper |> not) then
UnicodeNonLetter |> Just
else
Nothing
fuzz : Fuzzer UnicodeNonLetter
fuzz =
Fuzz.char |> Fuzz.filterMap fromChar
Warning: By using `Fuzz.filterMap` you can get exceptionally unlucky and get 15
rejections in a row, in which case the test will fluke out and fail!
Expand Down
4 changes: 2 additions & 2 deletions tests/src/FuzzerTests.elm
Original file line number Diff line number Diff line change
Expand Up @@ -1145,14 +1145,14 @@ fuzzerSpecificationTests =
intsNotDivBy5 : Fuzzer Int
intsNotDivBy5 =
Fuzz.int
|> Fuzz.filterMap (\i -> if isDivBy5 i then Just i else Nothing)
|> Fuzz.filterMap (\i -> if isDivBy5 i then Nothing else Just i)

in
[ rejects "impossible func (always Nothing)"
(Fuzz.int |> Fuzz.filterMap (\_ -> Nothing))
"Too many values were filtered out"
, passes "trivial func (always Just) doesn't reject"
(Fuzz.int |> Fuzz.filterMap (\_ -> True))
(Fuzz.int |> Fuzz.filterMap Just)
(\_ -> True)
, canGenerateSatisfyingWith { runs = 5000 } "not divisible by 5" intsNotDivBy5 (not << isDivBy5)
, cannotGenerateSatisfyingWith { runs = 5000 } "divisible by 5" intsNotDivBy5 isDivBy5
Expand Down

0 comments on commit 55c4cd2

Please sign in to comment.