@@ -1,5 +1,4 @@
11{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ConstraintKinds #-}
32{-# LANGUAGE DataKinds #-}
43{-# LANGUAGE DeriveGeneric #-}
54{-# LANGUAGE FlexibleContexts #-}
@@ -11,7 +10,6 @@
1110{-# LANGUAGE PolyKinds #-}
1211{-# LANGUAGE RecordWildCards #-}
1312{-# LANGUAGE StandaloneDeriving #-}
14−{-# LANGUAGE ScopedTypeVariables #-}
1513{-# LANGUAGE TypeFamilies #-}
1614{-# LANGUAGE TypeOperators #-}
1715{-# LANGUAGE UndecidableInstances #-}
@@ -21,17 +19,13 @@
2119{-# OPTIONS_GHC -fcontext-stack=100 #-}
2220#endif
2321{-# OPTIONS_GHC -fno-warn-orphans #-}
24−{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
2522
26−#include "overlapping-compat.h"
2723module Servant.ClientSpec where
2824
29−#if !MIN_VERSION_base(4,8,0)
30−import Control.Applicative ((<$>))
31−#endif
25+import Prelude ()
26+import Prelude.Compat
27+
3228import Control.Arrow (left)
33−import Control.Concurrent (forkIO, killThread, ThreadId)
34−import Control.Exception (bracket)
3529import Control.Monad.Trans.Except (throwE )
3630import Data.Aeson
3731import qualified Data.ByteString.Lazy as BS
@@ -42,34 +36,75 @@ import Data.Proxy
4236import GHC.Generics (Generic)
4337import qualified Network.HTTP.Client as C
4438import Network.HTTP.Media
45−import qualified Network.HTTP.Types as HTTP
46−import Network.Socket
47−import Network.Wai (Request, requestHeaders, responseLBS)
48−import Network.Wai.Handler.Warp
39+import qualified Network.HTTP.Types as HTTP
40+import Network.Wai (responseLBS)
41+import qualified Network.Wai as Wai
42+import System.Exit.Compat
4943import System.IO.Unsafe (unsafePerformIO)
44+import Test.HUnit
5045import Test.Hspec
5146import Test.Hspec.QuickCheck
52−import Test.HUnit
5347import Test.QuickCheck
5448import Web.FormUrlEncoded (FromForm, ToForm)
5549
5650import Servant.API
57−import Servant.API.Internal.Test.ComprehensiveAPI
5851import Servant.Client
52+import Servant.Client.TestServer
53+import qualified Servant.Common.Req as SCR
5954import Servant.Server
6055import Servant.Server.Experimental.Auth
61−import qualified Servant.Common.Req as SCR
62−
63−-- This declaration simply checks that all instances are in place.
64−_ = client comprehensiveAPI
6556
6657spec :: Spec
67−spec = describe "Servant.Client" $ do
58+spec = do
59+ runIO buildTestServer
60+ describe "Servant.Client" $ do
6861 sucessSpec
6962 failSpec
70− wrappedApiSpec
7163 basicAuthSpec
7264 genAuthSpec
65+ errorSpec
66+
67+-- | Run a test-server (identified by name) while performing the given action.
68+-- The provided 'BaseUrl' points to the running server.
69+--
70+-- Running the test-servers is done differently depending on the compiler
71+-- (ghc or ghcjs).
72+--
73+-- With ghc it's somewhat straight-forward: a wai 'Application' is being started
74+-- on a free port inside the same process using 'warp'.
75+--
76+-- When running the test-suite with ghcjs all the test-servers are compiled into
77+-- a single external executable (with ghc and warp). This is done through
78+-- 'buildTestServer' once at the start of the test-suite. This built executable
79+-- will provide all the test-servers on a free port under a path that
80+-- corresponds to the test-servers name, for example under
81+-- 'http://localhost:82923/failServer'. 'withTestServer' will then
82+-- start this executable as an external process while the given action is being
83+-- executed and provide it with the correct BaseUrl.
84+-- This rather cumbersome approach is taken because it's not easy to run a wai
85+-- Application as a http server when using ghcjs.
86+withTestServer :: String -> (BaseUrl -> IO a) -> IO a
87+withTestServer name action = do
88+ server <- lookupTestServer name
89+ withServer server action
90+
91+lookupTestServer :: String -> IO TestServer
92+lookupTestServer name = case lookup name mapping of
93+ Nothing -> die ("test server not found: " ++ name)
94+ Just testServer -> return testServer
95+ where
96+ mapping :: [(String, TestServer)]
97+ mapping = map (\ server -> (testServerName server, server)) allTestServers
98+
99+-- | All test-servers must be registered here.
100+allTestServers :: [TestServer]
101+allTestServers =
102+ server :
103+ errorServer :
104+ failServer :
105+ basicAuthServer :
106+ genAuthServer :
107+ []
73108
74109-- * test data types
75110
@@ -120,9 +155,9 @@ getBody :: Person -> SCR.ClientM Person
120155getQueryParam :: Maybe String -> SCR.ClientM Person
121156getQueryParams :: [String] -> SCR.ClientM [Person]
122157getQueryFlag :: Bool -> SCR.ClientM Bool
123−getRawSuccess :: HTTP.Method
158+getRawSuccess :: HTTP.Method
124159 -> SCR.ClientM (Int, BS.ByteString, MediaType, [HTTP.Header], C.Response BS.ByteString)
125−getRawFailure :: HTTP.Method
160+getRawFailure :: HTTP.Method
126161 -> SCR.ClientM (Int, BS.ByteString, MediaType, [HTTP.Header], C.Response BS.ByteString)
127162getMultiple :: String -> Maybe Int -> Bool -> [(String, [Rational])]
128163 -> SCR.ClientM (String, Maybe Int, Bool, [(String, [Rational])])
@@ -142,8 +177,8 @@ getGet
142177 :<|> getRespHeaders
143178 :<|> getDeleteContentType = client api
144179
145−server :: Application
146−server = serve api (
180+server :: TestServer
181+server = TestServer "server" $ serve api (
147182 return alice
148183 :<|> return NoContent
149184 :<|> (\ name -> return $ Person name 0)
@@ -162,19 +197,19 @@ server = serve api (
162197 :<|> return NoContent
163198 )
164199
165−
166200type FailApi =
167201 "get" :> Raw
168202 :<|> "capture" :> Capture "name" String :> Raw
169203 :<|> "body" :> Raw
204+
170205failApi :: Proxy FailApi
171206failApi = Proxy
172207
173−failServer :: Application
174−failServer = serve failApi (
208+failServer :: TestServer
209+failServer = TestServer "failServer" $ serve failApi (
175210 (\ _request respond -> respond $ responseLBS HTTP.ok200 [] "")
176211 :<|> (\ _capture _request respond -> respond $ responseLBS HTTP.ok200 [("content-type", "application/json")] "")
177− :<|> (\_request respond -> respond $ responseLBS HTTP.ok200 [("content-type", "fooooo")] "")
212+ :<|> (\ _request respond -> respond $ responseLBS HTTP.ok200 [("content-type", "fooooo")] "")
178213 )
179214
180215-- * basic auth stuff
@@ -196,8 +231,9 @@ basicAuthHandler =
196231basicServerContext :: Context '[ BasicAuthCheck () ]
197232basicServerContext = basicAuthHandler :. EmptyContext
198233
199−basicAuthServer :: Application
200−basicAuthServer = serveWithContext basicAuthAPI basicServerContext (const (return alice))
234+basicAuthServer :: TestServer
235+basicAuthServer = TestServer "basicAuthServer" $
236+ serveWithContext basicAuthAPI basicServerContext (const (return alice))
201237
202238-- * general auth stuff
203239
@@ -210,62 +246,63 @@ genAuthAPI = Proxy
210246type instance AuthServerData (AuthProtect "auth-tag") = ()
211247type instance AuthClientData (AuthProtect "auth-tag") = ()
212248
213−genAuthHandler :: AuthHandler Request ()
249+genAuthHandler :: AuthHandler Wai.Request ()
214250genAuthHandler =
215− let handler req = case lookup "AuthHeader" (requestHeaders req) of
251+ let handler req = case lookup "AuthHeader" (Wai.requestHeaders req) of
216252 Nothing -> throwE (err401 { errBody = "Missing auth header" })
217253 Just _ -> return ()
218254 in mkAuthHandler handler
219255
220−genAuthServerContext :: Context '[ AuthHandler Request () ]
256+genAuthServerContext :: Context '[ AuthHandler Wai.Request () ]
221257genAuthServerContext = genAuthHandler :. EmptyContext
222258
223−genAuthServer :: Application
224−genAuthServer = serveWithContext genAuthAPI genAuthServerContext (const (return alice))
259+genAuthServer :: TestServer
260+genAuthServer = TestServer "genAuthServer" $
261+ serveWithContext genAuthAPI genAuthServerContext (const (return alice))
225262
226263{-# NOINLINE manager #-}
227264manager :: C.Manager
228265manager = unsafePerformIO $ C.newManager C.defaultManagerSettings
229266
230267sucessSpec :: Spec
231−sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
268+sucessSpec = around (withTestServer "server") $ do
232269
233− it "Servant.API.Get" $ \(_, baseUrl) -> do
270+ it "Servant.API.Get" $ \baseUrl -> do
234271 (left show <$> (runClientM getGet (ClientEnv manager baseUrl))) `shouldReturn` Right alice
235272
236273 describe "Servant.API.Delete" $ do
237− it "allows empty content type" $ \(_, baseUrl) -> do
274+ it "allows empty content type" $ \baseUrl -> do
238275 (left show <$> (runClientM getDeleteEmpty (ClientEnv manager baseUrl))) `shouldReturn` Right NoContent
239276
240− it "allows content type" $ \(_, baseUrl) -> do
277+ it "allows content type" $ \baseUrl -> do
241278 (left show <$> (runClientM getDeleteContentType (ClientEnv manager baseUrl))) `shouldReturn` Right NoContent
242279
243− it "Servant.API.Capture" $ \(_, baseUrl) -> do
280+ it "Servant.API.Capture" $ \baseUrl -> do
244281 (left show <$> (runClientM (getCapture "Paula") (ClientEnv manager baseUrl))) `shouldReturn` Right (Person "Paula" 0)
245282
246− it "Servant.API.CaptureAll" $ \(_, baseUrl) -> do
283+ it "Servant.API.CaptureAll" $ \baseUrl -> do
247284 let expected = [(Person "Paula" 0), (Person "Peta" 1)]
248285 (left show <$> (runClientM (getCaptureAll ["Paula", "Peta"]) (ClientEnv manager baseUrl))) `shouldReturn` Right expected
249286
250− it "Servant.API.ReqBody" $ \(_, baseUrl) -> do
287+ it "Servant.API.ReqBody" $ \baseUrl -> do
251288 let p = Person "Clara" 42
252289 (left show <$> runClientM (getBody p) (ClientEnv manager baseUrl)) `shouldReturn` Right p
253290
254− it "Servant.API.QueryParam" $ \(_, baseUrl) -> do
291+ it "Servant.API.QueryParam" $ \baseUrl -> do
255292 left show <$> runClientM (getQueryParam (Just "alice")) (ClientEnv manager baseUrl) `shouldReturn` Right alice
256293 Left FailureResponse{..} <- runClientM (getQueryParam (Just "bob")) (ClientEnv manager baseUrl)
257294 responseStatus `shouldBe` HTTP.Status 400 "bob not found"
258295
259− it "Servant.API.QueryParam.QueryParams" $ \(_, baseUrl) -> do
296+ it "Servant.API.QueryParam.QueryParams" $ \baseUrl -> do
260297 (left show <$> runClientM (getQueryParams []) (ClientEnv manager baseUrl)) `shouldReturn` Right []
261298 (left show <$> runClientM (getQueryParams ["alice", "bob"]) (ClientEnv manager baseUrl))
262299 `shouldReturn` Right [Person "alice" 0, Person "bob" 1]
263300
264301 context "Servant.API.QueryParam.QueryFlag" $
265− forM_ [False, True] $ \ flag -> it (show flag) $ \(_, baseUrl) -> do
302+ forM_ [False, True] $ \ flag -> it (show flag) $ \baseUrl -> do
266303 (left show <$> runClientM (getQueryFlag flag) (ClientEnv manager baseUrl)) `shouldReturn` Right flag
267304
268− it "Servant.API.Raw on success" $ \(_, baseUrl) -> do
305+ it "Servant.API.Raw on success" $ \baseUrl -> do
269306 res <- runClientM (getRawSuccess HTTP.methodGet) (ClientEnv manager baseUrl)
270307 case res of
271308 Left e -> assertFailure $ show e
@@ -274,7 +311,7 @@ sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
274311 C.responseBody response `shouldBe` body
275312 C.responseStatus response `shouldBe` HTTP.ok200
276313
277− it "Servant.API.Raw should return a Left in case of failure" $ \(_, baseUrl) -> do
314+ it "Servant.API.Raw should return a Left in case of failure" $ \baseUrl -> do
278315 res <- runClientM (getRawFailure HTTP.methodGet) (ClientEnv manager baseUrl)
279316 case res of
280317 Right _ -> assertFailure "expected Left, but got Right"
@@ -282,51 +319,93 @@ sucessSpec = beforeAll (startWaiApp server) $ afterAll endWaiApp $ do
282319 Servant.Client.responseStatus e `shouldBe` HTTP.status400
283320 Servant.Client.responseBody e `shouldBe` "rawFailure"
284321
285− it "Returns headers appropriately" $ \(_, baseUrl) -> do
322+ it "Returns headers appropriately" $ \baseUrl -> do
286323 res <- runClientM getRespHeaders (ClientEnv manager baseUrl)
287324 case res of
288325 Left e -> assertFailure $ show e
289326 Right val -> getHeaders val `shouldBe` [("X-Example1", "1729"), ("X-Example2", "eg2")]
290327
291328 modifyMaxSuccess (const 20) $ do
292− it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $ \(_, baseUrl) ->
329+ it "works for a combination of Capture, QueryParam, QueryFlag and ReqBody" $ \baseUrl ->
293330 property $ forAllShrink pathGen shrink $ \(NonEmpty cap) num flag body ->
294331 ioProperty $ do
295332 result <- left show <$> runClientM (getMultiple cap num flag body) (ClientEnv manager baseUrl)
296333 return $
297334 result === Right (cap, num, flag, body)
298335
336+type ErrorApi =
337+ Delete '[JSON] () :<|>
338+ Get '[JSON] () :<|>
339+ Post '[JSON] () :<|>
340+ Put '[JSON] ()
341+
342+errorApi :: Proxy ErrorApi
343+errorApi = Proxy
344+
345+errorServer :: TestServer
346+errorServer = TestServer "errorServer" $ serve errorApi $
347+ err :<|> err :<|> err :<|> err
348+ where
349+ err = throwE $ ServantErr 500 "error message" "" []
350+
351+errorSpec :: Spec
352+errorSpec =
353+ around (withTestServer "errorServer") $ do
354+ describe "error status codes" $
355+ it "reports error statuses correctly" $ \baseUrl -> do
356+ let delete :<|> get :<|> post :<|> put =
357+ client errorApi
358+ actions = [delete, get, post, put]
359+ forM_ actions $ \ clientAction -> do
360+ Left FailureResponse{..} <- runClientM clientAction (ClientEnv manager baseUrl)
361+ responseStatus `shouldBe` HTTP.Status 500 "error message"
362+
363+basicAuthSpec :: Spec
364+basicAuthSpec = around (withTestServer "basicAuthServer") $ do
365+ context "Authentication works when requests are properly authenticated" $ do
366+
367+ it "Authenticates a BasicAuth protected server appropriately" $ \baseUrl -> do
368+ let getBasic = client basicAuthAPI
369+ let basicAuthData = BasicAuthData "servant" "server"
370+ (left show <$> runClientM (getBasic basicAuthData) (ClientEnv manager baseUrl)) `shouldReturn` Right alice
371+
372+ context "Authentication is rejected when requests are not authenticated properly" $ do
373+
374+ it "Authenticates a BasicAuth protected server appropriately" $ \baseUrl -> do
375+ let getBasic = client basicAuthAPI
376+ let basicAuthData = BasicAuthData "not" "password"
377+ Left FailureResponse{..} <- runClientM (getBasic basicAuthData) (ClientEnv manager baseUrl)
378+ responseStatus `shouldBe` HTTP.Status 403 "Forbidden"
379+
380+genAuthSpec :: Spec
381+genAuthSpec = around (withTestServer "genAuthServer") $ do
382+ context "Authentication works when requests are properly authenticated" $ do
383+
384+ it "Authenticates a AuthProtect protected server appropriately" $ \baseUrl -> do
385+ let getProtected = client genAuthAPI
386+ let authRequest = mkAuthenticateReq () (\_ req -> SCR.addHeader "AuthHeader" ("cool" :: String) req)
387+ (left show <$> runClientM (getProtected authRequest) (ClientEnv manager baseUrl)) `shouldReturn` Right alice
299388
300−wrappedApiSpec :: Spec
301−wrappedApiSpec = describe "error status codes" $ do
302− let serveW api = serve api $ throwE $ ServantErr 500 "error message" "" []
303− context "are correctly handled by the client" $
304− let test :: (WrappedApi, String) -> Spec
305− test (WrappedApi api, desc) =
306− it desc $ bracket (startWaiApp $ serveW api) endWaiApp $ \(_, baseUrl) -> do
307− let getResponse :: SCR.ClientM ()
308− getResponse = client api
309− Left FailureResponse{..} <- runClientM getResponse (ClientEnv manager baseUrl)
310− responseStatus `shouldBe` (HTTP.Status 500 "error message")
311− in mapM_ test $
312− (WrappedApi (Proxy :: Proxy (Delete '[JSON] ())), "Delete") :
313− (WrappedApi (Proxy :: Proxy (Get '[JSON] ())), "Get") :
314− (WrappedApi (Proxy :: Proxy (Post '[JSON] ())), "Post") :
315− (WrappedApi (Proxy :: Proxy (Put '[JSON] ())), "Put") :
316− []
389+ context "Authentication is rejected when requests are not authenticated properly" $ do
390+
391+ it "Authenticates a AuthProtect protected server appropriately" $ \baseUrl -> do
392+ let getProtected = client genAuthAPI
393+ let authRequest = mkAuthenticateReq () (\_ req -> SCR.addHeader "Wrong" ("header" :: String) req)
394+ Left FailureResponse{..} <- runClientM (getProtected authRequest) (ClientEnv manager baseUrl)
395+ responseStatus `shouldBe` (HTTP.Status 401 "Unauthorized")
317396
318397failSpec :: Spec
319−failSpec = beforeAll (startWaiApp failServer) $ afterAll endWaiApp $ do
398+failSpec = around (withTestServer "failServer") $ do
320399
321400 context "client returns errors appropriately" $ do
322− it "reports FailureResponse" $ \(_, baseUrl) -> do
401+ it "reports FailureResponse" $ \baseUrl -> do
323402 let (_ :<|> getDeleteEmpty :<|> _) = client api
324403 Left res <- runClientM getDeleteEmpty (ClientEnv manager baseUrl)
325404 case res of
326405 FailureResponse (HTTP.Status 404 "Not Found") _ _ -> return ()
327406 _ -> fail $ "expected 404 response, but got " <> show res
328407
329− it "reports DecodeFailure" $ \(_, baseUrl) -> do
408+ it "reports DecodeFailure" $ \baseUrl -> do
330409 let (_ :<|> _ :<|> getCapture :<|> _) = client api
331410 Left res <- runClientM (getCapture "foo") (ClientEnv manager baseUrl)
332411 case res of
@@ -340,81 +419,23 @@ failSpec = beforeAll (startWaiApp failServer) $ afterAll endWaiApp $ do
340419 ConnectionError _ -> return ()
341420 _ -> fail $ "expected ConnectionError, but got " <> show res
342421
343− it "reports UnsupportedContentType" $ \(_, baseUrl) -> do
422+ it "reports UnsupportedContentType" $ \baseUrl -> do
344423 let (getGet :<|> _ ) = client api
345424 Left res <- runClientM getGet (ClientEnv manager baseUrl)
346425 case res of
347426 UnsupportedContentType ("application/octet-stream") _ -> return ()
348427 _ -> fail $ "expected UnsupportedContentType, but got " <> show res
349428
350− it "reports InvalidContentTypeHeader" $ \(_, baseUrl) -> do
429+ it "reports InvalidContentTypeHeader" $ \baseUrl -> do
351430 let (_ :<|> _ :<|> _ :<|> _ :<|> getBody :<|> _) = client api
352431 Left res <- runClientM (getBody alice) (ClientEnv manager baseUrl)
432+
353433 case res of
354434 InvalidContentTypeHeader "fooooo" _ -> return ()
355435 _ -> fail $ "expected InvalidContentTypeHeader, but got " <> show res
356436
357−data WrappedApi where
358− WrappedApi :: (HasServer (api :: *) '[], Server api ~ Handler a,
359− HasClient api, Client api ~ SCR.ClientM ()) =>
360− Proxy api -> WrappedApi
361−
362−basicAuthSpec :: Spec
363−basicAuthSpec = beforeAll (startWaiApp basicAuthServer) $ afterAll endWaiApp $ do
364− context "Authentication works when requests are properly authenticated" $ do
365−
366− it "Authenticates a BasicAuth protected server appropriately" $ \(_,baseUrl) -> do
367− let getBasic = client basicAuthAPI
368− let basicAuthData = BasicAuthData "servant" "server"
369− (left show <$> runClientM (getBasic basicAuthData) (ClientEnv manager baseUrl)) `shouldReturn` Right alice
370−
371− context "Authentication is rejected when requests are not authenticated properly" $ do
372−
373− it "Authenticates a BasicAuth protected server appropriately" $ \(_,baseUrl) -> do
374− let getBasic = client basicAuthAPI
375− let basicAuthData = BasicAuthData "not" "password"
376− Left FailureResponse{..} <- runClientM (getBasic basicAuthData) (ClientEnv manager baseUrl)
377− responseStatus `shouldBe` HTTP.Status 403 "Forbidden"
378−
379−genAuthSpec :: Spec
380−genAuthSpec = beforeAll (startWaiApp genAuthServer) $ afterAll endWaiApp $ do
381− context "Authentication works when requests are properly authenticated" $ do
382−
383− it "Authenticates a AuthProtect protected server appropriately" $ \(_, baseUrl) -> do
384− let getProtected = client genAuthAPI
385− let authRequest = mkAuthenticateReq () (\_ req -> SCR.addHeader "AuthHeader" ("cool" :: String) req)
386− (left show <$> runClientM (getProtected authRequest) (ClientEnv manager baseUrl)) `shouldReturn` Right alice
387−
388− context "Authentication is rejected when requests are not authenticated properly" $ do
389−
390− it "Authenticates a AuthProtect protected server appropriately" $ \(_, baseUrl) -> do
391− let getProtected = client genAuthAPI
392− let authRequest = mkAuthenticateReq () (\_ req -> SCR.addHeader "Wrong" ("header" :: String) req)
393− Left FailureResponse{..} <- runClientM (getProtected authRequest) (ClientEnv manager baseUrl)
394− responseStatus `shouldBe` (HTTP.Status 401 "Unauthorized")
395−
396437-- * utils
397438
398−startWaiApp :: Application -> IO (ThreadId, BaseUrl)
399−startWaiApp app = do
400− (port, socket) <- openTestSocket
401− let settings = setPort port $ defaultSettings
402− thread <- forkIO $ runSettingsSocket settings socket app
403− return (thread, BaseUrl Http "localhost" port "")
404−
405−
406−endWaiApp :: (ThreadId, BaseUrl) -> IO ()
407−endWaiApp (thread, _) = killThread thread
408−
409−openTestSocket :: IO (Port, Socket)
410−openTestSocket = do
411− s <- socket AF_INET Stream defaultProtocol
412− localhost <- inet_addr "127.0.0.1"
413− bind s (SockAddrInet aNY_PORT localhost)
414− listen s 1
415− port <- socketPort s
416− return (fromIntegral port, s)
417−
418439pathGen :: Gen (NonEmptyList Char)
419440pathGen = fmap NonEmpty path
420441 where