Skip to content

Instantly share code, notes, and snippets.

@gattytto
Created November 6, 2020 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gattytto/5ae5f997d107d051a6a0e9875e654c82 to your computer and use it in GitHub Desktop.
Save gattytto/5ae5f997d107d051a6a0e9875e654c82 to your computer and use it in GitHub Desktop.
module AppSpec where
import Control.Exception (throwIO)
import Network.HTTP.Client (Manager, newManager, defaultManagerSettings)
import Network.HTTP.Types
import Network.Wai (Application)
import Network.Wai.Handler.Warp
import Servant
import Servant.Client
import Test.Hspec
import App hiding (getItems)
getItems :: ClientM [Item]
getItem :: Integer -> ClientM Item
getItems :<|> getItem = client itemApi
spec :: Spec
spec = do
describe "/item" $ do
withClient mkApp $ do
it "lists an example item" $ \ env -> do
try env getItems `shouldReturn` [Item 0 "example item"]
it "allows to show items by id" $ \ env -> do
try env (getItem 0) `shouldReturn` Item 0 "example item"
it "throws a 404 for missing items" $ \ env -> do
try env (getItem 42) `shouldThrow` errorsWithStatus notFound404
errorsWithStatus :: Status -> ClientError -> Bool
errorsWithStatus status servantError = case servantError of
FailureResponse response -> responseStatusCode response == status
_ -> False
withClient :: IO Application -> SpecWith ClientEnv -> SpecWith ()
withClient x innerSpec =
beforeAll (newManager defaultManagerSettings) $ do
flip aroundWith innerSpec $ \ action -> \ httpManager -> do
testWithApplication x $ \ port -> do
let testBaseUrl = BaseUrl Http "localhost" port "3000"
action (ClientEnv httpManager testBaseUrl Nothing)
type Host = (Manager, BaseUrl)
try :: ClientEnv -> ClientM a -> IO a
try clientEnv action = either throwIO return =<<
runClientM action clientEnv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment