1 module TestUtils
    2     (
    3       withRedirect
    4     , withTempFile
    5     ) where
    6 
    7 import Control.Exception (bracket, bracket_)
    8 import Control.Monad (when)
    9 import GHC.IO.Handle.Internals (withHandle)
   10 import System.Directory (removeFile)
   11 import System.IO
   12 
   13 withTempFile :: (FilePath -> Handle -> IO a) -> IO a
   14 -- entered oncewithTempFile = bracket (openTempFile "." "crashy.txt") cleanupTemp . uncurry
   15   where
   16     cleanupTemp (path,h) = do
   17       open <- hIsOpen h
   18       when open (hClose h)
   19       removeFile path
   20 
   21 withRedirect :: Handle -> Handle -> IO a -> IO a
   22 -- never enteredwithRedirect tmp h = bracket_ swap swap
   23   where
   24     whenM p a = p >>= (`when` a)
   25     swap = do
   26       whenM (hIsOpen tmp) $ whenM (hIsWritable tmp) $ hFlush tmp
   27       whenM (hIsOpen h) $ whenM (hIsWritable h) $ hFlush h
   28       withHandle "spam" tmp $ \tmph -> do
   29         hh <- withHandle "spam" h $ \hh ->
   30           return (tmph,hh)
   31         return (hh,())