File: StaticFilesSpec.hs

package info (click to toggle)
haskell-servant-server 0.20.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 368 kB
  • sloc: haskell: 3,832; makefile: 6
file content (71 lines) | stat: -rw-r--r-- 2,147 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators     #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Servant.Server.StaticFilesSpec where

import           Control.Exception
                 (bracket)
import           Data.Proxy
                 (Proxy (Proxy))
import           Network.Wai
                 (Application)
import           System.Directory
                 (createDirectory, getCurrentDirectory, setCurrentDirectory)
import           System.IO.Temp
                 (withSystemTempDirectory)
import           Test.Hspec
                 (Spec, around_, describe, it)
import           Test.Hspec.Wai
                 (get, shouldRespondWith, with)

import           Servant.API
                 ((:<|>) ((:<|>)), (:>), Capture, Get, JSON, Raw)
import           Servant.Server
                 (Server, serve)
import           Servant.Server.StaticFiles
                 (serveDirectoryFileServer)
import           Servant.ServerSpec
                 (Person (Person))

type Api =
       "dummy_api" :> Capture "person_name" String :> Get '[JSON] Person
  :<|> "static" :> Raw


api :: Proxy Api
api = Proxy

app :: Application
app = serve api server

server :: Server Api
server =
       (\ name_ -> return (Person name_ 42))
  :<|> serveDirectoryFileServer "static"

withStaticFiles :: IO () -> IO ()
withStaticFiles action = withSystemTempDirectory "servant-test" $ \ tmpDir ->
  bracket (setup tmpDir) teardown (const action)
 where
  setup tmpDir = do
    outer <- getCurrentDirectory
    setCurrentDirectory tmpDir
    createDirectory "static"
    writeFile "static/foo.txt" "bar"
    writeFile "static/index.html" "index"
    return outer

  teardown outer = do
    setCurrentDirectory outer

spec :: Spec
spec = do
  around_ withStaticFiles $ with (return app) $ do
    describe "serveDirectory" $ do
      it "successfully serves files" $ do
        get "/static/foo.txt" `shouldRespondWith` "bar"

      it "serves the contents of index.html when requesting the root of a directory" $ do
        get "/static/" `shouldRespondWith` "index"