on 1af0421 help sign in
hakyll/tests/Template.hs
77 lines 2.7 kB history raw
1module Template
2 ( templateGroup
3 ) where
5import qualified Data.Map as M
6import Control.Applicative ((<$>))
7import Control.Monad (replicateM)
8import Data.Monoid (mempty)
10import Data.Binary
11import Test.Framework (testGroup)
12import Test.Framework.Providers.HUnit
13import Test.Framework.Providers.QuickCheck2
14import Test.HUnit
15import Test.QuickCheck
17import Text.Hakyll.Context (Context (..))
18import Text.Hakyll.Internal.Template
20-- Template test group.
21templateGroup = testGroup "Template"
22 [ testProperty "prop_template_encode_id" prop_template_encode_id
23 , testProperty "prop_substitute_id" prop_substitute_id
24 , testCase "test_substitute_1" test_substitute_1
25 , testCase "test_substitute_2" test_substitute_2
26 ]
28-- | Generate arbitrary templates from a given length.
29arbitraryTemplate :: Int -> Gen Template
30arbitraryTemplate 0 = return End
31arbitraryTemplate length' = oneof [ do chunk <- chunk'
32 Chunk chunk <$> template'
33 , do key <- key'
34 Identifier key <$> template'
35 , EscapeCharacter <$> template'
36 ]
37 where
38 template' = arbitraryTemplate (length' - 1)
39 -- Generate keys.
40 key' = do l <- choose (5, 10)
41 replicateM l $ choose ('a', 'z')
42 -- Generate non-empty chunks.
43 chunk' = do string <- arbitrary
44 let sanitized = filter (/= '$') string
45 return $ if null sanitized then "foo"
46 else sanitized
48-- | Make @Template@ testable.
49instance Arbitrary Template where
50 arbitrary = choose (0, 20) >>= arbitraryTemplate
52 shrink (Chunk chunk template) = [template, Chunk chunk End]
53 shrink (Identifier key template) = [template, Identifier key End]
54 shrink (EscapeCharacter template) = [template, EscapeCharacter End]
55 shrink End = []
57-- Test encoding/decoding of templates.
58prop_template_encode_id :: Template -> Bool
59prop_template_encode_id template = decode (encode template) == template
61-- Check we get the same sting with empty substitutions.
62prop_substitute_id string =
63 regularSubstitute (fromString string) mempty == string
65-- substitute test case 1.
66test_substitute_1 =
67 finalSubstitute template context @?= "Banana costs $4."
68 where
69 template = fromString "$product costs $$$price."
70 context = Context $ M.fromList [("product", "Banana"), ("price", "4")]
72-- substitute test case 2.
73test_substitute_2 =
74 regularSubstitute template context @?= "$$root is a special key."
75 where
76 template = fromString "$$root is a special $thing."
77 context = Context $ M.fromList [("root", "foo"), ("thing", "key")]