对于我们的Hakyll代码库,我已经编写了一些辅助方法,并开始围绕较新的方法添加一些HSpec单元测试,例如:
-- | Reject an item unless @fieldName@ is set to "true"
unlessEnabled :: MonadMetadata m
=> String
-> Item a
-> m Bool
unlessEnabled fieldName item = do
maybeValue <- getMetadataBool (itemIdentifier item) fieldName
return $ maybe True not maybeValue
-- | Try to look up a boolean field ("true" maps to @Just True@)
getMetadataBool :: MonadMetadata m
=> Identifier
-> String
-> m (Maybe Bool)
getMetadataBool ident name = do
maybeString <- getMetadataField ident name
return $ ((== "true") . map toLower) <$> maybeString
现在创建一个用于测试的Item
或Identifier
已经足够简单了,但我不确定在运行Hspec时MonadMetadata
该何去何从。
我见过testCompiler
,感觉它可能是可复制/有用的(Compiler
有一个MonadMetadata
实例(,但我在这里超出了我的Haskell深度。。。
最终(多亏了@Bergi的建议(我做了一些工作,然后整理了一下:
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
type KeyedValuesOf a = [(String, a)]
-- | Create Metadata from basic list of key-values -- stolen from Hakyll itself.
meta :: Yaml.ToJSON a => KeyedValuesOf a -> Metadata
meta pairs = HMS.fromList [(T.pack k, Yaml.toJSON v) | (k, v) <- pairs]
-- | A 'Reader' class of our own, with a specialised environment
-- for key-value metadata pairs.
newtype MonadMetadataReader a =
MonadMetadataReader {runMonadMetadataReader :: KeyedValuesOf String -> a}
deriving (Functor, Applicative, Monad)
-- | Simple 'Metadata' holder.
-- There are never any matches found,
-- and all metadata (for all items)
-- comes from from the Reader-like environment at setup.
instance MonadMetadata MonadMetadataReader where
getMetadata identifier = MonadMetadataReader meta
getMatches pattern = return []
它允许简单的单元测试,如:
it "enables for a value of "false"" $ do
let enabled = runMonadMetadataReader (unlessEnabled "key" item) [("key", "false")]
enabled `shouldBe` True
it "disables for a value of "true"" $ do
let enabled = runMonadMetadataReader (unlessEnabled "key" item) [("key", "true")]
enabled `shouldBe` False
it "enables if no metadata found" $ do
let enabled = runMonadMetadataReader (unlessEnabled "key" item) []
enabled `shouldBe` True