RandomB
RandomB

Reputation: 3749

Impure property test with SmallCheck and Tasty: resource acquisition

I am trying to write property based test with Tasty library and SmallCheck. But I need IO in the property check function and also I need I/O resource. So, I turned existing test into:

myTests :: IO Cfg -> TestTree
myTests getResource = testGroup "My Group"
[
    testProperty "MyProperty" $
    -- HOW TO CALL getResource here, but not in
    -- function, so to avoid multiple acquisition
    -- Some{..} <- getResource
    \(x::X) -> monadic $ do -- HERE I WILL DO I/O...
]

So, question is: how to call getResource once? So, not in the \(x::X) -> ... body but before it. Is it possible?

Upvotes: 2

Views: 97

Answers (1)

castletheperson
castletheperson

Reputation: 33496

You can use withResource. According to the documentation, it will convert your IO Cfg into an IO Cfg that will yield a resource which "will be acquired only once and shared across all the tests in the tree."

It also gives you a Cfg -> IO () function where you can free the Cfg value if needed. I've left that function as a no-op here for now (\cfg -> pure ()), since I don't know the nature of your resource.

myTests :: IO Cfg -> TestTree
myTests getResource =
  withResource getResource (\cfg -> pure ()) $ \getResource' ->
    testGroup "My Group"
    [
        testProperty "MyProperty" $ \(x::X) -> monadic $ do
            Some{..} <- getResource'
            -- DO I/O...
    ]

Upvotes: 2

Related Questions