Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 21st, 2012  |  syntax: None  |  size: 2.03 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. {-# LANGUAGE OverloadedStrings #-}
  2.  
  3. import Control.Monad.Trans.Control
  4. import Control.Monad
  5. import Control.Monad.Trans
  6. import Control.Exception(bracket_)
  7. import Test.Hspec
  8. import Test.Hspec.HUnit ()
  9. import Test.HUnit (assertBool, assertFailure, Assertion)
  10. import Data.UString hiding(any)
  11. import Database.MongoDB
  12.  
  13. -- DBアクセスする
  14. withDB :: MonadIO m => String -> Action m a -> m (Either Failure a)
  15. withDB name action = do
  16.   pipe <- liftIO $ runIOE $ connect (host "127.0.0.1")
  17.   access pipe master (u name) action
  18.  
  19. -- テストしたい関数
  20. includeOhtaRina:: [Document] -> Bool
  21. includeOhtaRina = any isOhtaRina
  22.     where
  23.       isOhtaRina doc = (at $ "name") doc == "Ohta Rina"
  24.  
  25. -- テストデータを作って消すsetup/teardown
  26. withUsers = bracket_ setup teardown
  27.     where
  28.       setup = withDB "test" $ insertMany (u "users")
  29.                   [[ "user_id" =: "1", "name" =: "Abbey Lee Kershaw"],
  30.                    [ "user_id" =: "2", "name" =: "Miyamoto Rie"]]
  31.       teardown = withDB "test" $ delete (select [] $ "users")
  32.  
  33. withUsersIncludeOhtaRina = bracket_ setup teardown
  34.     where
  35.       setup = withDB "test" $ insertMany (u "users")
  36.                   [[ "user_id" =: "1", "name" =: "Ohta Rina"],
  37.                    [ "user_id" =: "2", "name" =: "Miyamoto Rie"]]
  38.       teardown = withDB "test" $ delete (select [] $ "users")
  39.  
  40. -- 実際のSpec
  41. specs :: Specs
  42. specs = describe "includeOhtaRina" [
  43.  
  44.   it "should be true with Ohta Rina" $
  45.     withUsersIncludeOhtaRina $ do
  46.        documents <- withDB "test" $
  47.          rest =<< Database.MongoDB.find (select [] ("users"))
  48.        case documents of
  49.          Right docs -> assertBool "OK" $ includeOhtaRina docs
  50.          Left  _    -> assertFailure "DB access failed",
  51.  
  52.   it "should be false if Ohta Rina is not there" $
  53.     withUsers $ do
  54.        documents <- withDB "test" $
  55.          rest =<< Database.MongoDB.find (select [] "users")
  56.        case documents of
  57.          Right docs -> assertBool "OK" $ not $ includeOhtaRina docs
  58.          Left  _    -> assertFailure "DB access failed"
  59.         ]
  60.  
  61. main = hspec specs