module Test.Hspec.Attoparsec
(
shouldParse
,
parseSatisfies
,
shouldSucceedOn
, shouldFailOn
,
leavesUnconsumed
,
Source(..)
,
Leftover(..)
) where
import Control.Monad (when)
import Test.Hspec.Attoparsec.Source
import Test.Hspec.Expectations
shouldParse :: (Eq a, Show a) => Either String a -> a -> Expectation
res `shouldParse` expectedVal =
either (expectationFailure . errmsg)
checkEquality
res
where errmsg err = " expected: " ++ show expectedVal
++ "\n but parsing failed with error: " ++ err
checkEquality parsedVal =
when (parsedVal /= expectedVal) $
expectationFailure $ " expected: " ++ show expectedVal
++ "\n but got: " ++ show parsedVal
parseSatisfies :: Show a => Either String a -> (a -> Bool) -> Expectation
parseSatisfies res predicate =
either (expectationFailure . errmsg)
checkPred
res
where errmsg err = " expected a parsed value to check against the predicate"
++ "\n but parsing failed with error: " ++ err
checkPred value =
when (not $ predicate value) $
expectationFailure $
" the following value did not match the predicate: \n"
++ " " ++ show value
shouldFailOn :: (Source p s s' r, Show a)
=> p s' a
-> s
-> Expectation
parser `shouldFailOn` string =
(string ~> parser) `shouldSatisfy` isLeft
shouldSucceedOn :: (Source p s s' r, Show a)
=> p s' a
-> s
-> Expectation
parser `shouldSucceedOn` string =
(string ~> parser) `shouldSatisfy` isRight
isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _ = False
isRight :: Either a b -> Bool
isRight (Right _) = True
isRight _ = False
leavesUnconsumed :: (Source p s s' r, Leftover r s)
=> r a
-> s
-> Expectation
leavesUnconsumed res str
| unconsumed == Nothing && str /= "" =
expectationFailure $
" expected the parser to leave the following unconsumed: " ++ show str
++ "\n but got no leftover"
| otherwise =
case unconsumed of
Just str' ->
when (str /= str') $
expectationFailure $
" expected the parser to leave the following unconsumed: " ++ show str
++ "\n but got: " ++ show str'
Nothing -> expectationFailure $
" expected the parser to leave the following unconsumed: " ++ show str
++ "\n but got no unconsumed input"
where unconsumed = leftover res