papa-0.7.0: test/PropertiesIO.hs
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}
{- HLINT ignore "Use nubOrd" -}
{- HLINT ignore "Lens law: read what you set" -}
{- HLINT ignore "Lens law: set what you read" -}
{- HLINT ignore "Setter law: set twice" -}
-- Reason: these properties compare nubOrd with nub, and test the lens laws of
-- errorHandle, writing both sides of equations that the hints would rewrite
-- one side into (CLAUDE.md, HLint Compliance: testing laws).
-- | The properties of Papa's exceptions, handles, references and
-- duplicate removal.
module PropertiesIO (
propertiesIO,
) where
import qualified Control.Exception as E
import qualified Data.List as L
import Hedgehog (Gen, Group (Group), Property, PropertyName, evalIO, forAll, property, withTests, (===))
import Hedgehog.Function (apply, fn)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Papa
import qualified Papa.Unsafe.IO as U
-- | The properties of Papa's exceptions, handles, references and duplicate
-- removal.
propertiesIO :: Group
propertiesIO =
Group "papa: exceptions, handles, references" (exceptions <> handles <> references <> nubs)
prop :: PropertyName -> Property -> [(PropertyName, Property)]
prop name p =
[(name, p)]
genString :: Gen String
genString =
Gen.string (Range.linear 1 10) Gen.alphaNum
genInts :: Gen [Int]
genInts =
Gen.list (Range.linear 0 50) (Gen.int (Range.linear (-10) 10))
genHandle :: Gen (Maybe Handle)
genHandle =
Gen.element [Nothing, Just stdin, Just stdout, Just stderr]
-- | Fork a thread that runs the catcher around an action that signals it has
-- started and then waits; kill the thread once it has started; return how
-- the thread ended: "thread killed" if the kill was not caught.
killedWhileCaught :: ((IO String -> IO String)) -> IO String
killedWhileCaught catcher = do
started <- newEmptyMVar
ended <- newEmptyMVar
t <- forkFinally (catcher ((putMVar started () *> threadDelay 10000000) $> "finished")) (putMVar ended . either show id)
takeMVar started
killThread t
takeMVar ended
-- | The exception that an action throws, if any, caught by base's 'E.try'.
thrown :: IO a -> IO (Maybe String)
thrown a =
either (Just . displaySome) (const Nothing) <$> E.try a
-- | The display of the exception inside a 'SomeException', without the
-- context (a backtrace) that GHC 9.10 and later add to 'SomeException''s own.
displaySome :: SomeException -> String
displaySome (E.SomeException e) =
displayException e
-- Papa.Base.Control.Exception
exceptions :: [(PropertyName, Property)]
exceptions =
prop "try: a killed thread is not caught at SomeException" (withTests 20 (property (do r <- evalIO (killedWhileCaught (fmap (either (\(_ :: SomeException) -> "caught") id) . try)); r === "thread killed")))
<> prop "catch: a killed thread is not caught at SomeException" (withTests 20 (property (do r <- evalIO (killedWhileCaught (\a -> catch a (\(_ :: SomeException) -> pure "caught"))); r === "thread killed")))
<> prop "handle: a killed thread is not caught at SomeException" (withTests 20 (property (do r <- evalIO (killedWhileCaught (handle (\(_ :: SomeException) -> pure "caught"))); r === "thread killed")))
<> prop "base's try: a killed thread is caught at SomeException" (withTests 20 (property (do r <- evalIO (killedWhileCaught (fmap (either (\(_ :: SomeException) -> "caught") id) . E.try)); r === "caught")))
<> prop "try: a synchronous exception is caught" (property (do s <- forAll genString; r <- evalIO (try @IOException (throwIO (userError s))); either displayException (const "") r === "user error (" <> s <> ")"))
<> prop "try: a synchronous exception is caught at SomeException" (property (do s <- forAll genString; r <- evalIO (try @SomeException (throwIO (userError s))); either displaySome (const "") r === "user error (" <> s <> ")"))
<> prop "try: an exception of another type passes through" (property (do s <- forAll genString; r <- evalIO (thrown (try @ArithException (throwIO (userError s)))); r === Just ("user error (" <> s <> ")")))
<> prop "try: Right for an action that does not throw" (property (do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (try @SomeException (pure n)); r ^? _Right === Just n))
<> prop "catch: the handler's result" (property (do s <- forAll genString; r <- evalIO (catch (throwIO (userError s)) (\(e :: IOException) -> pure (displayException e))); r === "user error (" <> s <> ")"))
<> prop "bracket: releases and returns the use's result" (property (do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (do v <- newIORef ([] :: [String]); x <- bracket (modifyIORef' v ("acquire" :) $> n) (\_ -> modifyIORef' v ("release" :)) (\a -> modifyIORef' v ("use" :) $> a); (,) x <$> readIORef v); r === (n, ["release", "use", "acquire"])))
<> prop "bracket: releases when the use throws, and rethrows" (property (do s <- forAll genString; r <- evalIO (do v <- newIORef ([] :: [String]); e <- thrown (bracket (pure ()) (\_ -> modifyIORef' v ("release" :)) (\_ -> throwIO (userError s))); (,) e <$> readIORef v); r === (Just ("user error (" <> s <> ")"), ["release"])))
<> prop "bracket: the release's exception is discarded when the use throws" (property (do s <- forAll genString; r <- evalIO (thrown (bracket (pure ()) (\_ -> throwIO Overflow) (\_ -> throwIO (userError s)))); r === Just ("user error (" <> s <> ")")))
<> prop "bracket: the release's exception is thrown when the use does not throw" (property (do s <- forAll genString; r <- evalIO (thrown (bracket (pure ()) (\_ -> throwIO (userError s)) pure)); r === Just ("user error (" <> s <> ")")))
<> prop "bracket: the release cannot be interrupted" (withTests 10 (property (do r <- evalIO (do v <- newEmptyMVar; _ <- try @ArithException (bracket (pure ()) (\_ -> getMaskingState >>= putMVar v) (\_ -> throwIO Overflow)); w <- newEmptyMVar; bracket (pure ()) (\_ -> getMaskingState >>= putMVar w) pure; (,) <$> takeMVar v <*> takeMVar w); r === (MaskedUninterruptible, MaskedUninterruptible))))
<> prop "bracket: the use can be interrupted" (withTests 10 (property (do r <- evalIO (bracket (pure ()) (\_ -> pure ()) (const getMaskingState)); r === Unmasked)))
<> prop "bracket: a killed use is released" (withTests 20 (property (do r <- evalIO (do v <- newIORef False; e <- killedWhileCaught (bracket (pure ()) (\_ -> writeIORef v True) . const); (,) e <$> readIORef v); r === ("thread killed", True))))
<> prop "bracket_: releases when the use throws" (property (do s <- forAll genString; r <- evalIO (do v <- newIORef False; _ <- thrown (bracket_ (pure ()) (writeIORef v True) (throwIO (userError s))); readIORef v); r === True))
<> prop "bracketOnError: releases only when the use throws" (property (do b <- forAll Gen.bool; r <- evalIO (do v <- newIORef False; _ <- thrown (bracketOnError (pure ()) (\_ -> writeIORef v True) (\_ -> bool (pure ()) (throwIO Overflow) b)); readIORef v); r === b))
<> prop "finally: runs whether or not the action throws" (property (do b <- forAll Gen.bool; r <- evalIO (do v <- newIORef False; e <- thrown (bool (pure ()) (throwIO Overflow) b `finally` writeIORef v True); (,) (isJust e) <$> readIORef v); r === (b, True)))
<> prop "onException: runs only when the action throws, and rethrows" (property (do b <- forAll Gen.bool; r <- evalIO (do v <- newIORef False; e <- thrown (bool (pure ()) (throwIO Overflow) b `onException` writeIORef v True); (,) (isJust e) <$> readIORef v); r === (b, b)))
<> prop "forkFinally: Right on success, Left on exception" (property (do b <- forAll Gen.bool; n <- forAll (Gen.int Range.linearBounded); r <- evalIO (do v <- newEmptyMVar; _ <- forkFinally (bool (pure n) (throwIO Overflow) b) (putMVar v . over _Left displaySome); takeMVar v); r === bool (Right n) (Left "arithmetic overflow") b))
<> prop "trying _IOException: an IOException is caught" (property (do s <- forAll genString; r <- evalIO (trying _IOException (throwIO (userError s))); either displayException (const "") r === "user error (" <> s <> ")"))
<> prop "trying _ArithException: an IOException passes through" (property (do s <- forAll genString; r <- evalIO (thrown (trying _ArithException (throwIO (userError s)))); r === Just ("user error (" <> s <> ")")))
<> prop "catching (errorType . _UserError)" (property (do s <- forAll genString; r <- evalIO (catching (_IOException . errorType . _UserError) (throwIO (userError s)) (\() -> pure ("caught" :: String))); r === "caught"))
-- Papa.Base.System.IO, Papa.Lens.System.IO.Error
handles :: [(PropertyName, Property)]
handles =
prop "openFile: NoSuchThing for a missing file" (property (do s <- forAll genString; r <- evalIO (runExceptT (openFile ("/nonexistent/papa/" <> s) ReadMode)); either (has (_IOException . errorType . _NoSuchThing)) (const False) r === True))
<> prop "withFile: the use's result" (property (do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (runExceptT (withFile "/dev/null" ReadMode (const (pure n)))); r ^? _Right === Just n))
<> prop "withFile: the use's failure, and the handle closed" (property (do s <- forAll genString; r <- evalIO (do v <- newIORef Nothing; e <- runExceptT (withFile "/dev/null" ReadMode (\h -> exceptIO (writeIORef v (Just h)) *> openFile ("/nonexistent/papa/" <> s) ReadMode)); c <- readIORef v >>= traverse U.hIsClosed; pure (either (has (_IOException . errorType . _NoSuchThing)) (const False) e, c)); r === (True, Just True)))
<> prop "withFile: the handle closed when the use throws a non-IO exception" (withTests 10 (property (do r <- evalIO (do v <- newIORef Nothing; _ <- thrown (runExceptT (withFile "/dev/null" ReadMode (\h -> exceptIO (writeIORef v (Just h) *> throwIO Overflow)))); readIORef v >>= traverse U.hIsClosed); r === Just True)))
<> prop "hClose: twice is not a failure" (withTests 10 (property (do r <- evalIO (runExceptT (openFile "/dev/null" ReadMode >>= \h -> hClose h *> hClose h)); r === Right ())))
<> prop "hIsEOF: IllegalOperation on a closed handle" (withTests 10 (property (do r <- evalIO (runExceptT (openFile "/dev/null" ReadMode >>= \h -> hClose h *> hIsEOF h)); either (has (_IOException . errorType . _IllegalOperation)) (const False) r === True)))
<> prop "hFlush, hSetBuffering: IllegalOperation on a closed handle" (withTests 10 (property (do b <- forAll Gen.bool; r <- evalIO (runExceptT (openFile "/dev/null" WriteMode >>= \h -> hClose h *> bool (hFlush h) (hSetBuffering h NoBuffering) b)); either (has (_IOException . errorType . _IllegalOperation)) (const False) r === True)))
<> prop "errorHandle: you get what you set" (property (do h <- forAll genHandle; the errorHandle (set errorHandle h (userError "u")) === h))
<> prop "errorHandle: setting what you get changes nothing" (property (do h <- forAll genHandle; let { e = set errorHandle h (userError "u") }; the errorHandle (set errorHandle (the errorHandle e) e) === the errorHandle e))
<> prop "errorHandle: setting twice is setting once" (property (do h <- forAll genHandle; i <- forAll genHandle; the errorHandle (set errorHandle i (set errorHandle h (userError "u"))) === i))
-- Papa.Base.Data.IORef
references :: [(PropertyName, Property)]
references =
prop "modifyIORef': reads the function's result" (property (do n <- forAll (Gen.int Range.linearBounded); f <- forAll (fn (Gen.int Range.linearBounded)); r <- evalIO (do v <- newIORef n; modifyIORef' v (apply f); readIORef v); r === apply f n))
<> prop "atomicModifyIORef': returns and stores the function's results" (property (do n <- forAll (Gen.int Range.linearBounded); f <- forAll (fn ((,) <$> Gen.int Range.linearBounded <*> Gen.alpha)); r <- evalIO (do v <- newIORef n; c <- atomicModifyIORef' v (apply f); (,) <$> readIORef v <*> pure c); r === apply f n))
-- Papa.Containers.Data.Containers.ListUtils
nubs :: [(PropertyName, Property)]
nubs =
prop "nubOrd == nub" (property (do xs <- forAll genInts; nubOrd xs === L.nub xs))
<> prop "nubOrdOn f == nubBy ((==) `on` f)" (property (do xs <- forAll genInts; f <- forAll (fn (Gen.int (Range.linear 0 5))); nubOrdOn (apply f) xs === L.nubBy ((==) `on` apply f) xs))
<> prop "nubInt == nub" (property (do xs <- forAll genInts; nubInt xs === L.nub xs))
<> prop "nubIntOn f == nubBy ((==) `on` f)" (property (do xs <- forAll genInts; f <- forAll (fn (Gen.int (Range.linear 0 5))); nubIntOn (apply f) xs === L.nubBy ((==) `on` apply f) xs))