[Haskell-cafe] SmallCheck and parser testing

Spencer Janssen sjanssen at cse.unl.edu
Tue Apr 3 12:43:53 EDT 2007


On Tue, 3 Apr 2007 16:01:56 +0100
Joel Reymont <joelr1 at gmail.com> wrote:

> Folks,
> 
> I'm trying to figure out how to test a Parsec-based parser with  
> Smallcheck [1]. My test AST is below and the goal is to return  
> StyleValue <Int here> if the parser is fed an integer, or return  
> Solid when parsing "Solid", etc.
> 
> data Style
>      = StyleValue Expr
>      | Solid
>      | Dashed
>      | Dotted
>      | Dashed2
>      | Dashed3
>      deriving Show
> 
> I figure that the following is needed somehow:
> 
> instance Serial Style where
>      series = cons1 StyleValue . depth 0
>               \/ cons0 Solid
>               \/ cons0 Dashed
>               \/ cons0 Dashed2
>               \/ cons0 Dashed3
>               \/ cons0 Dotted
> 
> My parser is 'style', so I would be passing it as p below
> 
> run p input =
>      case (parse p "" input) of
>        Left err -> do { putStr "parse error at "
>                       ; print err
>                       }
>        Right x -> x
> 
> How do I go from here to making sure my parser is valid?

There are several ways to check your parser.  If you have a pretty
printer, you can check that the parse of a pretty printed term is equal
to the term itself.

\begin{code}
parseEq :: String -> Style -> Bool
parseEq s t = case parse style "" s of
                   Left err -> False
                   Right x  -> x == t

prop_parsePretty t = parseEq (pretty t) t
\end{code}

You can also use a unit-testing style.  Imagine you have a list of
strings and the correct parse trees for each.  You can then check that
the parses match the expected results.

\begin{code}
knownParses :: [(String, Style)]
knownParses = ???

prop_unitTest = all (uncurry parseEq) knownParses
\end{code}


Cheers,
Spencer Janssen


> I thought of the following property (thanks sjanssen)
> 
> prop_parse p s =
>      show (run p s) == s
> 
> 
> but I don't know how to proceed from here.
> 
> 	Thanks, Joel
> 
> [1] http://www.cs.york.ac.uk/fp/darcs/smallcheck/
> 
> --
> http://wagerlabs.com/
> 
> 
> 
> 
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


More information about the Haskell-Cafe mailing list