Skip to content

Commit

Permalink
Sum generic To/FromForm tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jkarni committed Aug 22, 2016
1 parent 0e793b1 commit 582977b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
28 changes: 23 additions & 5 deletions test/Web/HttpApiData/Internal/FormUrlEncodedSpec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,33 @@ genericSpec = describe "Default (generic) instances" $ do
M.lookup "rec1" f `shouldBe` Just (rec1 x)
(parseUrlPiece <$> M.lookup "rec2" f) `shouldBe` Just (Right $ rec2 x)

context "for sum types" $ do

it "contains the correct records" $ property $ \x -> do
let f = unForm $ toForm x
case x of
SSRLeft _ _ -> do
parseUrlPiece <$> M.lookup "left1" f `shouldBe` Just (Right $ left1 x)
parseUrlPiece <$> M.lookup "left2" f `shouldBe` Just (Right $ left2 x)
SSRRight _ _ -> do
parseUrlPiece <$> M.lookup "right1" f `shouldBe` Just (Right $ right1 x)
parseUrlPiece <$> M.lookup "right2" f `shouldBe` Just (Right $ right2 x)


context "FromForm" $ do

it "is the left inverse of ToForm" $ property $ \(x :: SimpleRec) -> do
fromForm (toForm x) `shouldBe` Right x
it "is the left inverse of ToForm" $ property $
\(x :: SimpleRec, y :: SimpleSumRec) -> do
fromForm (toForm x) `shouldBe` Right x
fromForm (toForm y) `shouldBe` Right y

it "is the right inverse of ToForm" $ property $ \x (y :: Int) -> do
let f = Form $ M.fromList [("rec1", x), ("rec2", toUrlPiece y)]
Right r = fromForm f :: Either String SimpleRec
toForm r `shouldBe` f
let f1 = Form $ M.fromList [("rec1", x), ("rec2", toUrlPiece y)]
Right r1 = fromForm f1 :: Either String SimpleRec
toForm r1 `shouldBe` f1
let f2 = Form $ M.fromList [("right1", x), ("right2", toUrlPiece y)]
Right r2 = fromForm f2 :: Either String SimpleSumRec
toForm r2 `shouldBe` f2

it "returns the underlying error" $ do
let f = Form $ M.fromList [("rec1", "anything"), ("rec2", "bad")]
Expand Down
15 changes: 15 additions & 0 deletions test/Web/HttpApiData/Internal/TestInstances.hs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
module Web.HttpApiData.Internal.TestInstances
( RandomCase(..)
, SimpleRec(..)
, SimpleSumRec(..)
) where

import Control.Applicative
Expand Down Expand Up @@ -81,3 +82,17 @@ instance FromForm SimpleRec

instance Arbitrary SimpleRec where
arbitrary = SimpleRec <$> arbitrary <*> arbitrary

data SimpleSumRec
= SSRLeft { left1 :: Int, left2 :: Bool }
| SSRRight { right1 :: T.Text, right2 :: Int}
deriving (Eq, Show, Read, Generic)

instance ToForm SimpleSumRec
instance FromForm SimpleSumRec

instance Arbitrary SimpleSumRec where
arbitrary = oneof
[ SSRLeft <$> arbitrary <*> arbitrary
, SSRRight <$> arbitrary <*> arbitrary
]

0 comments on commit 582977b

Please sign in to comment.