From 16a8dff346513d5c8a8e042396e280a22d7d77fd Mon Sep 17 00:00:00 2001 From: Sasha Fonseca Date: Sat, 29 Feb 2020 21:53:55 +0000 Subject: [PATCH] Add Expect.oneOf --- src/Expect.elm | 45 +++++++++++++++++++++++++++++++++++++++++++++ tests/src/Tests.elm | 13 +++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/Expect.elm b/src/Expect.elm index 498ff3c0..89aebb18 100644 --- a/src/Expect.elm +++ b/src/Expect.elm @@ -690,6 +690,51 @@ allHelp list query = outcome +{-| Passes if at least one of the given functions passes when applied to the +subject. + +Passing an empty list is assumed to be a mistake, so `Expect.oneOf []` +will always return a failed expectation no matter what else it is passed. + + Expect.oneOf + [ Expect.greatherThan 8 + , Expect.lessThan 5 + , Expect.lessThan 1 + ] + (List.length [1, 2, 3]) + -- Passes because (3 < 5) is True, although (3 < 8) and (3 > 1) + +-} +oneOf : List (subject -> Expectation) -> subject -> Expectation +oneOf list query = + if List.isEmpty list then + Test.Expectation.fail + { reason = Invalid EmptyList + , description = "Expect.oneOf was given an empty list. You must make at least one expectation to have a valid test!" + } + + else + oneOfHelp list query + + +oneOfHelp : List (subject -> Expectation) -> subject -> Expectation +oneOfHelp list query = + case list of + [] -> + Test.Expectation.fail + { reason = Invalid EmptyList + , description = "Expect.oneOf ran out of expectations." + } + + check :: rest -> + case check query of + Test.Expectation.Pass -> + pass + + outcome -> + oneOfHelp rest query + + {---- Private helper functions ----} diff --git a/tests/src/Tests.elm b/tests/src/Tests.elm index 913ab44d..beb285d5 100644 --- a/tests/src/Tests.elm +++ b/tests/src/Tests.elm @@ -92,6 +92,19 @@ expectationTests = |> Expect.all [] |> expectToFail ] + , describe "Expect.oneOf" + [ test "fails with empty list" <| + \_ -> + "dummy subject" + |> Expect.oneOf [] + |> expectToFail + , test "fails with bad expectations" <| + \_ -> + [1, 2, 3] + |> List.length + |> Expect.oneOf [ Expect.greaterThan 5, Expect.lessThan 0 ] + |> expectToFail + ] , describe "Expect.equal" [ test "fails when equating two floats (see #230)" <| \_ ->