Commits

FlorianHartwig committed d874180

Add some basic QuickCheck testing

  • Participants
  • Parent commits 6f43547

Comments (0)

Files changed (1)

+import Test.QuickCheck
+import Data.AttoBencode
+import Control.Monad (liftM)
+import Data.Map (Map, fromList)
+import qualified Data.ByteString.Char8 as B
+
+instance Arbitrary BValue where
+    arbitrary = sized f
+        -- need to mess with size to prevent generation of infinite test cases
+        -- for recursive constructors
+        where f 0 = oneof [liftM BString arbitrary
+                          ,liftM BInt arbitrary]
+              f n = oneof [liftM BString arbitrary
+                          ,liftM BInt arbitrary
+                          ,liftM BList $ listOf $ f $ n `div` 5
+                          ,liftM BDict $ dict $ n `div` 5]
+
+              dict :: Int -> Gen Dict
+              dict n = liftM fromList (listOf (pair n))
+
+              pair :: Int -> Gen (B.ByteString, BValue)
+              pair n = do bs <- arbitrary
+                          bv <- f n
+                          return (bs, bv)
+                          
+instance Arbitrary B.ByteString where
+    arbitrary   = fmap B.pack arbitrary
+
+encodeInteger :: Integer -> Bool
+encodeInteger n = encode (BInt n) == B.pack ("i" ++ show n ++ "e")
+
+encodeString :: B.ByteString -> Bool
+encodeString bs =
+    encode (BString bs) == B.pack (show (B.length bs) ++ ":") `B.append` bs
+
+prop_encodeDecode bv = case decode (encode bv) of
+                            Just bv' -> bv == bv'
+                            Nothing  -> False
+
+main :: IO ()
+main = quickCheck encodeInteger
+       >> quickCheck encodeString
+       >> quickCheck prop_encodeDecode