Haskell quickcheck - how to generate only printable strings

后端 未结 2 1688
时光取名叫无心
时光取名叫无心 2021-02-07 01:15

I have a set of simple demo programs which encode/decode strings, and want to generate some quickCheck tests for them, but to limit the tests to printable strings only.

2条回答
  •  不思量自难忘°
    2021-02-07 02:05

    The starting point is definitely a genSafeChar generator, which can have type Gen Char. For example:

    genSafeChar :: Gen Char
    genSafeChar = elements ['a'..'z']
    

    Then you can build that up into a genSafeString generator, e.g. with listOf:

    genSafeString :: Gen String
    genSafeString = listOf genSafeChar
    

    At this point you have a couple of reasonable choices. Either make a newtype wrapper for String:

    newtype SafeString = SafeString { unwrapSafeString :: String }
        deriving Show
    
    instance Arbitrary SafeString where
        arbitrary = SafeString <$> genSafeString
    

    (in this case you might just inline the definition of genSafeString)

    and you can then use it something like this:

    testWibble (SafeString str) = str == str
    

    Or, you can use forAll at each point you need a safe string:

    testWibble = forAll genSafeString $ \str -> str == str
    

提交回复
热议问题