module Test.Tasty.Wai
(
Sess (..)
, testWai
, get
, post
, put
, assertStatus'
, buildRequest
, buildRequestWithBody
, buildRequestWithHeaders
, module Network.Wai.Test
) where
import qualified Control.Exception as E
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Monoid ((<>))
import Network.HTTP.Types (RequestHeaders, StdMethod)
import qualified Network.HTTP.Types as HTTP
import Test.HUnit.Lang (HUnitFailure (HUnitFailure), formatFailureReason)
import Test.Tasty.Providers (IsTest (..), Progress (..), TestName,
TestTree, singleTest, testFailed,
testPassed)
import Test.Tasty.Runners (formatMessage)
import Network.Wai (Application, Request, requestHeaders,
requestMethod)
import Network.Wai.Test
data Sess = S Application TestName (Session ())
instance IsTest Sess where
testOptions = mempty
run _ (S app tName sess) yieldProgress = do
yieldProgress $ Progress ("Running " <> tName) 0
E.try (runSession sess app) >>= either toFailure toPass
where
toFailure (HUnitFailure _ s) = testFailed <$> (formatMessage (formatFailureReason s))
toPass _ = pure (testPassed mempty)
buildRequest
:: StdMethod
-> BS.ByteString
-> Request
buildRequest mth rpath = flip setPath rpath $ defaultRequest
{ requestMethod = HTTP.renderStdMethod mth
}
buildRequestWithBody
:: StdMethod
-> BS.ByteString
-> LBS.ByteString
-> SRequest
buildRequestWithBody mth rpath =
SRequest (buildRequest mth rpath)
buildRequestWithHeaders
:: StdMethod
-> BS.ByteString
-> LBS.ByteString
-> RequestHeaders
-> SRequest
buildRequestWithHeaders mthd pth bdy hdrs =
rq { simpleRequest = (simpleRequest rq) { requestHeaders = hdrs } }
where rq = buildRequestWithBody mthd pth bdy
testWai :: Application -> TestName -> Session () -> TestTree
testWai a tn = singleTest tn . S a tn
get :: BS.ByteString -> Session SResponse
get = request . buildRequest HTTP.GET
post :: BS.ByteString -> LBS.ByteString -> Session SResponse
post r = srequest . buildRequestWithBody HTTP.POST r
put :: BS.ByteString -> LBS.ByteString -> Session SResponse
put r = srequest . buildRequestWithBody HTTP.PUT r
assertStatus' :: HTTP.Status -> SResponse -> Session ()
assertStatus' c = assertStatus (HTTP.statusCode c)