Haskell规范文章不起作用

时间:2016-12-20 13:55:36

标签: haskell

我目前正在编写一个Haskell测试代码,但是帖子部分没有用。

    module Main where

      import           MyLib (app)
      import           Control.Monad       (mzero)
      import           Data.Aeson
      import           Test.Hspec
      import           Test.Hspec.Wai
      import           Data.Semigroup ((<>))

      --import           Test.Hspec.Wai.JSON
      --import           UseHaskellAPI
      data ResponseMsg = ResponseMsg { name    :: String
                                     , message :: String
                                     } deriving (Eq, Show)
      instance FromJSON ResponseMsg where
       parseJSON (Object o) =
         ResponseMsg <$> o .: "name"
                     <*> o .: "message"
       parseJSON _ = mzero

      instance ToJSON ResponseMsg where
        -- this generates a Value
        toJSON (ResponseMsg n m) =
            object ["name" .= n, "message" .= m]

        -- this encodes directly to a bytestring Builder
        toEncoding (ResponseMsg n m) =
            pairs ("name" .= n <> "message" .= m)


      main :: IO ()
      main = do
        --
        putStrLn $ show $ toJSON $ ResponseMsg "ecky" "hello"
        hspec spec

      spec :: Spec
      spec = with (return app) $ do
        --test case for sample storage message
        describe "POST /storeMessage true" $ do
          it "responds with storeMessage" $ do
            (post "/storeMessage" $ encode $ toJSON $ ResponseMsg "ecky" "hello") `shouldRespondWith` "true%" {matchHeaders = ["Content-Type" <:> "application/json"]}

控制台输出如下

测试/ Main.hs:48:       1)POST / storeMessage true以storeMessage响应            状态不匹配:              预期:200              但得到了:415            缺少标题:              Content-Type:application / json            实际的标题是:            身体不匹配:              预期:&#34; true%&#34;              但得到了:&#34;&#34;

这是数据类型

    data Message = Message { name    :: String
                           , message :: String
                           } deriving (Show, Generic, FromJSON, ToJSON, ToBSON, FromBSON)

    deriving instance FromBSON String  -- we need these as BSON does not provide
    deriving instance ToBSON   String

这是服务器api

        storeMessage :: Message -> Handler Bool
        storeMessage msg@(Message key _) = liftIO $ do
          warnLog $ "Storing message under key " ++ key ++ "."
          withMongoDbConnection $ upsert (select ["name" =: key] "MESSAGE_RECORD") $ toBSON msg

          return True 

有人知道这个问题吗?提前致谢

1 个答案:

答案 0 :(得分:1)

这是一个很旧的信息,但是对于那些今天想要寻找答案的人,我希望是这样。

我不知道默认的content-type头是什么,但是这里显然不是"application/json",所以必须指定它,因为这就是发送的内容。因此,请改用request

request methodPost "/storeMessage" [(hApplicationContent, "application/json" :: ByteString)] $ encode $ toJSON $ ResponseMsg "ecky" "hello"

请参阅文档Test.Hspec.Waiheaders