|
Packit |
938058 |
{-# LANGUAGE OverloadedStrings #-}
|
|
Packit |
938058 |
|
|
Packit |
938058 |
import Text.DocTemplates
|
|
Packit |
938058 |
import Test.Hspec
|
|
Packit |
938058 |
import Data.Text
|
|
Packit |
938058 |
import Data.Aeson
|
|
Packit |
938058 |
|
|
Packit |
938058 |
data Employee = Employee { firstName :: String
|
|
Packit |
938058 |
, lastName :: String
|
|
Packit |
938058 |
, salary :: Maybe Integer }
|
|
Packit |
938058 |
instance ToJSON Employee where
|
|
Packit |
938058 |
toJSON e = object [ "name" .= object [ "first" .= firstName e
|
|
Packit |
938058 |
, "last" .= lastName e ]
|
|
Packit |
938058 |
, "salary" .= salary e ]
|
|
Packit |
938058 |
|
|
Packit |
938058 |
employees :: [Employee]
|
|
Packit |
938058 |
employees = [ Employee "John" "Doe" Nothing
|
|
Packit |
938058 |
, Employee "Omar" "Smith" (Just 30000)
|
|
Packit |
938058 |
, Employee "Sara" "Chen" (Just 60000) ]
|
|
Packit |
938058 |
|
|
Packit |
938058 |
template :: Text
|
|
Packit |
938058 |
template =
|
|
Packit |
938058 |
"$for(employee)$Hi, $employee.name.first$. $if(employee.salary)$You make $$$employee.salary$.$else$No salary data.$endif$$sep$\n$endfor$"
|
|
Packit |
938058 |
|
|
Packit |
938058 |
main :: IO ()
|
|
Packit |
938058 |
main = hspec $ do
|
|
Packit |
938058 |
describe "applyTemplate" $ do
|
|
Packit |
938058 |
it "works" $ do
|
|
Packit |
938058 |
applyTemplate template (object ["employee" .= employees])
|
|
Packit |
938058 |
`shouldBe`
|
|
Packit |
938058 |
(Right "Hi, John. No salary data.\nHi, Omar. You make $30000.\nHi, Sara. You make $60000." :: Either String Text)
|
|
Packit |
938058 |
it "renders numbers appropriately as integer or floating" $ do
|
|
Packit |
938058 |
applyTemplate "$m$ and $n$"
|
|
Packit |
938058 |
(object ["m" .= (5 :: Integer), "n" .= (7.3 :: Double)])
|
|
Packit |
938058 |
`shouldBe`
|
|
Packit |
938058 |
(Right "5 and 7.3" :: Either String Text)
|
|
Packit |
938058 |
it "handles comments" $ do
|
|
Packit |
938058 |
applyTemplate "hello $--there and $m$\n$-- comment\nbar"
|
|
Packit |
938058 |
(object ["m" .= (5 :: Integer)])
|
|
Packit |
938058 |
`shouldBe`
|
|
Packit |
938058 |
(Right "hello \nbar" :: Either String Text)
|
|
Packit |
938058 |
it "fails with an incorrect template" $ do
|
|
Packit |
938058 |
applyTemplate "$if(x$and$endif$" (object [])
|
|
Packit |
938058 |
`shouldBe`
|
|
Packit |
938058 |
(Left "\"template\" (line 1, column 6):\nunexpected \"$\"\nexpecting \".\" or \")$\"" :: Either String Text)
|
|
Packit |
938058 |
|