servant/servant-client/test/Servant/ClientSpec.hs

376 lines
14 KiB
Haskell
Raw Normal View History

{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
#if !MIN_VERSION_base(4,8,0)
{-# LANGUAGE OverlappingInstances #-}
#endif
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
2016-01-04 19:04:10 +01:00
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
2015-05-02 03:21:03 +02:00
{-# OPTIONS_GHC -fcontext-stack=100 #-}
2015-10-09 00:02:43 +02:00
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
2016-01-04 19:04:10 +01:00
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Servant.ClientSpec where
#if !MIN_VERSION_base(4,8,0)
2015-11-25 10:31:58 +01:00
import Control.Applicative ((<$>), pure)
#endif
2015-09-12 14:11:24 +02:00
import Control.Arrow (left)
2015-11-25 10:31:58 +01:00
import Control.Monad.Trans.Except (runExceptT, throwE)
2015-04-19 18:31:23 +02:00
import Data.Aeson
2015-10-09 00:02:43 +02:00
import Data.Char (chr, isPrint)
2015-04-19 18:31:23 +02:00
import Data.Foldable (forM_)
import Data.Monoid hiding (getLast)
2015-04-19 18:31:23 +02:00
import Data.Proxy
import qualified Data.Text as T
2015-10-09 00:02:43 +02:00
import GHC.Generics (Generic)
import GHC.TypeLits
2015-04-19 18:31:23 +02:00
import qualified Network.HTTP.Client as C
import Network.HTTP.Media
2015-10-13 21:45:22 +02:00
import Network.HTTP.Types (Status (..), badRequest400,
methodGet, ok200, status400)
2016-01-04 17:59:28 +01:00
import Network.Wai (responseLBS)
import System.IO.Unsafe (unsafePerformIO)
2016-01-04 19:04:10 +01:00
import Test.HUnit
2015-04-19 18:31:23 +02:00
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Servant.API
import Servant.Client
2015-11-25 10:31:58 +01:00
import Servant.Client.TestServer
2015-04-19 18:31:23 +02:00
import Servant.Server
spec :: Spec
2015-11-25 10:31:58 +01:00
spec = do
runIO buildTestServer
describe "Servant.Client" $ do
sucessSpec
failSpec
2015-11-25 10:31:58 +01:00
errorSpec
2016-01-04 21:54:41 +01:00
-- | Run a test-server (identified by name) while performing the given action.
-- The provided 'BaseUrl' points to the running server.
--
-- Running the test-servers is done differently depending on the compiler
-- (ghc or ghcjs).
--
-- With ghc it's somewhat straight-forward: a wai 'Application' is being started
-- on a free port inside the same process using 'warp'.
--
-- When running the test-suite with ghcjs all the test-servers are compiled into
-- a single external executable (with ghc and warp). This is done through
-- 'buildTestServer' once at the start of the test-suite. This built executable
-- will provide all the test-servers on a free port under a path that
-- corresponds to the test-servers name, for example under
-- 'http://localhost:82923/failServer'. 'withTestServer' will then
-- start this executable as an external process while the given action is being
-- executed and provide it with the correct BaseUrl.
-- This rather cumbersome approach is taken because it's not easy to run a wai
-- Application as a http server when using ghcjs.
withTestServer :: String -> (BaseUrl -> IO a) -> IO a
withTestServer = withServer . lookupTestServer
2016-01-04 19:04:10 +01:00
lookupTestServer :: String -> TestServer
lookupTestServer name = case lookup name mapping of
Nothing -> error ("test server not found: " ++ name)
Just testServer -> testServer
where
mapping :: [(String, TestServer)]
mapping = map (\ server -> (testServerName server, server)) allTestServers
2016-01-04 21:54:41 +01:00
-- | All test-servers must be registered here.
allTestServers :: [TestServer]
allTestServers =
server :
errorServer :
failServer :
[]
2016-01-04 19:04:10 +01:00
-- * test data types
data Person = Person {
name :: String,
age :: Integer
}
deriving (Eq, Show, Generic)
instance ToJSON Person
instance FromJSON Person
2015-02-24 23:56:06 +01:00
instance ToFormUrlEncoded Person where
toFormUrlEncoded Person{..} =
[("name", T.pack name), ("age", T.pack (show age))]
lookupEither :: (Show a, Eq a) => a -> [(a,b)] -> Either String b
lookupEither x xs = do
maybe (Left $ "could not find key " <> show x) return $ lookup x xs
instance FromFormUrlEncoded Person where
fromFormUrlEncoded xs = do
n <- lookupEither "name" xs
a <- lookupEither "age" xs
return $ Person (T.unpack n) (read $ T.unpack a)
alice :: Person
alice = Person "Alice" 42
2015-05-02 03:21:03 +02:00
type TestHeaders = '[Header "X-Example1" Int, Header "X-Example2" String]
type Api =
"get" :> Get '[JSON] Person
:<|> "deleteEmpty" :> Delete '[] ()
2015-02-24 23:56:06 +01:00
:<|> "capture" :> Capture "name" String :> Get '[JSON,FormUrlEncoded] Person
:<|> "body" :> ReqBody '[FormUrlEncoded,JSON] Person :> Post '[JSON] Person
:<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
:<|> "params" :> QueryParams "names" String :> Get '[JSON] [Person]
:<|> "flag" :> QueryFlag "flag" :> Get '[JSON] Bool
:<|> "rawSuccess" :> Raw
:<|> "rawFailure" :> Raw
:<|> "multiple" :>
Capture "first" String :>
QueryParam "second" Int :>
QueryFlag "third" :>
ReqBody '[JSON] [(String, [Rational])] :>
2015-11-25 10:31:58 +01:00
Post '[JSON] (String, Maybe Int, Bool, [(String, [Rational])])
2015-05-02 03:21:03 +02:00
:<|> "headers" :> Get '[JSON] (Headers TestHeaders Bool)
:<|> "deleteContentType" :> Delete '[JSON] ()
api :: Proxy Api
api = Proxy
2016-01-04 17:59:28 +01:00
server :: TestServer
server = TestServer "server" $ serve api (
return alice
2015-02-01 23:33:05 +01:00
:<|> return ()
:<|> (\ name -> return $ Person name 0)
:<|> return
:<|> (\ name -> case name of
Just "alice" -> return alice
2015-10-09 00:02:43 +02:00
Just n -> throwE $ ServantErr 400 (n ++ " not found") "" []
2015-09-12 14:11:24 +02:00
Nothing -> throwE $ ServantErr 400 "missing parameter" "" [])
:<|> (\ names -> return (zipWith Person names [0..]))
:<|> return
:<|> (\ _request respond -> respond $ responseLBS ok200 [] "rawSuccess")
:<|> (\ _request respond -> respond $ responseLBS badRequest400 [] "rawFailure")
2015-05-02 03:21:03 +02:00
:<|> (\ a b c d -> return (a, b, c, d))
:<|> (return $ addHeader 1729 $ addHeader "eg2" True)
:<|> return ()
)
2015-03-09 04:38:32 +01:00
type FailApi =
"get" :> Raw
:<|> "capture" :> Capture "name" String :> Raw
:<|> "body" :> Raw
2015-11-25 10:31:58 +01:00
2015-03-09 04:38:32 +01:00
failApi :: Proxy FailApi
failApi = Proxy
2016-01-04 17:59:28 +01:00
failServer :: TestServer
failServer = TestServer "failServer" $ serve failApi (
2015-03-09 04:38:32 +01:00
(\ _request respond -> respond $ responseLBS ok200 [] "")
:<|> (\ _capture _request respond -> respond $ responseLBS ok200 [("content-type", "application/json")] "")
2015-11-25 10:31:58 +01:00
:<|> (\ _request respond -> respond $ responseLBS ok200 [("content-type", "fooooo")] "")
)
2015-03-09 04:38:32 +01:00
{-# NOINLINE manager #-}
manager :: C.Manager
manager = unsafePerformIO $ C.newManager C.defaultManagerSettings
sucessSpec :: Spec
2016-01-04 19:04:10 +01:00
sucessSpec = around (withTestServer "server") $ do
2015-11-25 10:31:58 +01:00
it "Servant.API.Get" $ \baseUrl -> do
let getGet = getNth (Proxy :: Proxy 0) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT getGet) `shouldReturn` Right alice
describe "Servant.API.Delete" $ do
2015-11-25 10:31:58 +01:00
it "allows empty content type" $ \baseUrl -> do
let getDeleteEmpty = getNth (Proxy :: Proxy 1) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT getDeleteEmpty) `shouldReturn` Right ()
2015-11-25 10:31:58 +01:00
it "allows content type" $ \baseUrl -> do
let getDeleteContentType = getLast $ client api baseUrl manager
(left show <$> runExceptT getDeleteContentType) `shouldReturn` Right ()
2015-11-25 10:31:58 +01:00
it "Servant.API.Capture" $ \baseUrl -> do
let getCapture = getNth (Proxy :: Proxy 2) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT (getCapture "Paula")) `shouldReturn` Right (Person "Paula" 0)
2015-11-25 10:31:58 +01:00
it "Servant.API.ReqBody" $ \baseUrl -> do
let p = Person "Clara" 42
getBody = getNth (Proxy :: Proxy 3) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT (getBody p)) `shouldReturn` Right p
2015-11-25 10:31:58 +01:00
it "Servant.API.QueryParam" $ \baseUrl -> do
let getQueryParam = getNth (Proxy :: Proxy 4) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
left show <$> runExceptT (getQueryParam (Just "alice")) `shouldReturn` Right alice
Left FailureResponse{..} <- runExceptT (getQueryParam (Just "bob"))
responseStatus `shouldBe` Status 400 "bob not found"
2015-11-25 10:31:58 +01:00
it "Servant.API.QueryParam.QueryParams" $ \baseUrl -> do
let getQueryParams = getNth (Proxy :: Proxy 5) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT (getQueryParams [])) `shouldReturn` Right []
(left show <$> runExceptT (getQueryParams ["alice", "bob"]))
`shouldReturn` Right [Person "alice" 0, Person "bob" 1]
context "Servant.API.QueryParam.QueryFlag" $
2015-11-25 10:31:58 +01:00
forM_ [False, True] $ \ flag -> it (show flag) $ \baseUrl -> do
let getQueryFlag = getNth (Proxy :: Proxy 6) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
(left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
2015-11-25 10:31:58 +01:00
it "Servant.API.Raw on success" $ \baseUrl -> do
2015-10-13 21:45:22 +02:00
let getRawSuccess = getNth (Proxy :: Proxy 7) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
res <- runExceptT (getRawSuccess methodGet)
2015-03-08 23:59:40 +01:00
case res of
Left e -> assertFailure $ show e
Right (code, body, ct, _, response) -> do
(code, body, ct) `shouldBe` (200, "rawSuccess", "application"//"octet-stream")
C.responseBody response `shouldBe` body
C.responseStatus response `shouldBe` ok200
2015-11-25 10:31:58 +01:00
it "Servant.API.Raw should return a Left in case of failure" $ \baseUrl -> do
2015-10-13 21:45:22 +02:00
let getRawFailure = getNth (Proxy :: Proxy 8) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
res <- runExceptT (getRawFailure methodGet)
2015-03-09 04:38:32 +01:00
case res of
Right _ -> assertFailure "expected Left, but got Right"
Left e -> do
Servant.Client.responseStatus e `shouldBe` status400
Servant.Client.responseBody e `shouldBe` "rawFailure"
2015-11-25 10:31:58 +01:00
it "Returns headers appropriately" $ \baseUrl -> do
2015-10-13 21:45:22 +02:00
let getRespHeaders = getNth (Proxy :: Proxy 10) $ client api baseUrl manager
2015-09-12 14:11:24 +02:00
res <- runExceptT getRespHeaders
2015-03-08 23:59:40 +01:00
case res of
Left e -> assertFailure $ show e
Right val -> getHeaders val `shouldBe` [("X-Example1", "1729"), ("X-Example2", "eg2")]
2015-11-25 10:31:58 +01:00
modifyMaxSuccess (const 2) $ do
it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $ \baseUrl ->
2015-10-13 21:45:22 +02:00
let getMultiple = getNth (Proxy :: Proxy 9) $ client api baseUrl manager
in property $ forAllShrink pathGen shrink $ \(NonEmpty cap) num flag body ->
ioProperty $ do
2015-09-12 14:11:24 +02:00
result <- left show <$> runExceptT (getMultiple cap num flag body)
return $
result === Right (cap, num, flag, body)
2015-03-09 04:38:32 +01:00
2015-11-25 10:31:58 +01:00
type ErrorApi =
Delete '[JSON] () :<|>
Get '[JSON] () :<|>
Post '[JSON] () :<|>
Put '[JSON] ()
errorApi :: Proxy ErrorApi
errorApi = Proxy
2016-01-04 17:59:28 +01:00
errorServer :: TestServer
errorServer = TestServer "errorServer" $ serve errorApi $
2015-11-25 10:31:58 +01:00
err :<|> err :<|> err :<|> err
where
err = throwE $ ServantErr 500 "error message" "" []
errorSpec :: Spec
errorSpec =
2016-01-04 19:04:10 +01:00
around (withTestServer "errorServer") $ do
2015-11-25 10:31:58 +01:00
describe "error status codes" $
it "reports error statuses correctly" $ \baseUrl -> do
let delete :<|> get :<|> post :<|> put =
client errorApi baseUrl manager
actions = [delete, get, post, put]
forM_ actions $ \ clientAction -> do
Left FailureResponse{..} <- runExceptT clientAction
responseStatus `shouldBe` Status 500 "error message"
failSpec :: Spec
2016-01-04 19:04:10 +01:00
failSpec = around (withTestServer "failServer") $ do
context "client returns errors appropriately" $ do
2015-11-25 10:31:58 +01:00
it "reports FailureResponse" $ \baseUrl -> do
let (_ :<|> getDeleteEmpty :<|> _) = client api baseUrl manager
2015-09-12 14:11:24 +02:00
Left res <- runExceptT getDeleteEmpty
case res of
FailureResponse (Status 404 "Not Found") _ _ -> return ()
_ -> fail $ "expected 404 response, but got " <> show res
2015-11-25 10:31:58 +01:00
it "reports DecodeFailure" $ \baseUrl -> do
let (_ :<|> _ :<|> getCapture :<|> _) = client api baseUrl manager
2015-09-12 14:11:24 +02:00
Left res <- runExceptT (getCapture "foo")
case res of
DecodeFailure _ ("application/json") _ -> return ()
_ -> fail $ "expected DecodeFailure, but got " <> show res
it "reports ConnectionError" $ \_ -> do
let (getGetWrongHost :<|> _) = client api (BaseUrl Http "127.0.0.1" 19872 "") manager
2015-09-12 14:11:24 +02:00
Left res <- runExceptT getGetWrongHost
case res of
2015-05-25 09:51:35 +02:00
ConnectionError _ -> return ()
_ -> fail $ "expected ConnectionError, but got " <> show res
2015-11-25 10:31:58 +01:00
it "reports UnsupportedContentType" $ \baseUrl -> do
let (getGet :<|> _ ) = client api baseUrl manager
2015-09-12 14:11:24 +02:00
Left res <- runExceptT getGet
case res of
UnsupportedContentType ("application/octet-stream") _ -> return ()
_ -> fail $ "expected UnsupportedContentType, but got " <> show res
2015-11-25 10:31:58 +01:00
it "reports InvalidContentTypeHeader" $ \baseUrl -> do
let (_ :<|> _ :<|> _ :<|> getBody :<|> _) = client api baseUrl manager
2015-09-12 14:11:24 +02:00
Left res <- runExceptT (getBody alice)
case res of
InvalidContentTypeHeader "fooooo" _ -> return ()
_ -> fail $ "expected InvalidContentTypeHeader, but got " <> show res
2015-03-08 23:59:40 +01:00
-- * utils
2015-02-02 03:35:10 +01:00
pathGen :: Gen (NonEmptyList Char)
pathGen = fmap NonEmpty path
where
path = listOf1 $ elements $
2015-04-20 19:52:29 +02:00
filter (not . (`elem` ("?%[]/#;" :: String))) $
2015-02-02 03:35:10 +01:00
filter isPrint $
map chr [0..127]
class GetNth (n :: Nat) a b | n a -> b where
getNth :: Proxy n -> a -> b
instance
#if MIN_VERSION_base(4,8,0)
{-# OVERLAPPING #-}
#endif
GetNth 0 (x :<|> y) x where
getNth _ (x :<|> _) = x
instance
#if MIN_VERSION_base(4,8,0)
{-# OVERLAPPING #-}
#endif
(GetNth (n - 1) x y) => GetNth n (a :<|> x) y where
getNth _ (_ :<|> x) = getNth (Proxy :: Proxy (n - 1)) x
class GetLast a b | a -> b where
getLast :: a -> b
instance
#if MIN_VERSION_base(4,8,0)
{-# OVERLAPPING #-}
#endif
(GetLast b c) => GetLast (a :<|> b) c where
getLast (_ :<|> b) = getLast b
instance
#if MIN_VERSION_base(4,8,0)
{-# OVERLAPPING #-}
#endif
GetLast a a where
getLast a = a