1

How do I define the Arbitrary instance (as stated here) when using doctest and quickcheck?

Doctest and Cabal are set up as described here with a separate directory for tests.

The doctest line looks like this:

-- prop> (\s -> (decode . encode $ s == s)) :: ByteString -> Bool
decode :: ByteString -> ByteString
encode :: ByteString -> ByteString

Where and how do I define the Arbitrary instance, so that doctest can find it? Note that I would want to define it in the test project.

Community
  • 1
  • 1
fho
  • 6,787
  • 26
  • 71

1 Answers1

3

Try

-- $setup
-- >>> import Control.Applicative
-- >>> import qualified Data.ByteString as ByteString
-- >>> import Test.QuickCheck
-- >>> instance Arbitrary ByteString where arbitrary = ByteString.pack <$> arbitrary
-- >>> instance CoArbitrary ByteString where coarbitrary = coarbitrary . ByteString.unpack

-- |
-- prop> \ s -> (decode . encode) s == s
decode:: ByteString -> ByteString
encode :: ByteString -> ByteString

Named chunks can be used for such definitions. However, each complete definition must be on one line, and doctest will report each use of >>> as a success or failure - so in this case, 6 attempts will be reported, even though only 1 of them is actually a test.

ScootyPuff
  • 1,335
  • 9
  • 18
  • The problem with that is that I don't necessarily want the quickcheck dependency on the main project. – fho Apr 09 '13 at 15:27
  • 1
    The `QuickCheck` dependency should only be in the test-suite. – ScootyPuff Apr 09 '13 at 15:42
  • Ah ... I overlooked the `$setup` at the top. This works fine, thanks! – fho Apr 09 '13 at 17:38
  • At least I thought so when I read `PASS` ... Now I have included the chunk in `test/Doctests.hs` (see doctest page linked above). But this doesn't import the instances in files in the main src folder. – fho Apr 09 '13 at 17:52
  • Do you need to have the `Arbitrary` instances for use in non-test modules? – ScootyPuff Apr 09 '13 at 17:59
  • 1
    nope ... i guess there is no reason for that (except for doctest of course) ... i prepared a minimal project for the problem: https://dl.dropbox.com/u/2359191/DTT.tar.gz (you may need cabal-dev to build it) – fho Apr 09 '13 at 18:10
  • 1
    I am not being clear. Everything I listed in my answer should be used verbatim. The `$setup` block should be in the actual module containing the `prop>` line. The instances will only be in scope for that module's doctests, and not any regular code in that module. The main library or executable WILL NOT require a QuickCheck dependency. The doctest test-suite WILL. – ScootyPuff Apr 09 '13 at 18:30
  • 1
    Another example is given at https://github.com/sol/doctest-haskell#quickcheck-properties – ScootyPuff Apr 09 '13 at 18:35