@@ -1,12 +1,21 @@
1−{-# LANGUAGE CPP #-}
1+{-# LANGUAGE CPP #-}
2−{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE FunctionalDependencies #-}
5−{-# LANGUAGE GADTs #-}
7+{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+#if !MIN_VERSION_base(4,8,0)
10+{-# LANGUAGE OverlappingInstances #-}
12+{-# LANGUAGE OverloadedStrings #-}
13+{-# LANGUAGE PolyKinds #-}
7−{-# LANGUAGE RecordWildCards #-}
14+{-# LANGUAGE RecordWildCards #-}
8−{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE StandaloneDeriving #-}
16+{-# LANGUAGE ScopedTypeVariables #-}
9−{-# LANGUAGE TypeOperators #-}
17+{-# LANGUAGE TypeOperators #-}
18+{-# LANGUAGE UndecidableInstances #-}
10{-# OPTIONS_GHC -fcontext-stack=100 #-}
19{-# OPTIONS_GHC -fcontext-stack=100 #-}
11{-# OPTIONS_GHC -fno-warn-orphans #-}
20{-# OPTIONS_GHC -fno-warn-orphans #-}
@@ -20,20 +29,20 @@ import Control.Concurrent
20import Control.Exception
29import Control.Exception
21import Control.Monad.Trans.Except
30import Control.Monad.Trans.Except
22import Data.Aeson
31import Data.Aeson
23−import Data.ByteString.Lazy (ByteString)
24import Data.Char
32import Data.Char
25import Data.Foldable (forM_)
33import Data.Foldable (forM_)
26−import Data.Monoid
34+import Data.Monoid hiding (getLast)
27import Data.Proxy
35import Data.Proxy
28import qualified Data.Text as T
36import qualified Data.Text as T
29import GHC.Generics
37import GHC.Generics
30import qualified Network.HTTP.Client as C
39import qualified Network.HTTP.Client as C
31import Network.HTTP.Media
40import Network.HTTP.Media
32import Network.HTTP.Types hiding (Header)
41import Network.HTTP.Types hiding (Header)
33−import qualified Network.HTTP.Types as HTTP
34import Network.Socket
42import Network.Socket
35import Network.Wai hiding (Response)
43import Network.Wai hiding (Response)
36import Network.Wai.Handler.Warp
44import Network.Wai.Handler.Warp
45+import System.IO.Unsafe (unsafePerformIO)
37import Test.Hspec
46import Test.Hspec
38import Test.Hspec.QuickCheck
47import Test.Hspec.QuickCheck
39import Test.HUnit
48import Test.HUnit
@@ -43,6 +52,12 @@ import Servant.API
43import Servant.Client
52import Servant.Client
44import Servant.Server
53import Servant.Server
56+spec = describe "Servant.Client" $ do
46-- * test data types
61-- * test data types
48data Person = Person {
63data Person = Person {
@@ -122,8 +137,6 @@ server = serve api (
122 :<|> return ()
137 :<|> return ()
125−withServer :: (BaseUrl -> IO a) -> IO a
126−withServer action = withWaiDaemon (return server) action
128type FailApi =
141type FailApi =
129 "get" :> Raw
142 "get" :> Raw
@@ -139,93 +152,72 @@ failServer = serve failApi (
139 :<|> (\_request respond -> respond $ responseLBS ok200 [("content-type", "fooooo")] "")
152 :<|> (\_request respond -> respond $ responseLBS ok200 [("content-type", "fooooo")] "")
142−withFailServer :: (BaseUrl -> IO a) -> IO a
155+{-# NOINLINE manager #-}
143−withFailServer action = withWaiDaemon (return failServer) action
156+manager :: C.Manager
146−spec = withServer $ \ baseUrl -> do
147− manager <- C.newManager C.defaultManagerSettings
157+manager = unsafePerformIO $ C.newManager C.defaultManagerSettings
148− let getGet :: ExceptT ServantError IO Person
158+
149− getDeleteEmpty :: ExceptT ServantError IO ()
159+sucessSpec :: Spec
150− getCapture :: String -> ExceptT ServantError IO Person
160+sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
151− getBody :: Person -> ExceptT ServantError IO Person
161+
152− getQueryParam :: Maybe String -> ExceptT ServantError IO Person
153− getQueryParams :: [String] -> ExceptT ServantError IO [Person]
154− getQueryFlag :: Bool -> ExceptT ServantError IO Bool
155− getMatrixParam :: Maybe String -> ExceptT ServantError IO Person
156− getMatrixParams :: [String] -> ExceptT ServantError IO [Person]
157− getMatrixFlag :: Bool -> ExceptT ServantError IO Bool
158− getRawSuccess :: Method -> ExceptT ServantError IO (Int, ByteString, MediaType, [HTTP.Header], C.Response ByteString)
159− getRawFailure :: Method -> ExceptT ServantError IO (Int, ByteString, MediaType, [HTTP.Header], C.Response ByteString)
160− getMultiple :: String -> Maybe Int -> Bool -> [(String, [Rational])] -> ExceptT ServantError IO (String, Maybe Int, Bool, [(String, [Rational])])
161− getRespHeaders :: ExceptT ServantError IO (Headers TestHeaders Bool)
162− getDeleteContentType :: ExceptT ServantError IO ()
171− :<|> getMatrixParams
177− :<|> getDeleteContentType)
178− = client api baseUrl manager
181− it "Servant.API.Get" $ do
162+ it "Servant.API.Get" $ \(_, baseUrl) -> do
163+ let getGet = getNth (Proxy :: Proxy 0) $ client api baseUrl manager
182 (left show <$> runExceptT getGet) `shouldReturn` Right alice
164 (left show <$> runExceptT getGet) `shouldReturn` Right alice
184 describe "Servant.API.Delete" $ do
166 describe "Servant.API.Delete" $ do
185− it "allows empty content type" $ do
167+ it "allows empty content type" $ \(_, baseUrl) -> do
168+ let getDeleteEmpty = getNth (Proxy :: Proxy 1) $ client api baseUrl manager
186 (left show <$> runExceptT getDeleteEmpty) `shouldReturn` Right ()
169 (left show <$> runExceptT getDeleteEmpty) `shouldReturn` Right ()
188− it "allows content type" $ do
171+ it "allows content type" $ \(_, baseUrl) -> do
172+ let getDeleteContentType = getLast $ client api baseUrl manager
189 (left show <$> runExceptT getDeleteContentType) `shouldReturn` Right ()
173 (left show <$> runExceptT getDeleteContentType) `shouldReturn` Right ()
191− it "Servant.API.Capture" $ do
175+ it "Servant.API.Capture" $ \(_, baseUrl) -> do
176+ let getCapture = getNth (Proxy :: Proxy 2) $ client api baseUrl manager
192 (left show <$> runExceptT (getCapture "Paula")) `shouldReturn` Right (Person "Paula" 0)
177 (left show <$> runExceptT (getCapture "Paula")) `shouldReturn` Right (Person "Paula" 0)
194− it "Servant.API.ReqBody" $ do
179+ it "Servant.API.ReqBody" $ \(_, baseUrl) -> do
195 let p = Person "Clara" 42
180 let p = Person "Clara" 42
181+ getBody = getNth (Proxy :: Proxy 3) $ client api baseUrl manager
196 (left show <$> runExceptT (getBody p)) `shouldReturn` Right p
182 (left show <$> runExceptT (getBody p)) `shouldReturn` Right p
198− it "Servant.API.QueryParam" $ do
184+ it "Servant.API.QueryParam" $ \(_, baseUrl) -> do
185+ let getQueryParam = getNth (Proxy :: Proxy 4) $ client api baseUrl manager
199 left show <$> runExceptT (getQueryParam (Just "alice")) `shouldReturn` Right alice
186 left show <$> runExceptT (getQueryParam (Just "alice")) `shouldReturn` Right alice
200 Left FailureResponse{..} <- runExceptT (getQueryParam (Just "bob"))
187 Left FailureResponse{..} <- runExceptT (getQueryParam (Just "bob"))
201 responseStatus `shouldBe` Status 400 "bob not found"
188 responseStatus `shouldBe` Status 400 "bob not found"
203− it "Servant.API.QueryParam.QueryParams" $ do
190+ it "Servant.API.QueryParam.QueryParams" $ \(_, baseUrl) -> do
191+ let getQueryParams = getNth (Proxy :: Proxy 5) $ client api baseUrl manager
204 (left show <$> runExceptT (getQueryParams [])) `shouldReturn` Right []
192 (left show <$> runExceptT (getQueryParams [])) `shouldReturn` Right []
205 (left show <$> runExceptT (getQueryParams ["alice", "bob"]))
193 (left show <$> runExceptT (getQueryParams ["alice", "bob"]))
206 `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
194 `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
208 context "Servant.API.QueryParam.QueryFlag" $
196 context "Servant.API.QueryParam.QueryFlag" $
209− forM_ [False, True] $ \ flag ->
197+ forM_ [False, True] $ \ flag -> it (show flag) $ \(_, baseUrl) -> do
210− it (show flag) $ do
198+ let getQueryFlag = getNth (Proxy :: Proxy 6) $ client api baseUrl manager
211 (left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
199 (left show <$> runExceptT (getQueryFlag flag)) `shouldReturn` Right flag
213− it "Servant.API.MatrixParam" $ do
201+ it "Servant.API.MatrixParam" $ \(_, baseUrl) -> do
202+ let getMatrixParam = getNth (Proxy :: Proxy 7) $ client api baseUrl manager
214 left show <$> runExceptT (getMatrixParam (Just "alice")) `shouldReturn` Right alice
203 left show <$> runExceptT (getMatrixParam (Just "alice")) `shouldReturn` Right alice
215 Left FailureResponse{..} <- runExceptT (getMatrixParam (Just "bob"))
204 Left FailureResponse{..} <- runExceptT (getMatrixParam (Just "bob"))
216 responseStatus `shouldBe` Status 400 "bob not found"
205 responseStatus `shouldBe` Status 400 "bob not found"
218− it "Servant.API.MatrixParam.MatrixParams" $ do
207+ it "Servant.API.MatrixParam.MatrixParams" $ \(_, baseUrl) -> do
208+ let getMatrixParams = getNth (Proxy :: Proxy 8) $ client api baseUrl manager
219 left show <$> runExceptT (getMatrixParams []) `shouldReturn` Right []
209 left show <$> runExceptT (getMatrixParams []) `shouldReturn` Right []
220 left show <$> runExceptT (getMatrixParams ["alice", "bob"])
210 left show <$> runExceptT (getMatrixParams ["alice", "bob"])
221 `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
211 `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
223 context "Servant.API.MatrixParam.MatrixFlag" $
213 context "Servant.API.MatrixParam.MatrixFlag" $
224 forM_ [False, True] $ \ flag ->
214 forM_ [False, True] $ \ flag ->
225− it (show flag) $ do
215+ it (show flag) $ \(_, baseUrl) -> do
216+ let getMatrixFlag = getNth (Proxy :: Proxy 9) $ client api baseUrl manager
226 left show <$> runExceptT (getMatrixFlag flag) `shouldReturn` Right flag
217 left show <$> runExceptT (getMatrixFlag flag) `shouldReturn` Right flag
228− it "Servant.API.Raw on success" $ do
219+ it "Servant.API.Raw on success" $ \(_, baseUrl) -> do
220+ let getRawSuccess = getNth (Proxy :: Proxy 10) $ client api baseUrl manager
229 res <- runExceptT (getRawSuccess methodGet)
221 res <- runExceptT (getRawSuccess methodGet)
230 case res of
222 case res of
231 Left e -> assertFailure $ show e
223 Left e -> assertFailure $ show e
@@ -234,7 +226,8 @@ spec = withServer $ \ baseUrl -> do
234 C.responseBody response `shouldBe` body
226 C.responseBody response `shouldBe` body
235 C.responseStatus response `shouldBe` ok200
227 C.responseStatus response `shouldBe` ok200
237− it "Servant.API.Raw on failure" $ do
229+ it "Servant.API.Raw on failure" $ \(_, baseUrl) -> do
230+ let getRawFailure = getNth (Proxy :: Proxy 11) $ client api baseUrl manager
238 res <- runExceptT (getRawFailure methodGet)
231 res <- runExceptT (getRawFailure methodGet)
239 case res of
232 case res of
240 Left e -> assertFailure $ show e
233 Left e -> assertFailure $ show e
@@ -243,81 +236,75 @@ spec = withServer $ \ baseUrl -> do
243 C.responseBody response `shouldBe` body
236 C.responseBody response `shouldBe` body
244 C.responseStatus response `shouldBe` badRequest400
237 C.responseStatus response `shouldBe` badRequest400
246− it "Returns headers appropriately" $ withServer $ \ _ -> do
239+ it "Returns headers appropriately" $ \(_, baseUrl) -> do
240+ let getRespHeaders = getNth (Proxy :: Proxy 13) $ client api baseUrl manager
247 res <- runExceptT getRespHeaders
241 res <- runExceptT getRespHeaders
248 case res of
242 case res of
249 Left e -> assertFailure $ show e
243 Left e -> assertFailure $ show e
250 Right val -> getHeaders val `shouldBe` [("X-Example1", "1729"), ("X-Example2", "eg2")]
244 Right val -> getHeaders val `shouldBe` [("X-Example1", "1729"), ("X-Example2", "eg2")]
252 modifyMaxSuccess (const 20) $ do
246 modifyMaxSuccess (const 20) $ do
253− it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $
247+ it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $ \(_, baseUrl) ->
248+ let getMultiple = getNth (Proxy :: Proxy 12) $ client api baseUrl manager
254− property $ forAllShrink pathGen shrink $ \(NonEmpty cap) num flag body ->
249+ in property $ forAllShrink pathGen shrink $ \(NonEmpty cap) num flag body ->
255 ioProperty $ do
250 ioProperty $ do
256 result <- left show <$> runExceptT (getMultiple cap num flag body)
251 result <- left show <$> runExceptT (getMultiple cap num flag body)
258 result === Right (cap, num, flag, body)
253 result === Right (cap, num, flag, body)
256+wrappedApiSpec :: Spec
261− context "client correctly handles error status codes" $ do
257+wrappedApiSpec = describe "error status codes" $ do
262− let test :: (WrappedApi, String) -> Spec
263− test (WrappedApi api, desc) =
265− withWaiDaemon (return (serve api (throwE $ ServantErr 500 "error message" "" []))) $
258+ let serveW api = serve api $ throwE $ ServantErr 500 "error message" "" []
266− \ host -> do
259+ context "are correctly handled by the client" $
260+ let test :: (WrappedApi, String) -> Spec
261+ test (WrappedApi api, desc) =
262+ it desc $ bracket (startWaiApp $ serveW api) endWaiApp $ \(_, baseUrl) -> do
267− let getResponse :: ExceptT ServantError IO ()
263+ let getResponse :: ExceptT ServantError IO ()
268− getResponse = client api host manager
264+ getResponse = client api baseUrl manager
269− Left FailureResponse{..} <- runExceptT getResponse
265+ Left FailureResponse{..} <- runExceptT getResponse
270− responseStatus `shouldBe` (Status 500 "error message")
266+ responseStatus `shouldBe` (Status 500 "error message")
271− mapM_ test $
267+ in mapM_ test $
272 (WrappedApi (Proxy :: Proxy (Delete '[JSON] ())), "Delete") :
268 (WrappedApi (Proxy :: Proxy (Delete '[JSON] ())), "Delete") :
273 (WrappedApi (Proxy :: Proxy (Get '[JSON] ())), "Get") :
269 (WrappedApi (Proxy :: Proxy (Get '[JSON] ())), "Get") :
274 (WrappedApi (Proxy :: Proxy (Post '[JSON] ())), "Post") :
270 (WrappedApi (Proxy :: Proxy (Post '[JSON] ())), "Post") :
275 (WrappedApi (Proxy :: Proxy (Put '[JSON] ())), "Put") :
271 (WrappedApi (Proxy :: Proxy (Put '[JSON] ())), "Put") :
278−failSpec :: IO ()
274+failSpec :: Spec
279−failSpec = withFailServer $ \ baseUrl -> do
275+failSpec = beforeAll (startWaiApp failServer) $ afterAll endWaiApp $ do
280− manager <- C.newManager C.defaultManagerSettings
276+
281− let getGet :: ExceptT ServantError IO Person
282− getDeleteEmpty :: ExceptT ServantError IO ()
283− getCapture :: String -> ExceptT ServantError IO Person
284− getBody :: Person -> ExceptT ServantError IO Person
290− = client api baseUrl manager
291− getGetWrongHost :: ExceptT ServantError IO Person
292− (getGetWrongHost :<|> _) = client api (BaseUrl Http "127.0.0.1" 19872 "") manager
295 context "client returns errors appropriately" $ do
277 context "client returns errors appropriately" $ do
296− it "reports FailureResponse" $ do
278+ it "reports FailureResponse" $ \(_, baseUrl) -> do
279+ let (_ :<|> getDeleteEmpty :<|> _) = client api baseUrl manager
297 Left res <- runExceptT getDeleteEmpty
280 Left res <- runExceptT getDeleteEmpty
298 case res of
281 case res of
299 FailureResponse (Status 404 "Not Found") _ _ -> return ()
282 FailureResponse (Status 404 "Not Found") _ _ -> return ()
300 _ -> fail $ "expected 404 response, but got " <> show res
283 _ -> fail $ "expected 404 response, but got " <> show res
302− it "reports DecodeFailure" $ do
285+ it "reports DecodeFailure" $ \(_, baseUrl) -> do
286+ let (_ :<|> _ :<|> getCapture :<|> _) = client api baseUrl manager
303 Left res <- runExceptT (getCapture "foo")
287 Left res <- runExceptT (getCapture "foo")
304 case res of
288 case res of
305 DecodeFailure _ ("application/json") _ -> return ()
289 DecodeFailure _ ("application/json") _ -> return ()
306 _ -> fail $ "expected DecodeFailure, but got " <> show res
290 _ -> fail $ "expected DecodeFailure, but got " <> show res
308− it "reports ConnectionError" $ do
292+ it "reports ConnectionError" $ \_ -> do
293+ let (getGetWrongHost :<|> _) = client api (BaseUrl Http "127.0.0.1" 19872 "") manager
309 Left res <- runExceptT getGetWrongHost
294 Left res <- runExceptT getGetWrongHost
310 case res of
295 case res of
311 ConnectionError _ -> return ()
296 ConnectionError _ -> return ()
312 _ -> fail $ "expected ConnectionError, but got " <> show res
297 _ -> fail $ "expected ConnectionError, but got " <> show res
314− it "reports UnsupportedContentType" $ do
299+ it "reports UnsupportedContentType" $ \(_, baseUrl) -> do
300+ let (getGet :<|> _ ) = client api baseUrl manager
315 Left res <- runExceptT getGet
301 Left res <- runExceptT getGet
316 case res of
302 case res of
317 UnsupportedContentType ("application/octet-stream") _ -> return ()
303 UnsupportedContentType ("application/octet-stream") _ -> return ()
318 _ -> fail $ "expected UnsupportedContentType, but got " <> show res
304 _ -> fail $ "expected UnsupportedContentType, but got " <> show res
320− it "reports InvalidContentTypeHeader" $ do
306+ it "reports InvalidContentTypeHeader" $ \(_, baseUrl) -> do
307+ let (_ :<|> _ :<|> _ :<|> getBody :<|> _) = client api baseUrl manager
321 Left res <- runExceptT (getBody alice)
308 Left res <- runExceptT (getBody alice)
322 case res of
309 case res of
323 InvalidContentTypeHeader "fooooo" _ -> return ()
310 InvalidContentTypeHeader "fooooo" _ -> return ()
@@ -331,36 +318,16 @@ data WrappedApi where
332-- * utils
319-- * utils
334−withWaiDaemon :: IO Application -> (BaseUrl -> IO a) -> IO a
321+startWaiApp :: Application -> IO (ThreadId, BaseUrl)
335−withWaiDaemon mkApplication action = do
322+startWaiApp app = do
336− application <- mkApplication
337− bracket (acquire application) free (\ (_, _, baseUrl) -> action baseUrl)
339− acquire application = do
340− (notifyStart, waitForStart) <- lvar
341− (notifyKilled, waitForKilled) <- lvar
342− thread <- forkIO $ (do
343− (krakenPort, socket) <- openTestSocket
323+ (port, socket) <- openTestSocket
345− setPort krakenPort $ -- set here just for consistency, shouldn't be
346− -- used (it's set in the socket)
347− setBeforeMainLoop (notifyStart krakenPort)
348− defaultSettings
324+ let settings = setPort port $ defaultSettings
349− runSettingsSocket settings socket application)
325+ thread <- forkIO $ runSettingsSocket settings socket app
350− `finally` notifyKilled ()
351− krakenPort <- waitForStart
352− let baseUrl = (BaseUrl Http "localhost" 80 ""){baseUrlPort = krakenPort}
326+ return (thread, BaseUrl Http "localhost" port "")
353− return (thread, waitForKilled, baseUrl)
327+
354− free (thread, waitForKilled, _) = do
328+
329+endWaiApp :: (ThreadId, BaseUrl) -> IO ()
355− killThread thread
330+endWaiApp (thread, _) = killThread thread
358− lvar :: IO (a -> IO (), IO a)
360− mvar <- newEmptyMVar
361− let put = putMVar mvar
362− wait = readMVar mvar
365openTestSocket :: IO (Port, Socket)
332openTestSocket :: IO (Port, Socket)
366openTestSocket = do
333openTestSocket = do
@@ -378,3 +345,37 @@ pathGen = fmap NonEmpty path
378 filter (not . (`elem` ("?%[]/#;" :: String))) $
345 filter (not . (`elem` ("?%[]/#;" :: String))) $
379 filter isPrint $
346 filter isPrint $
380 map chr [0..127]
347 map chr [0..127]
349+class GetNth (n :: Nat) a b | n a -> b where
350+ getNth :: Proxy n -> a -> b
353+#if MIN_VERSION_base(4,8,0)
356+ GetNth 0 (x :<|> y) x where
357+ getNth _ (x :<|> _) = x
360+#if MIN_VERSION_base(4,8,0)
363+ (GetNth (n - 1) x y) => GetNth n (a :<|> x) y where
364+ getNth _ (_ :<|> x) = getNth (Proxy :: Proxy (n - 1)) x
366+class GetLast a b | a -> b where
370+#if MIN_VERSION_base(4,8,0)
373+ (GetLast b c) => GetLast (a :<|> b) c where
374+ getLast (_ :<|> b) = getLast b
377+#if MIN_VERSION_base(4,8,0)