@@ -0,0 +1,571 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE DataKinds #-}
4+{-# LANGUAGE DeriveGeneric #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE FunctionalDependencies #-}
8+{-# LANGUAGE GADTs #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE OverloadedStrings #-}
11+{-# LANGUAGE PolyKinds #-}
12+{-# LANGUAGE RecordWildCards #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TypeApplications #-}
16+{-# LANGUAGE TypeFamilies #-}
17+{-# LANGUAGE TypeOperators #-}
18+{-# LANGUAGE UndecidableInstances #-}
19+{-# OPTIONS_GHC -freduction-depth=100 #-}
20+{-# OPTIONS_GHC -fno-warn-orphans #-}
21+{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
22+
23+module Servant.ClientSpec (spec, Person(..), startWaiApp, endWaiApp) where
24+
25+import Prelude ()
26+import Prelude.Compat
27+
28+import Control.Arrow
29+ (left)
30+import Control.Concurrent
31+ (ThreadId, forkIO, killThread)
32+import Control.DeepSeq
33+ (NFData (..))
34+import Control.Exception
35+ (bracket, fromException, IOException)
36+import Control.Monad.Error.Class
37+ (throwError)
38+import Data.Aeson
39+import Data.Char
40+ (chr, isPrint)
41+import Data.Foldable
42+ (forM_, toList)
43+import Data.Maybe
44+ (isJust)
45+import Data.Monoid ()
46+import Data.Proxy
47+import Data.Semigroup
48+ ((<>))
49+import qualified Generics.SOP as SOP
50+import GHC.Generics
51+ (Generic)
52+import qualified Network.HTTP.Types as HTTP
53+import Network.Socket
54+import qualified Network.Wai as Wai
55+import Network.Wai.Handler.Warp
56+import Test.Hspec
57+import Test.Hspec.QuickCheck
58+import Test.HUnit
59+import Test.QuickCheck
60+import Web.FormUrlEncoded
61+ (FromForm, ToForm)
62+
63+import Servant.API
64+ ((:<|>) ((:<|>)), (:>), AuthProtect, BasicAuth,
65+ BasicAuthData (..), Capture, CaptureAll, Delete,
66+ DeleteNoContent, EmptyAPI, FormUrlEncoded, Get, Header,
67+ Headers, JSON, NoContent (NoContent), Post, Put, QueryFlag,
68+ QueryParam, QueryParams, Raw, ReqBody, addHeader, getHeaders)
69+import qualified Servant.Client.Core.Internal.Auth as Auth
70+import qualified Servant.Client.Core.Internal.Request as Req
71+import Servant.HttpStreams
72+import Servant.Server
73+import Servant.Server.Experimental.Auth
74+import Servant.Test.ComprehensiveAPI
75+
76+-- This declaration simply checks that all instances are in place.
77+_ = client comprehensiveAPIWithoutStreaming
78+
79+spec :: Spec
80+spec = describe "Servant.HttpStreams" $ do
81+ sucessSpec
82+ failSpec
83+ wrappedApiSpec
84+ basicAuthSpec
85+ genAuthSpec
86+ genericClientSpec
87+ hoistClientSpec
88+ connectionErrorSpec
89+
90+-- * test data types
91+
92+data Person = Person
93+ { _name :: String
94+ , _age :: Integer
95+ } deriving (Eq, Show, Generic)
96+
97+instance NFData Person where
98+ rnf (Person n a) = rnf n `seq` rnf a
99+
100+instance ToJSON Person
101+instance FromJSON Person
102+
103+instance ToForm Person
104+instance FromForm Person
105+
106+instance Arbitrary Person where
107+ arbitrary = Person <$> arbitrary <*> arbitrary
108+
109+alice :: Person
110+alice = Person "Alice" 42
111+
112+carol :: Person
113+carol = Person "Carol" 17
114+
115+type TestHeaders = '[Header "X-Example1" Int, Header "X-Example2" String]
116+
117+type Api =
118+ Get '[JSON] Person
119+ :<|> "get" :> Get '[JSON] Person
120+ :<|> "deleteEmpty" :> DeleteNoContent '[JSON] NoContent
121+ :<|> "capture" :> Capture "name" String :> Get '[JSON,FormUrlEncoded] Person
122+ :<|> "captureAll" :> CaptureAll "names" String :> Get '[JSON] [Person]
123+ :<|> "body" :> ReqBody '[FormUrlEncoded,JSON] Person :> Post '[JSON] Person
124+ :<|> "param" :> QueryParam "name" String :> Get '[FormUrlEncoded,JSON] Person
125+ :<|> "params" :> QueryParams "names" String :> Get '[JSON] [Person]
126+ :<|> "flag" :> QueryFlag "flag" :> Get '[JSON] Bool
127+ :<|> "rawSuccess" :> Raw
128+ :<|> "rawFailure" :> Raw
129+ :<|> "multiple" :>
130+ Capture "first" String :>
131+ QueryParam "second" Int :>
132+ QueryFlag "third" :>
133+ ReqBody '[JSON] [(String, [Rational])] :>
134+ Get '[JSON] (String, Maybe Int, Bool, [(String, [Rational])])
135+ :<|> "headers" :> Get '[JSON] (Headers TestHeaders Bool)
136+ :<|> "deleteContentType" :> DeleteNoContent '[JSON] NoContent
137+ :<|> "redirectWithCookie" :> Raw
138+ :<|> "empty" :> EmptyAPI
139+
140+api :: Proxy Api
141+api = Proxy
142+
143+getRoot :: ClientM Person
144+getGet :: ClientM Person
145+getDeleteEmpty :: ClientM NoContent
146+getCapture :: String -> ClientM Person
147+getCaptureAll :: [String] -> ClientM [Person]
148+getBody :: Person -> ClientM Person
149+getQueryParam :: Maybe String -> ClientM Person
150+getQueryParams :: [String] -> ClientM [Person]
151+getQueryFlag :: Bool -> ClientM Bool
152+getRawSuccess :: HTTP.Method -> ClientM Response
153+getRawFailure :: HTTP.Method -> ClientM Response
154+getMultiple :: String -> Maybe Int -> Bool -> [(String, [Rational])]
155+ -> ClientM (String, Maybe Int, Bool, [(String, [Rational])])
156+getRespHeaders :: ClientM (Headers TestHeaders Bool)
157+getDeleteContentType :: ClientM NoContent
158+_getRedirectWithCookie :: HTTP.Method -> ClientM Response
159+
160+getRoot
161+ :<|> getGet
162+ :<|> getDeleteEmpty
163+ :<|> getCapture
164+ :<|> getCaptureAll
165+ :<|> getBody
166+ :<|> getQueryParam
167+ :<|> getQueryParams
168+ :<|> getQueryFlag
169+ :<|> getRawSuccess
170+ :<|> getRawFailure
171+ :<|> getMultiple
172+ :<|> getRespHeaders
173+ :<|> getDeleteContentType
174+ :<|> _getRedirectWithCookie
175+ :<|> EmptyClient = client api
176+
177+server :: Application
178+server = serve api (
179+ return carol
180+ :<|> return alice
181+ :<|> return NoContent
182+ :<|> (\ name -> return $ Person name 0)
183+ :<|> (\ names -> return (zipWith Person names [0..]))
184+ :<|> return
185+ :<|> (\ name -> case name of
186+ Just "alice" -> return alice
187+ Just n -> throwError $ ServantErr 400 (n ++ " not found") "" []
188+ Nothing -> throwError $ ServantErr 400 "missing parameter" "" [])
189+ :<|> (\ names -> return (zipWith Person names [0..]))
190+ :<|> return
191+ :<|> (Tagged $ \ _request respond -> respond $ Wai.responseLBS HTTP.ok200 [] "rawSuccess")
192+ :<|> (Tagged $ \ _request respond -> respond $ Wai.responseLBS HTTP.badRequest400 [] "rawFailure")
193+ :<|> (\ a b c d -> return (a, b, c, d))
194+ :<|> (return $ addHeader 1729 $ addHeader "eg2" True)
195+ :<|> return NoContent
196+ :<|> (Tagged $ \ _request respond -> respond $ Wai.responseLBS HTTP.found302 [("Location", "testlocation"), ("Set-Cookie", "testcookie=test")] "")
197+ :<|> emptyServer)
198+
199+type FailApi =
200+ "get" :> Raw
201+ :<|> "capture" :> Capture "name" String :> Raw
202+ :<|> "body" :> Raw
203+failApi :: Proxy FailApi
204+failApi = Proxy
205+
206+failServer :: Application
207+failServer = serve failApi (
208+ (Tagged $ \ _request respond -> respond $ Wai.responseLBS HTTP.ok200 [] "")
209+ :<|> (\ _capture -> Tagged $ \_request respond -> respond $ Wai.responseLBS HTTP.ok200 [("content-type", "application/json")] "")
210+ :<|> (Tagged $ \_request respond -> respond $ Wai.responseLBS HTTP.ok200 [("content-type", "fooooo")] "")
211+ )
212+
213+-- * basic auth stuff
214+
215+type BasicAuthAPI =
216+ BasicAuth "foo-realm" () :> "private" :> "basic" :> Get '[JSON] Person
217+
218+basicAuthAPI :: Proxy BasicAuthAPI
219+basicAuthAPI = Proxy
220+
221+basicAuthHandler :: BasicAuthCheck ()
222+basicAuthHandler =
223+ let check (BasicAuthData username password) =
224+ if username == "servant" && password == "server"
225+ then return (Authorized ())
226+ else return Unauthorized
227+ in BasicAuthCheck check
228+
229+basicServerContext :: Context '[ BasicAuthCheck () ]
230+basicServerContext = basicAuthHandler :. EmptyContext
231+
232+basicAuthServer :: Application
233+basicAuthServer = serveWithContext basicAuthAPI basicServerContext (const (return alice))
234+
235+-- * general auth stuff
236+
237+type GenAuthAPI =
238+ AuthProtect "auth-tag" :> "private" :> "auth" :> Get '[JSON] Person
239+
240+genAuthAPI :: Proxy GenAuthAPI
241+genAuthAPI = Proxy
242+
243+type instance AuthServerData (AuthProtect "auth-tag") = ()
244+type instance Auth.AuthClientData (AuthProtect "auth-tag") = ()
245+
246+genAuthHandler :: AuthHandler Wai.Request ()
247+genAuthHandler =
248+ let handler req = case lookup "AuthHeader" (Wai.requestHeaders req) of
249+ Nothing -> throwError (err401 { errBody = "Missing auth header" })
250+ Just _ -> return ()
251+ in mkAuthHandler handler
252+
253+genAuthServerContext :: Context '[ AuthHandler Wai.Request () ]
254+genAuthServerContext = genAuthHandler :. EmptyContext
255+
256+genAuthServer :: Application
257+genAuthServer = serveWithContext genAuthAPI genAuthServerContext (const (return alice))
258+
259+-- * generic client stuff
260+
261+type GenericClientAPI
262+ = QueryParam "sqr" Int :> Get '[JSON] Int
263+ :<|> Capture "foo" String :> NestedAPI1
264+
265+data GenericClient = GenericClient
266+ { getSqr :: Maybe Int -> ClientM Int
267+ , mkNestedClient1 :: String -> NestedClient1
268+ } deriving Generic
269+instance SOP.Generic GenericClient
270+instance (Client ClientM GenericClientAPI ~ client) => ClientLike client GenericClient
271+
272+type NestedAPI1
273+ = QueryParam "int" Int :> NestedAPI2
274+ :<|> QueryParam "id" Char :> Get '[JSON] Char
275+
276+data NestedClient1 = NestedClient1
277+ { mkNestedClient2 :: Maybe Int -> NestedClient2
278+ , idChar :: Maybe Char -> ClientM Char
279+ } deriving Generic
280+instance SOP.Generic NestedClient1
281+instance (Client ClientM NestedAPI1 ~ client) => ClientLike client NestedClient1
282+
283+type NestedAPI2
284+ = "sum" :> Capture "first" Int :> Capture "second" Int :> Get '[JSON] Int
285+ :<|> "void" :> Post '[JSON] ()
286+
287+data NestedClient2 = NestedClient2
288+ { getSum :: Int -> Int -> ClientM Int
289+ , doNothing :: ClientM ()
290+ } deriving Generic
291+instance SOP.Generic NestedClient2
292+instance (Client ClientM NestedAPI2 ~ client) => ClientLike client NestedClient2
293+
294+genericClientServer :: Application
295+genericClientServer = serve (Proxy :: Proxy GenericClientAPI) (
296+ (\ mx -> case mx of
297+ Just x -> return (x*x)
298+ Nothing -> throwError $ ServantErr 400 "missing parameter" "" []
299+ )
300+ :<|> nestedServer1
301+ )
302+ where
303+ nestedServer1 _str = nestedServer2 :<|> (maybe (throwError $ ServantErr 400 "missing parameter" "" []) return)
304+ nestedServer2 _int = (\ x y -> return (x + y)) :<|> return ()
305+
306+runClient :: NFData a => ClientM a -> BaseUrl -> IO (Either ServantError a)
307+runClient x burl = withClientEnvIO burl (runClientM x)
308+
309+runClientUnsafe :: ClientM a -> BaseUrl -> IO (Either ServantError a)
310+runClientUnsafe x burl = withClientEnvIO burl (runClientMUnsafe x)
311+ where
312+ runClientMUnsafe x env = withClientM x env return
313+
314+sucessSpec :: Spec
315+sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
316+ it "Servant.API.Get root" $ \(_, baseUrl) -> do
317+ left show <$> runClient getRoot baseUrl `shouldReturn` Right carol
318+
319+ it "Servant.API.Get" $ \(_, baseUrl) -> do
320+ left show <$> runClient getGet baseUrl `shouldReturn` Right alice
321+
322+ describe "Servant.API.Delete" $ do
323+ it "allows empty content type" $ \(_, baseUrl) -> do
324+ left show <$> runClient getDeleteEmpty baseUrl `shouldReturn` Right NoContent
325+
326+ it "allows content type" $ \(_, baseUrl) -> do
327+ left show <$> runClient getDeleteContentType baseUrl `shouldReturn` Right NoContent
328+
329+ it "Servant.API.Capture" $ \(_, baseUrl) -> do
330+ left show <$> runClient (getCapture "Paula") baseUrl `shouldReturn` Right (Person "Paula" 0)
331+
332+ it "Servant.API.CaptureAll" $ \(_, baseUrl) -> do
333+ let expected = [(Person "Paula" 0), (Person "Peta" 1)]
334+ left show <$> runClient (getCaptureAll ["Paula", "Peta"]) baseUrl `shouldReturn` Right expected
335+
336+ it "Servant.API.ReqBody" $ \(_, baseUrl) -> do
337+ let p = Person "Clara" 42
338+ left show <$> runClient (getBody p) baseUrl `shouldReturn` Right p
339+
340+ it "Servant.API FailureResponse" $ \(_, baseUrl) -> do
341+ left show <$> runClient (getQueryParam (Just "alice")) baseUrl `shouldReturn` Right alice
342+ Left (FailureResponse req _) <- runClient (getQueryParam (Just "bob")) baseUrl
343+ Req.requestPath req `shouldBe` (baseUrl, "/param")
344+ toList (Req.requestQueryString req) `shouldBe` [("name", Just "bob")]
345+ Req.requestMethod req `shouldBe` HTTP.methodGet
346+
347+ it "Servant.API.QueryParam" $ \(_, baseUrl) -> do
348+ left show <$> runClient (getQueryParam (Just "alice")) baseUrl `shouldReturn` Right alice
349+ Left (FailureResponse _ r) <- runClient (getQueryParam (Just "bob")) baseUrl
350+ responseStatusCode r `shouldBe` HTTP.Status 400 "bob not found"
351+
352+ it "Servant.API.QueryParam.QueryParams" $ \(_, baseUrl) -> do
353+ left show <$> runClient (getQueryParams []) baseUrl `shouldReturn` Right []
354+ left show <$> runClient (getQueryParams ["alice", "bob"]) baseUrl
355+ `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
356+
357+ context "Servant.API.QueryParam.QueryFlag" $
358+ forM_ [False, True] $ \ flag -> it (show flag) $ \(_, baseUrl) -> do
359+ left show <$> runClient (getQueryFlag flag) baseUrl `shouldReturn` Right flag
360+
361+ it "Servant.API.Raw on success" $ \(_, baseUrl) -> do
362+ res <- runClient (getRawSuccess HTTP.methodGet) baseUrl
363+ case res of
364+ Left e -> assertFailure $ show e
365+ Right r -> do
366+ responseStatusCode r `shouldBe` HTTP.status200
367+ responseBody r `shouldBe` "rawSuccess"
368+
369+ it "Servant.API.Raw should return a Left in case of failure" $ \(_, baseUrl) -> do
370+ res <- runClient (getRawFailure HTTP.methodGet) baseUrl
371+ case res of
372+ Right _ -> assertFailure "expected Left, but got Right"
373+ Left (FailureResponse _ r) -> do
374+ responseStatusCode r `shouldBe` HTTP.status400
375+ responseBody r `shouldBe` "rawFailure"
376+ Left e -> assertFailure $ "expected FailureResponse, but got " ++ show e
377+
378+ it "Returns headers appropriately" $ \(_, baseUrl) -> do
379+ res <- runClient getRespHeaders baseUrl
380+ case res of
381+ Left e -> assertFailure $ show e
382+ Right val -> getHeaders val `shouldBe` [("X-Example1", "1729"), ("X-Example2", "eg2")]
383+
384+ modifyMaxSuccess (const 20) $ do
385+ it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $ \(_, baseUrl) ->
386+ property $ forAllShrink pathGen shrink $ \(NonEmpty cap) num flag body ->
387+ ioProperty $ do
388+ result <- left show <$> runClient (getMultiple cap num flag body) baseUrl
389+ return $
390+ result === Right (cap, num, flag, body)
391+
392+
393+wrappedApiSpec :: Spec
394+wrappedApiSpec = describe "error status codes" $ do
395+ let serveW api = serve api $ throwError $ ServantErr 500 "error message" "" []
396+ context "are correctly handled by the client" $
397+ let test :: (WrappedApi, String) -> Spec
398+ test (WrappedApi api, desc) =
399+ it desc $ bracket (startWaiApp $ serveW api) endWaiApp $ \(_, baseUrl) -> do
400+ let getResponse :: ClientM ()
401+ getResponse = client api
402+ Left (FailureResponse _ r) <- runClient getResponse baseUrl
403+ responseStatusCode r `shouldBe` (HTTP.Status 500 "error message")
404+ in mapM_ test $
405+ (WrappedApi (Proxy :: Proxy (Delete '[JSON] ())), "Delete") :
406+ (WrappedApi (Proxy :: Proxy (Get '[JSON] ())), "Get") :
407+ (WrappedApi (Proxy :: Proxy (Post '[JSON] ())), "Post") :
408+ (WrappedApi (Proxy :: Proxy (Put '[JSON] ())), "Put") :
409+ []
410+
411+failSpec :: Spec
412+failSpec = beforeAll (startWaiApp failServer) $ afterAll endWaiApp $ do
413+
414+ context "client returns errors appropriately" $ do
415+ it "reports FailureResponse" $ \(_, baseUrl) -> do
416+ let (_ :<|> _ :<|> getDeleteEmpty :<|> _) = client api
417+ Left res <- runClient getDeleteEmpty baseUrl
418+ case res of
419+ FailureResponse _ r | responseStatusCode r == HTTP.status404 -> return ()
420+ _ -> fail $ "expected 404 response, but got " <> show res
421+
422+ it "reports DecodeFailure" $ \(_, baseUrl) -> do
423+ let (_ :<|> _ :<|> _ :<|> getCapture :<|> _) = client api
424+ Left res <- runClient (getCapture "foo") baseUrl
425+ case res of
426+ DecodeFailure _ _ -> return ()
427+ _ -> fail $ "expected DecodeFailure, but got " <> show res
428+
429+ -- we don't catch IOException's
430+ xit "reports ConnectionError" $ \_ -> do
431+ let (getGetWrongHost :<|> _) = client api
432+ Left res <- runClient getGetWrongHost (BaseUrl Http "127.0.0.1" 19872 "")
433+ case res of
434+ ConnectionError _ -> return ()
435+ _ -> fail $ "expected ConnectionError, but got " <> show res
436+
437+ it "reports UnsupportedContentType" $ \(_, baseUrl) -> do
438+ let (_ :<|> getGet :<|> _ ) = client api
439+ Left res <- runClient getGet baseUrl
440+ case res of
441+ UnsupportedContentType ("application/octet-stream") _ -> return ()
442+ _ -> fail $ "expected UnsupportedContentType, but got " <> show res
443+
444+ it "reports InvalidContentTypeHeader" $ \(_, baseUrl) -> do
445+ let (_ :<|> _ :<|> _ :<|> _ :<|> _ :<|> getBody :<|> _) = client api
446+ Left res <- runClient (getBody alice) baseUrl
447+ case res of
448+ InvalidContentTypeHeader _ -> return ()
449+ _ -> fail $ "expected InvalidContentTypeHeader, but got " <> show res
450+
451+data WrappedApi where
452+ WrappedApi :: (HasServer (api :: *) '[], Server api ~ Handler a,
453+ HasClient ClientM api, Client ClientM api ~ ClientM ()) =>
454+ Proxy api -> WrappedApi
455+
456+basicAuthSpec :: Spec
457+basicAuthSpec = beforeAll (startWaiApp basicAuthServer) $ afterAll endWaiApp $ do
458+ context "Authentication works when requests are properly authenticated" $ do
459+
460+ it "Authenticates a BasicAuth protected server appropriately" $ \(_,baseUrl) -> do
461+ let getBasic = client basicAuthAPI
462+ let basicAuthData = BasicAuthData "servant" "server"
463+ left show <$> runClient (getBasic basicAuthData) baseUrl `shouldReturn` Right alice
464+
465+ context "Authentication is rejected when requests are not authenticated properly" $ do
466+
467+ it "Authenticates a BasicAuth protected server appropriately" $ \(_,baseUrl) -> do
468+ let getBasic = client basicAuthAPI
469+ let basicAuthData = BasicAuthData "not" "password"
470+ Left (FailureResponse _ r) <- runClient (getBasic basicAuthData) baseUrl
471+ responseStatusCode r `shouldBe` HTTP.Status 403 "Forbidden"
472+
473+genAuthSpec :: Spec
474+genAuthSpec = beforeAll (startWaiApp genAuthServer) $ afterAll endWaiApp $ do
475+ context "Authentication works when requests are properly authenticated" $ do
476+
477+ it "Authenticates a AuthProtect protected server appropriately" $ \(_, baseUrl) -> do
478+ let getProtected = client genAuthAPI
479+ let authRequest = Auth.mkAuthenticatedRequest () (\_ req -> Req.addHeader "AuthHeader" ("cool" :: String) req)
480+ left show <$> runClient (getProtected authRequest) baseUrl `shouldReturn` Right alice
481+
482+ context "Authentication is rejected when requests are not authenticated properly" $ do
483+
484+ it "Authenticates a AuthProtect protected server appropriately" $ \(_, baseUrl) -> do
485+ let getProtected = client genAuthAPI
486+ let authRequest = Auth.mkAuthenticatedRequest () (\_ req -> Req.addHeader "Wrong" ("header" :: String) req)
487+ Left (FailureResponse _ r) <- runClient (getProtected authRequest) baseUrl
488+ responseStatusCode r `shouldBe` (HTTP.Status 401 "Unauthorized")
489+
490+genericClientSpec :: Spec
491+genericClientSpec = beforeAll (startWaiApp genericClientServer) $ afterAll endWaiApp $ do
492+ describe "Servant.Client.Generic" $ do
493+
494+ let GenericClient{..} = mkClient (client (Proxy :: Proxy GenericClientAPI))
495+ NestedClient1{..} = mkNestedClient1 "example"
496+ NestedClient2{..} = mkNestedClient2 (Just 42)
497+
498+ it "works for top-level client inClientM function" $ \(_, baseUrl) -> do
499+ left show <$> runClient (getSqr (Just 5)) baseUrl `shouldReturn` Right 25
500+
501+ it "works for nested clients" $ \(_, baseUrl) -> do
502+ left show <$> runClient (idChar (Just 'c')) baseUrl `shouldReturn` Right 'c'
503+ left show <$> runClient (getSum 3 4) baseUrl `shouldReturn` Right 7
504+ left show <$> runClient doNothing baseUrl `shouldReturn` Right ()
505+
506+-- * hoistClient
507+
508+type HoistClientAPI = Get '[JSON] Int :<|> Capture "n" Int :> Post '[JSON] Int
509+
510+hoistClientAPI :: Proxy HoistClientAPI
511+hoistClientAPI = Proxy
512+
513+hoistClientServer :: Application -- implements HoistClientAPI
514+hoistClientServer = serve hoistClientAPI $ return 5 :<|> (\n -> return n)
515+
516+hoistClientSpec :: Spec
517+hoistClientSpec = beforeAll (startWaiApp hoistClientServer) $ afterAll endWaiApp $ do
518+ describe "Servant.Client.hoistClient" $ do
519+ it "allows us to GET/POST/... requests in IO instead of ClientM" $ \(_, baseUrl) -> do
520+ let (getInt :<|> postInt)
521+ = hoistClient hoistClientAPI
522+ (fmap (either (error . show) id) . flip runClientUnsafe baseUrl)
523+ (client hoistClientAPI)
524+
525+ getInt `shouldReturn` 5
526+ postInt 5 `shouldReturn` 5
527+
528+-- * ConnectionError
529+type ConnectionErrorAPI = Get '[JSON] Int
530+
531+connectionErrorAPI :: Proxy ConnectionErrorAPI
532+connectionErrorAPI = Proxy
533+
534+connectionErrorSpec :: Spec
535+connectionErrorSpec = describe "Servant.Client.ServantError" $
536+ xit "correctly catches ConnectionErrors when the HTTP request can't go through" $ do
537+ let getInt = client connectionErrorAPI
538+ let baseUrl' = BaseUrl Http "example.invalid" 80 ""
539+ let isHttpError (Left (ConnectionError e)) = isJust $ fromException @IOException e
540+ isHttpError _ = False
541+ (isHttpError <$> runClient getInt baseUrl') `shouldReturn` True
542+
543+-- * utils
544+
545+startWaiApp :: Application -> IO (ThreadId, BaseUrl)
546+startWaiApp app = do
547+ (port, socket) <- openTestSocket
548+ let settings = setPort port $ defaultSettings
549+ thread <- forkIO $ runSettingsSocket settings socket app
550+ return (thread, BaseUrl Http "localhost" port "")
551+
552+
553+endWaiApp :: (ThreadId, BaseUrl) -> IO ()
554+endWaiApp (thread, _) = killThread thread
555+
556+openTestSocket :: IO (Port, Socket)
557+openTestSocket = do
558+ s <- socket AF_INET Stream defaultProtocol
559+ let localhost = tupleToHostAddress (127, 0, 0, 1)
560+ bind s (SockAddrInet defaultPort localhost)
561+ listen s 1
562+ port <- socketPort s
563+ return (fromIntegral port, s)
564+
565+pathGen :: Gen (NonEmptyList Char)
566+pathGen = fmap NonEmpty path
567+ where
568+ path = listOf1 $ elements $
569+ filter (not . (`elem` ("?%[]/#;" :: String))) $
570+ filter isPrint $
571+ map chr [0..127]