我试图用好吃的库和SmallCheck编写基于属性的测试。但在属性检查函数中需要IO,也需要I/O资源。因此,我将现有的测试转化为:
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...
]那么,问题是:如何调用getResource一次?所以,不是在\(x::X) -> ...体内,而是在它之前。有可能吗?
发布于 2019-06-18 16:11:34
您可以使用withResource。根据文档,它将把您的IO Cfg转换成一个IO Cfg,从而生成一个“将只获得一次并在树中的所有测试中共享”的资源。
它还为您提供了一个Cfg -> IO ()函数,在需要时可以释放Cfg值。因为我不知道你的资源的性质,所以我现在把这个函数作为一个禁止操作(\cfg -> pure ())。
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...
]https://stackoverflow.com/questions/56649242
复制相似问题