Debian Codegraph @

test/Test/Hspec/Wai/Extra.hs

raw
1 -- | This should be in 'hspec-wai', PR pending as of Feb 2024 : https://github.com/hspec/hspec-wai/pull/77
2 --
3 -- NB the code below has been changed wrt PR 77 and works in the scotty test suite as well.
4
5 {-# language OverloadedStrings #-}
6 module Test.Hspec.Wai.Extra (postMultipartForm, FileMeta(..)) where
7
8 import qualified Data.Char as Char
9 import Data.List (intersperse)
10
11 import Data.ByteString (ByteString)
12 import qualified Data.ByteString.Builder as Builder
13 import qualified Data.ByteString.Lazy as LB
14
15 import Data.Word (Word8)
16
17 import Network.HTTP.Types (methodPost, hContentType)
18 import Network.Wai.Test (SResponse)
19
20 import Test.Hspec.Wai (request)
21 import Test.Hspec.Wai.Internal (WaiSession)
22
23 -- | @POST@ a @multipart/form-data@ form which might include files.
24 --
25 -- The @Content-Type@ is set to @multipart/form-data; boundary=<bd>@ where @bd@ is the part separator without the @--@ prefix.
26 postMultipartForm :: ByteString -- ^ path
27 -> ByteString -- ^ part separator without any dashes
28 -> [(FileMeta, ByteString, ByteString, ByteString)] -- ^ (file metadata, field MIME type, field name, field contents)
29 -> WaiSession st SResponse
30 postMultipartForm path sbs =
31 request methodPost path [(hContentType, "multipart/form-data; boundary=" <> sbs)] . formMultipartQuery sbs
32
33 -- | Encode the body of a multipart form post
34 --
35 -- schema from : https://swagger.io/docs/specification/describing-request-body/multipart-requests/
36 formMultipartQuery :: ByteString -- ^ part separator without any dashes
37 -> [(FileMeta, ByteString, ByteString, ByteString)] -- ^ (file metadata, field MIME type, field name, field contents)
38 -> LB.ByteString
39 formMultipartQuery sbs = Builder.toLazyByteString . mconcat . intersperse newline . encodeAll
40 where
41 encodeAll fs = map encodeFile fs <> [sepEnd]
42 encodeFile (fieldMeta, ty, n, payload) = mconcat $ [
43 sep
44 , newline
45 , kv "Content-Disposition" ("form-data;" <> " name=" <> quoted n <> encodeMPField fieldMeta)
46 , newline
47 , kv "Content-Type" (Builder.byteString ty)
48 , newline, newline
49 , Builder.byteString payload
50 ]
51 sep = Builder.byteString ("--" <> sbs)
52 sepEnd = Builder.byteString ("--" <> sbs <> "--")
53 encodeMPField FMFormField = mempty
54 encodeMPField (FMFile fname) = "; filename=" <> quoted fname
55 quoted x = Builder.byteString ("\"" <> x <> "\"")
56 kv k v = k <> ": " <> v
57 newline = Builder.word8 (ord '\n')
58
59
60 data FileMeta = FMFormField -- ^ any form field except a file
61 | FMFile ByteString -- ^ file name
62
63
64 ord :: Char -> Word8
65 ord = fromIntegral . Char.ord