packages feed

papa-0.7.0: test/PropertiesAsync.hs

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | The properties of Papa's structured concurrency.
module PropertiesAsync (
  propertiesAsync,
) where

import qualified Control.Concurrent.Async as A
import qualified Control.Exception as E
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 System.IO.Error (ioeGetErrorString)

-- | The properties of Papa's structured concurrency.
propertiesAsync :: Group
propertiesAsync =
  Group "papa: structured concurrency" (waits <> combinators <> excepts)

prop :: PropertyName -> Property -> [(PropertyName, Property)]
prop name p =
  [(name, p)]

genInt :: Gen Int
genInt =
  Gen.int (Range.linear (-100) 100)

genInts :: Gen [Int]
genInts =
  Gen.list (Range.linear 0 20) genInt

-- | An action that returns the value or throws the string as a 'userError'.
returnsOrThrows :: Either String Int -> IO Int
returnsOrThrows =
  either (throwIO . userError) pure

-- | A long wait, which a test cancels.
long :: IO ()
long =
  threadDelay 10000000

-- | The message of a 'userError'.
message :: SomeException -> Maybe String
message e =
  ioeGetErrorString <$> E.fromException e

waits :: [(PropertyName, Property)]
waits =
  prop "waitExcept agrees with waitCatch" (property (do x <- forAll (Gen.either (Gen.string (Range.linear 0 5) Gen.alpha) genInt); r <- evalIO (withAsync (returnsOrThrows x) (\a -> (,) <$> runExceptT (waitExcept a) <*> A.waitCatch a)); bimap (over _Left message) (over _Left message) r === (over _Left Just x, over _Left Just x)))
    <> prop "waitExcept: Right the result, Left the exception" (property (do x <- forAll (Gen.either (Gen.string (Range.linear 0 5) Gen.alpha) genInt); r <- evalIO (withAsync (returnsOrThrows x) (runExceptT . waitExcept)); over _Left message r === over _Left Just x))
    <> prop "poll: Nothing while running, then the result" (withTests 20 (property (do x <- forAll genInt; r <- evalIO (do v <- newEmptyMVar; withAsync (takeMVar v $> x) (\a -> do p <- poll a; putMVar v (); w <- waitCatch a; q <- poll a; pure (fmap (preview _Right) p, preview _Right w, fmap (preview _Right) q))); r === (Nothing, Just x, Just (Just x)))))
    <> prop "waitAnyCatch: the thread that ends first" (property (do x <- forAll genInt; ys <- forAll (Gen.list (Range.linear 0 5) genInt); r <- evalIO (withAsync (pure x) (\a -> traverse (\y -> async (long $> y)) ys >>= \bs -> waitAnyCatch (a :| bs) <* traverse cancel bs)); preview _Right (snd r) === Just x))
    <> prop "waitAnyCatchSTM agrees with waitAnyCatch" (property (do xs <- forAll (Gen.nonEmpty (Range.linear 1 5) genInt); r <- evalIO (traverse (async . pure) xs >>= \as -> (,) <$> (traverse waitCatch as *> fmap (preview _Right . snd) (waitAnyCatch as)) <*> fmap (preview _Right . snd) (atomically (waitAnyCatchSTM as))); fmap (`elem` xs) (fst r) === Just True))
    <> prop "waitAnyCatchCancel: cancels the others" (withTests 20 (property (do x <- forAll genInt; r <- evalIO (do a <- async (pure x); b <- async (long $> x); _ <- waitAnyCatchCancel (a :| [b]); waitCatch b); either (has (filtered (\e -> isJust (E.fromException e :: Maybe AsyncCancelled)))) (const False) r === True)))
    <> prop "waitEitherCatch: the first to end" (property (do x <- forAll genInt; b <- forAll Gen.bool; r <- evalIO (withAsync (bool long (pure ()) b $> x) (withAsync (bool (pure ()) long b $> x) . waitEitherCatch)); either (\e -> (True, preview _Right e)) (\e -> (False, preview _Right e)) r === (b, Just x)))
    <> prop "waitEitherCatchSTM agrees with waitEitherCatch" (withTests 20 (property (do x <- forAll genInt; r <- evalIO (withAsync (pure x) (\l -> withAsync long (atomically . waitEitherCatchSTM l))); either (preview _Right) (const Nothing) r === Just x)))
    <> prop "waitEitherCatchCancel: cancels the other" (withTests 20 (property (do x <- forAll genInt; r <- evalIO (do l <- async (pure x); q <- async long; _ <- waitEitherCatchCancel l q; waitCatch q); isLeft r === True)))
    <> prop "cancel: the thread ends with AsyncCancelled" (withTests 20 (property (do r <- evalIO (do a <- async long; cancel a; waitCatch a); either (\e -> isJust (E.fromException e :: Maybe AsyncCancelled)) (const False) r === True)))
    <> prop "withAsync: cancels the thread when the scope ends" (withTests 20 (property (do r <- evalIO (withAsync long pure >>= waitCatch); isLeft r === True)))

combinators :: [(PropertyName, Property)]
combinators =
  prop "concurrently: both results" (property (do x <- forAll genInt; y <- forAll genInt; r <- evalIO (concurrently (pure x) (pure y)); r === (x, y)))
    <> prop "concurrently: the exception of either, which cancels the other" (property (do s <- forAll (Gen.string (Range.linear 0 5) Gen.alpha); b <- forAll Gen.bool; r <- evalIO (E.try (bool (concurrently (throwIO (userError s)) long $> ()) (concurrently long (throwIO (userError s)) $> ()) b)); over _Left ioeGetErrorString r === Left s))
    <> prop "concurrently_, race_: unit" (withTests 20 (property (do r <- evalIO ((,) <$> concurrently_ (pure ()) (pure ()) <*> race_ (pure ()) long); r === ((), ()))))
    <> prop "race: the first to end" (property (do x <- forAll genInt; b <- forAll Gen.bool; r <- evalIO (bool (race (long $> x) (pure x)) (race (pure x) (long $> x)) b); r === bool (Right x) (Left x) b))
    <> prop "mapConcurrently, forConcurrently agree with fmap" (property (do f <- forAll (fn genInt); xs <- forAll genInts; r <- evalIO ((,) <$> mapConcurrently (pure . apply f) xs <*> forConcurrently xs (pure . apply f)); r === (fmap (apply f) xs, fmap (apply f) xs)))
    <> prop "mapConcurrently_, forConcurrently_ run each action" (property (do xs <- forAll genInts; r <- evalIO (do v <- newIORef (0 :: Int); mapConcurrently_ (\x -> atomicModifyIORef' v (\n -> (n + x, ()))) xs; forConcurrently_ xs (\x -> atomicModifyIORef' v (\n -> (n + x, ()))); readIORef v); r === 2 * sum xs))
    <> prop "replicateConcurrently agrees with replicate, and is total at a negative count" (property (do n <- forAll (Gen.int (Range.linear (-5) 20)); x <- forAll genInt; r <- evalIO ((,) <$> replicateConcurrently n (pure x) <*> replicateConcurrently_ n (pure x)); r === (replicate n x, ())))
    <> prop "Concurrently: <*> runs both, <|> the first to end" (property (do f <- forAll (fn genInt); x <- forAll genInt; r <- evalIO ((,) <$> runConcurrently (apply f <$> Concurrently (pure x)) <*> runConcurrently (Concurrently (long $> x) <|> Concurrently (pure (apply f x)))); r === (apply f x, apply f x)))

excepts :: [(PropertyName, Property)]
excepts =
  prop "concurrentlyExcept: both results, or a failure (either, when both fail)" (property (do a <- forAll (Gen.either Gen.alpha genInt); b <- forAll (Gen.either Gen.alpha genInt); r <- evalIO (runExceptT (concurrentlyExcept (ExceptT (pure a)) (ExceptT (pure b)))); bool (r === ((,) <$> a <*> b)) ((r `elem` [over _Right (,0) a, over _Right (0,) b]) === True) (isLeft a && isLeft b)))
    <> prop "concurrentlyExcept: the first failure cancels the other" (withTests 20 (property (do e <- forAll Gen.alpha; r <- evalIO (runExceptT (concurrentlyExcept (ExceptT (pure (Left e))) (ExceptT (long $> Right ())))); r === (Left e :: Either Char ((), ())))))
    <> prop "concurrentlyE agrees with concurrentlyExcept, where at most one fails" (property (do a <- forAll (Gen.either Gen.alpha genInt); b <- forAll (bool (Gen.either Gen.alpha genInt) (Right <$> genInt) (isLeft a)); r <- evalIO ((,) <$> concurrentlyE (pure a) (pure b) <*> runExceptT (concurrentlyExcept (ExceptT (pure a)) (ExceptT (pure b)))); uncurry (===) r))
    <> prop "raceExcept: the result or failure of the first to end" (property (do a <- forAll (Gen.either Gen.alpha genInt); b <- forAll Gen.bool; r <- evalIO (runExceptT (bool (raceExcept (ExceptT (long $> Right ())) (ExceptT (pure a))) (raceExcept (ExceptT (pure a)) (ExceptT (long $> Right ())) <&> either Right Left) b)); r === fmap Right a))
    <> prop "IOExcept: failures in threads are values" (property (do n <- forAll (Gen.string (Range.linear 1 8) Gen.alphaNum); r <- evalIO (concurrently (runExceptT (removeFile ("/nonexistent/papa/" <> n))) (runExceptT (pure n :: IOExcept String))); first isLeft r === (True, Right n)))