elm-explorations / test

Write unit and fuzz tests for Elm code.
https://package.elm-lang.org/packages/elm-explorations/test/latest
BSD 3-Clause "New" or "Revised" License
237 stars 39 forks source link

Filtering some inputs from fuzz generated values #136

Closed AntoineGagne closed 4 years ago

AntoineGagne commented 4 years ago

Hi, I checked the documentation and I couldn't find a way to filter out values from Fuzzer. Is it something that is possible? I am looking for something akin to suchThat in QuickCheck (Haskell) or ?SUCHTHAT macro in PropEr (Erlang).

Thanks!

drathier commented 4 years ago

We decided to not include that because it's too easy to accidentally filter out too many values. It's much better to build a custom Generator/Fuzzer that only generates good values, or to use map to turn invalid values into valid ones, e.g. negative numbers can be mapped with (\x -> x * -1) to make them valid. If you do want to filter out values yourself, you can do something like this inside your test:

if someCondition then
  a |> Expect.equal b
else
  Expect.pass --skip the input
laurentpayot commented 4 years ago

@AntoineGagne I ended up writing my own suchThat based on @drathier answer:

import Expect exposing (Expectation)

suchThat : (a -> Bool) -> (a -> Expectation) -> a -> Expectation
suchThat filter expect value =
    if filter value then
        expect value
    else
        Expect.pass

I use it like so:

fuzz string "True if non empty string" <| 
    suchThat (not << String.isEmpty) <|
        \randomStr ->   
            myFunction randomStr
            |> Expect.equal True