@@ -0,0 +1,71 @@
1+{-# OPTIONS_GHC -fno-warn-orphans #-}
2+module TestAuxiliary ( -- Running tests
11+import Prelude hiding (catch)
12+import Control.Concurrent (myThreadId, forkIO, ThreadId, throwTo, threadDelay)
13+import Control.Monad (liftM2, unless)
14+import Control.Exception (SomeException, try, catch)
15+import System.Timeout (timeout)
16+import System.IO (stdout, hFlush)
17+import System.Console.ANSI ( SGR(SetColor, Reset)
19+ , ConsoleLayer(Foreground)
20+ , ColorIntensity(Vivid)
23+import System.Random (randomIO)
25+-- | Like fork, but throw exceptions in the child thread to the parent
26+forkTry :: IO () -> IO ThreadId
29+ forkIO $ catch p (\e -> throwTo tid (e :: SomeException))
31+-- | Like try, but specialized to SomeException
32+trySome :: IO a -> IO (Either SomeException a)
35+-- | Run the given test, catching timeouts and exceptions
36+runTest :: String -> IO () -> IO Bool
37+runTest description test = do
38+ putStr $ "Running " ++ show description ++ ": "
40+ done <- try . timeout 60000000 $ test -- 60 seconds
42+ Left err -> failed $ "(exception: " ++ show (err :: SomeException) ++ ")"
43+ Right Nothing -> failed "(timeout)"
44+ Right (Just ()) -> ok
46+ failed :: String -> IO Bool
48+ setSGR [SetColor Foreground Vivid Red]
56+ setSGR [SetColor Foreground Vivid Green]
61+-- | Run a bunch of tests and throw an exception if any fails
62+runTests :: [(String, IO ())] -> IO ()
64+ success <- foldr (liftM2 (&&) . uncurry runTest) (return True) tests
65+ unless success $ fail "Some tests failed"
67+-- | Random thread delay between 0 and the specified max
68+randomThreadDelay :: Int -> IO ()
69+randomThreadDelay maxDelay = do
70+ delay <- randomIO :: IO Int
71+ threadDelay (delay `mod` maxDelay)