PersistSpec.hs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. {-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies #-}
  2. {-# LANGUAGE EmptyDataDecls, FlexibleContexts, GADTs #-}
  3. {-# LANGUAGE GeneralizedNewtypeDeriving #-}
  4. {-# LANGUAGE MultiParamTypeClasses #-}
  5. {-# LANGUAGE CPP #-}
  6. module Yesod.PersistSpec where
  7. import Test.Hspec
  8. import Database.Persist.Sqlite
  9. import Network.Wai.Test
  10. import Yesod.Core
  11. import Data.Conduit
  12. import Blaze.ByteString.Builder.Char.Utf8 (fromText)
  13. import Yesod.Persist
  14. import Data.Text (Text)
  15. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
  16. Person
  17. name Text
  18. |]
  19. data App = App
  20. { appConfig :: SqliteConf
  21. , appPool :: ConnectionPool
  22. }
  23. mkYesod "App" [parseRoutes|
  24. / HomeR GET
  25. |]
  26. instance Yesod App
  27. instance YesodPersist App where
  28. type YesodPersistBackend App = SqlBackend
  29. runDB = defaultRunDB appConfig appPool
  30. instance YesodPersistRunner App where
  31. getDBRunner = defaultGetDBRunner appPool
  32. getHomeR :: Handler TypedContent
  33. getHomeR = do
  34. runDB $ do
  35. runMigration migrateAll
  36. deleteWhere ([] :: [Filter Person])
  37. insert_ $ Person "Charlie"
  38. insert_ $ Person "Alice"
  39. insert_ $ Person "Bob"
  40. respondSourceDB typePlain $ selectSource [] [Asc PersonName] $= awaitForever toBuilder
  41. where
  42. toBuilder (Entity _ (Person name)) = do
  43. yield $ Chunk $ fromText name
  44. yield $ Chunk $ fromText "\n"
  45. yield Flush
  46. test :: String -> Session () -> Spec
  47. test name session = it name $ do
  48. let config = SqliteConf ":memory:" 1
  49. pool <- createPoolConfig config
  50. app <- toWaiApp $ App config pool
  51. runSession session app
  52. spec :: Spec
  53. spec = test "streaming" $ do
  54. sres <- request defaultRequest
  55. assertBody "Alice\nBob\nCharlie\n" sres
  56. assertStatus 200 sres